// Global contact modal — single instance mounted once; any button opens it via
// window.openContactModal(source, variant) or dispatching a 'wo:open-contact' event.
// Two modes:
//   variant: 'contact'  → Name + Email + Message
//   variant: 'callback' → Name + Phone (with country code) + Convenient time + optional Email + Message

const COUNTRY_CODES = [
  { c: 'CY', n: 'Cyprus',         d: '+357', f: '🇨🇾' },
  { c: 'GB', n: 'United Kingdom', d: '+44',  f: '🇬🇧' },
  { c: 'US', n: 'United States',  d: '+1',   f: '🇺🇸' },
  { c: 'CA', n: 'Canada',         d: '+1',   f: '🇨🇦' },
  { c: 'UA', n: 'Ukraine',        d: '+380', f: '🇺🇦' },
  { c: 'DE', n: 'Germany',        d: '+49',  f: '🇩🇪' },
  { c: 'FR', n: 'France',         d: '+33',  f: '🇫🇷' },
  { c: 'ES', n: 'Spain',          d: '+34',  f: '🇪🇸' },
  { c: 'IT', n: 'Italy',          d: '+39',  f: '🇮🇹' },
  { c: 'NL', n: 'Netherlands',    d: '+31',  f: '🇳🇱' },
  { c: 'BE', n: 'Belgium',        d: '+32',  f: '🇧🇪' },
  { c: 'AT', n: 'Austria',        d: '+43',  f: '🇦🇹' },
  { c: 'CH', n: 'Switzerland',    d: '+41',  f: '🇨🇭' },
  { c: 'SE', n: 'Sweden',         d: '+46',  f: '🇸🇪' },
  { c: 'NO', n: 'Norway',         d: '+47',  f: '🇳🇴' },
  { c: 'DK', n: 'Denmark',        d: '+45',  f: '🇩🇰' },
  { c: 'FI', n: 'Finland',        d: '+358', f: '🇫🇮' },
  { c: 'IE', n: 'Ireland',        d: '+353', f: '🇮🇪' },
  { c: 'PT', n: 'Portugal',       d: '+351', f: '🇵🇹' },
  { c: 'PL', n: 'Poland',         d: '+48',  f: '🇵🇱' },
  { c: 'CZ', n: 'Czechia',        d: '+420', f: '🇨🇿' },
  { c: 'RO', n: 'Romania',        d: '+40',  f: '🇷🇴' },
  { c: 'BG', n: 'Bulgaria',       d: '+359', f: '🇧🇬' },
  { c: 'GR', n: 'Greece',         d: '+30',  f: '🇬🇷' },
  { c: 'HU', n: 'Hungary',        d: '+36',  f: '🇭🇺' },
  { c: 'HR', n: 'Croatia',        d: '+385', f: '🇭🇷' },
  { c: 'RS', n: 'Serbia',         d: '+381', f: '🇷🇸' },
  { c: 'TR', n: 'Turkey',         d: '+90',  f: '🇹🇷' },
  { c: 'IL', n: 'Israel',         d: '+972', f: '🇮🇱' },
  { c: 'AE', n: 'UAE',            d: '+971', f: '🇦🇪' },
  { c: 'SA', n: 'Saudi Arabia',   d: '+966', f: '🇸🇦' },
  { c: 'GE', n: 'Georgia',        d: '+995', f: '🇬🇪' },
  { c: 'AM', n: 'Armenia',        d: '+374', f: '🇦🇲' },
  { c: 'AZ', n: 'Azerbaijan',     d: '+994', f: '🇦🇿' },
  { c: 'KZ', n: 'Kazakhstan',     d: '+7',   f: '🇰🇿' },
  { c: 'MT', n: 'Malta',          d: '+356', f: '🇲🇹' },
  { c: 'EE', n: 'Estonia',        d: '+372', f: '🇪🇪' },
  { c: 'LV', n: 'Latvia',         d: '+371', f: '🇱🇻' },
  { c: 'LT', n: 'Lithuania',      d: '+370', f: '🇱🇹' },
  { c: 'SK', n: 'Slovakia',       d: '+421', f: '🇸🇰' },
  { c: 'SI', n: 'Slovenia',       d: '+386', f: '🇸🇮' },
  { c: 'LU', n: 'Luxembourg',     d: '+352', f: '🇱🇺' },
  { c: 'IS', n: 'Iceland',        d: '+354', f: '🇮🇸' },
  { c: 'IN', n: 'India',          d: '+91',  f: '🇮🇳' },
  { c: 'SG', n: 'Singapore',      d: '+65',  f: '🇸🇬' },
  { c: 'HK', n: 'Hong Kong',      d: '+852', f: '🇭🇰' },
  { c: 'JP', n: 'Japan',          d: '+81',  f: '🇯🇵' },
  { c: 'KR', n: 'South Korea',    d: '+82',  f: '🇰🇷' },
  { c: 'AU', n: 'Australia',      d: '+61',  f: '🇦🇺' },
  { c: 'NZ', n: 'New Zealand',    d: '+64',  f: '🇳🇿' },
  { c: 'BR', n: 'Brazil',         d: '+55',  f: '🇧🇷' },
  { c: 'MX', n: 'Mexico',         d: '+52',  f: '🇲🇽' },
  { c: 'AR', n: 'Argentina',      d: '+54',  f: '🇦🇷' },
  { c: 'ZA', n: 'South Africa',   d: '+27',  f: '🇿🇦' },
];

const ContactModal = () => {
  const [open, setOpen] = React.useState(false);
  const [variant, setVariant] = React.useState('contact');
  const [form, setForm] = React.useState({ name:'', email:'', phone:'', time:'', message:'' });
  const [dialCode, setDialCode] = React.useState('+357');
  const [submitting, setSubmitting] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [error, setError] = React.useState('');
  const [source, setSource] = React.useState('');

  React.useEffect(() => {
    const openHandler = (e) => {
      const detail = (e && e.detail) || {};
      setSubmitted(false); setError('');
      setForm({ name:'', email:'', phone:'', time:'', message:'' });
      setDialCode('+357');
      setSource(detail.source || 'unknown');
      setVariant(detail.variant === 'callback' ? 'callback' : 'contact');
      setOpen(true);
    };
    window.openContactModal = (src, v) => openHandler({ detail:{ source: src, variant: v }});
    window.addEventListener('wo:open-contact', openHandler);
    return () => window.removeEventListener('wo:open-contact', openHandler);
  }, []);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    if (open) {
      document.body.style.overflow = 'hidden';
      window.addEventListener('keydown', onKey);
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const close = () => setOpen(false);

  const submit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitting(true); setError('');
    window.trackEvent && window.trackEvent('cta_click', { location: source || 'contact_modal', cta: variant === 'callback' ? 'callback_submit' : 'contact_submit' });

    const fullPhone = form.phone ? `${dialCode} ${form.phone}`.trim() : '';

    const payload = variant === 'callback'
      ? {
          name: form.name,
          phone: fullPhone,
          preferred_time: form.time,
          email: form.email,
          message: form.message,
          _subject: `New callback request from WiseOps iGaming landing (${source || 'page'})`,
        }
      : {
          name: form.name,
          email: form.email,
          message: form.message,
          _subject: `New enquiry from WiseOps iGaming landing (${source || 'page'})`,
        };

    try {
      const res = await fetch('https://formspree.io/f/mreroael', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify(payload),
      });
      if (res.ok) {
        setSubmitted(true);
        setForm({ name:'', email:'', phone:'', time:'', message:'' });
      } else {
        const data = await res.json().catch(()=>({}));
        setError((data && data.errors && data.errors[0] && data.errors[0].message) || 'Something went wrong. Please try again or email info@wiseops.team.');
      }
    } catch (err) {
      setError('Network error. Please try again or email info@wiseops.team.');
    } finally {
      setSubmitting(false);
    }
  };

  if (!open) return null;

  const title = variant === 'callback' ? 'Request a Callback' : 'Contact Us';
  const successMsg = variant === 'callback'
    ? 'Thanks! We\u2019ll call you back shortly.'
    : 'Thanks! We\u2019ll get back to you shortly.';

  return (
    <div className="contact-modal" onClick={close} role="dialog" aria-modal="true" aria-label={title}>
      <div className="contact-modal-body" onClick={(e)=>e.stopPropagation()}>
        <button className="contact-close" aria-label="Close" onClick={close}>
          <Icon name="close" size={20} stroke={2.2}/>
        </button>
        <h3 className="contact-title">{title}</h3>

        {submitted ? (
          <div className="contact-success">
            <div className="contact-success-ic"><Icon name="check" size={32} stroke={3}/></div>
            <p>{successMsg}</p>
          </div>
        ) : variant === 'callback' ? (
          <form className="contact-form" onSubmit={submit}>
            <label className="cf-field">
              <input type="text" required placeholder=" "
                value={form.name} onChange={(e)=>setForm({...form, name:e.target.value})}/>
              <span className="cf-label">Name</span>
            </label>

            <label className="cf-field cf-phone">
              <select className="cf-dial" aria-label="Country code"
                value={dialCode} onChange={(e)=>setDialCode(e.target.value)}>
                {COUNTRY_CODES.map((c) => (
                  <option key={c.c} value={c.d}>{c.f} {c.d}</option>
                ))}
              </select>
              <input type="tel" required placeholder=" " autoComplete="tel-national"
                value={form.phone} onChange={(e)=>setForm({...form, phone:e.target.value})}/>
              <span className="cf-label">Phone</span>
            </label>

            <label className="cf-field">
              <input type="text" placeholder=" "
                value={form.time} onChange={(e)=>setForm({...form, time:e.target.value})}/>
              <span className="cf-label">Convenient time</span>
              <span className="cf-hint">Optional</span>
            </label>
            <label className="cf-field">
              <input type="email" placeholder=" "
                value={form.email} onChange={(e)=>setForm({...form, email:e.target.value})}/>
              <span className="cf-label">Email</span>
              <span className="cf-hint">Optional</span>
            </label>
            <label className="cf-field">
              <textarea rows="3" placeholder=" "
                value={form.message} onChange={(e)=>setForm({...form, message:e.target.value})}/>
              <span className="cf-label">Message</span>
              <span className="cf-hint">Optional</span>
            </label>
            {error && <div className="cf-error">{error}</div>}
            <button type="submit" className="btn btn-primary cf-submit" disabled={submitting}>
              {submitting ? 'Sending…' : 'Request Callback'}
            </button>
          </form>
        ) : (
          <form className="contact-form" onSubmit={submit}>
            <label className="cf-field">
              <input type="text" required placeholder=" "
                value={form.name} onChange={(e)=>setForm({...form, name:e.target.value})}/>
              <span className="cf-label">Name</span>
            </label>
            <label className="cf-field">
              <input type="email" required placeholder=" "
                value={form.email} onChange={(e)=>setForm({...form, email:e.target.value})}/>
              <span className="cf-label">Email</span>
            </label>
            <label className="cf-field">
              <textarea rows="4" placeholder=" "
                value={form.message} onChange={(e)=>setForm({...form, message:e.target.value})}/>
              <span className="cf-label">Message</span>
            </label>
            {error && <div className="cf-error">{error}</div>}
            <button type="submit" className="btn btn-primary cf-submit" disabled={submitting}>
              {submitting ? 'Sending…' : 'Send'}
            </button>
          </form>
        )}
      </div>
    </div>
  );
};

window.ContactModal = ContactModal;
