/* SKOPIA — Contact / Waitlist modal
 *
 * Global: window.openContactModal({ subject?, intent? })
 * Listens for: a click on any element with data-contact-trigger,
 *              or href="#contact" / href="#waitlist" / href="#signup"
 *              (when intent is set via attr data-intent).
 */

const CONTACT_EMAIL = 'contact@skopia.com.au';

const INTENT_PRESETS = {
  general:   { subject: 'SKOPIA — general enquiry',         heading: 'Get in touch.',        sub: 'Tell us what you need. We reply within one business day.' },
  waitlist:  { subject: 'SKOPIA — waitlist signup',          heading: 'Join the waitlist.',   sub: 'Build and Track are landing soon. Drop your details and we’ll be in touch the moment they’re ready.' },
  sales:     { subject: 'SKOPIA — volume pricing enquiry',   heading: 'Talk to us.',          sub: 'Volume pricing for teams of 10+, custom plans, procurement support — we’ll come back to you fast.' },
  signup:    { subject: 'SKOPIA Lens — early access',        heading: 'Start with Lens.',     sub: 'Drop your details and we’ll send a free Lens account by return.' },
};

const ContactModal = () => {
  const [open, setOpen] = useState(false);
  const [intent, setIntent] = useState('general');
  const [submitted, setSubmitted] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);
  const formRef = useRef(null);

  // ── Open / close API ───────────────────────────────────────
  useEffect(() => {
    window.openContactModal = (opts = {}) => {
      const next = opts.intent && INTENT_PRESETS[opts.intent] ? opts.intent : 'general';
      setIntent(next);
      setSubmitted(false);
      setError(null);
      setOpen(true);
    };

    // Global click delegation — intercept hash anchors / data attrs
    const onClick = (e) => {
      // Walk up to find a clickable
      let el = e.target;
      while (el && el !== document.body) {
        if (el.matches && (el.matches('[data-contact-trigger]') || el.matches('a[href]'))) {
          const explicit = el.getAttribute('data-contact-trigger');
          const href = el.getAttribute('href') || '';
          let next = null;
          if (explicit) next = explicit;
          else if (href === '#contact')   next = 'general';
          else if (href === '#waitlist')  next = 'waitlist';
          else if (href === '#sales')     next = 'sales';
          else if (href === '#signup')    next = 'signup';
          if (next) {
            e.preventDefault();
            window.openContactModal({ intent: next });
            return;
          }
        }
        el = el.parentElement;
      }
    };
    document.addEventListener('click', onClick, true);

    // Esc to close
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('keydown', onKey);

    return () => {
      document.removeEventListener('click', onClick, true);
      document.removeEventListener('keydown', onKey);
    };
  }, []);

  // ── Body scroll lock ───────────────────────────────────────
  useEffect(() => {
    if (open) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }
  }, [open]);

  const preset = INTENT_PRESETS[intent];

  const handleSubmit = (e) => {
    e.preventDefault();
    setError(null);
    setBusy(true);
    const fd = new FormData(formRef.current);
    const data = Object.fromEntries(fd.entries());

    // Compose a mailto fallback so the message reliably reaches the inbox
    // even without a backend handler.
    const body =
      `Hi SKOPIA team,\n\n` +
      `Name: ${data.name}\n` +
      `Company: ${data.company || '—'}\n` +
      `Role: ${data.role || '—'}\n` +
      `Email: ${data.email}\n` +
      `Phone: ${data.phone || '—'}\n` +
      `Interested in: ${data.interest || '—'}\n` +
      `Team size: ${data.teamSize || '—'}\n` +
      `\nMessage:\n${data.message || '—'}\n`;
    const subject = encodeURIComponent(`${preset.subject}${data.company ? ' — ' + data.company : ''}`);
    const url = `mailto:${CONTACT_EMAIL}?subject=${subject}&body=${encodeURIComponent(body)}`;

    try {
      // Open the user's mail client in a new tab
      window.location.href = url;
      setSubmitted(true);
    } catch (err) {
      setError('Could not open your mail client. Please email ' + CONTACT_EMAIL + ' directly.');
    } finally {
      setBusy(false);
    }
  };

  if (!open) return null;

  const inputStyle = {
    width: '100%',
    padding: '11px 14px',
    fontFamily: 'var(--font-body)',
    fontSize: 14,
    color: '#1A1A2E',
    background: '#fff',
    border: '1px solid #E2E6F0',
    borderRadius: 4,
    outline: 'none',
    transition: 'border-color .15s, box-shadow .15s',
  };
  const labelStyle = {
    display: 'block',
    fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 11,
    letterSpacing: 1.2, textTransform: 'uppercase',
    color: '#6B7280', marginBottom: 6,
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="contact-modal-title"
      style={{
        position: 'fixed', inset: 0, zIndex: 9000,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
        background: 'rgba(10,11,26,0.62)',
        backdropFilter: 'blur(8px)',
        WebkitBackdropFilter: 'blur(8px)',
        animation: 'contact-backdrop-in .25s ease both',
      }}
      onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
    >
      <div
        style={{
          position: 'relative',
          width: 'min(560px, 100%)',
          maxHeight: 'calc(100vh - 40px)',
          background: '#fff',
          borderRadius: 10,
          boxShadow: '0 40px 100px -20px rgba(0,0,0,0.4), 0 0 0 1px rgba(255,255,255,0.05)',
          overflow: 'hidden',
          animation: 'contact-modal-in .28s cubic-bezier(.2,.7,.2,1) both',
          display: 'flex', flexDirection: 'column',
        }}
      >
        {/* Gradient accent bar */}
        <div style={{ height: 4, background: 'var(--color-grad)' }} />

        {/* Close button */}
        <button
          onClick={() => setOpen(false)}
          aria-label="Close"
          style={{
            position: 'absolute', top: 14, right: 14,
            width: 32, height: 32, borderRadius: '50%',
            border: 'none', background: '#F1F3FA', color: '#6B7280',
            cursor: 'pointer', zIndex: 2,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'background .15s, color .15s',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = '#E2E6F0'; e.currentTarget.style.color = '#1A1A2E'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = '#F1F3FA'; e.currentTarget.style.color = '#6B7280'; }}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round">
            <path d="M6 6l12 12M18 6L6 18" />
          </svg>
        </button>

        {!submitted ? (
          <>
            {/* Header */}
            <div style={{ padding: '28px 28px 18px' }}>
              <div className="eyebrow" style={{ marginBottom: 12 }}>
                {intent === 'waitlist' ? 'Waitlist' : intent === 'sales' ? 'Sales' : 'Contact'}
              </div>
              <h3 id="contact-modal-title" style={{
                fontFamily: 'var(--font-head)', fontWeight: 900,
                fontSize: 28, letterSpacing: -0.8, lineHeight: 1.1,
                color: '#1A1A2E',
              }}>
                {preset.heading}
              </h3>
              <p style={{
                fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.55,
                color: '#6B7280', marginTop: 8, maxWidth: 460,
              }}>{preset.sub}</p>
            </div>

            {/* Body — scrollable */}
            <form
              ref={formRef}
              onSubmit={handleSubmit}
              style={{
                padding: '0 28px 24px',
                overflowY: 'auto',
                display: 'flex', flexDirection: 'column', gap: 14,
              }}
            >
              <input type="hidden" name="intent" value={intent} />

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }} className="contact-row">
                <div>
                  <label style={labelStyle} htmlFor="ct-name">Name *</label>
                  <input style={inputStyle} id="ct-name" name="name" type="text" required autoComplete="name"
                    onFocus={(e) => { e.target.style.borderColor = '#4A6FE8'; e.target.style.boxShadow = '0 0 0 3px rgba(74,111,232,0.15)'; }}
                    onBlur={(e) => { e.target.style.borderColor = '#E2E6F0'; e.target.style.boxShadow = 'none'; }}
                  />
                </div>
                <div>
                  <label style={labelStyle} htmlFor="ct-email">Email *</label>
                  <input style={inputStyle} id="ct-email" name="email" type="email" required autoComplete="email"
                    onFocus={(e) => { e.target.style.borderColor = '#4A6FE8'; e.target.style.boxShadow = '0 0 0 3px rgba(74,111,232,0.15)'; }}
                    onBlur={(e) => { e.target.style.borderColor = '#E2E6F0'; e.target.style.boxShadow = 'none'; }}
                  />
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }} className="contact-row">
                <div>
                  <label style={labelStyle} htmlFor="ct-company">Company</label>
                  <input style={inputStyle} id="ct-company" name="company" type="text" autoComplete="organization"
                    onFocus={(e) => { e.target.style.borderColor = '#4A6FE8'; e.target.style.boxShadow = '0 0 0 3px rgba(74,111,232,0.15)'; }}
                    onBlur={(e) => { e.target.style.borderColor = '#E2E6F0'; e.target.style.boxShadow = 'none'; }}
                  />
                </div>
                <div>
                  <label style={labelStyle} htmlFor="ct-role">Role</label>
                  <input style={inputStyle} id="ct-role" name="role" type="text" placeholder="e.g. Project Manager"
                    onFocus={(e) => { e.target.style.borderColor = '#4A6FE8'; e.target.style.boxShadow = '0 0 0 3px rgba(74,111,232,0.15)'; }}
                    onBlur={(e) => { e.target.style.borderColor = '#E2E6F0'; e.target.style.boxShadow = 'none'; }}
                  />
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }} className="contact-row">
                <div>
                  <label style={labelStyle} htmlFor="ct-phone">Phone</label>
                  <input style={inputStyle} id="ct-phone" name="phone" type="tel" autoComplete="tel"
                    onFocus={(e) => { e.target.style.borderColor = '#4A6FE8'; e.target.style.boxShadow = '0 0 0 3px rgba(74,111,232,0.15)'; }}
                    onBlur={(e) => { e.target.style.borderColor = '#E2E6F0'; e.target.style.boxShadow = 'none'; }}
                  />
                </div>
                <div>
                  <label style={labelStyle} htmlFor="ct-team">Team size</label>
                  <select style={{ ...inputStyle, appearance: 'auto' }} id="ct-team" name="teamSize"
                    onFocus={(e) => { e.target.style.borderColor = '#4A6FE8'; e.target.style.boxShadow = '0 0 0 3px rgba(74,111,232,0.15)'; }}
                    onBlur={(e) => { e.target.style.borderColor = '#E2E6F0'; e.target.style.boxShadow = 'none'; }}
                  >
                    <option value="">Select…</option>
                    <option>1 – 4</option>
                    <option>5 – 9</option>
                    <option>10 – 24</option>
                    <option>25 – 99</option>
                    <option>100+</option>
                  </select>
                </div>
              </div>

              <div>
                <label style={labelStyle} htmlFor="ct-interest">Interested in</label>
                <select style={{ ...inputStyle, appearance: 'auto' }} id="ct-interest" name="interest"
                  defaultValue={intent === 'waitlist' ? 'SKOPIA Build / Track' : ''}
                  onFocus={(e) => { e.target.style.borderColor = '#4A6FE8'; e.target.style.boxShadow = '0 0 0 3px rgba(74,111,232,0.15)'; }}
                  onBlur={(e) => { e.target.style.borderColor = '#E2E6F0'; e.target.style.boxShadow = 'none'; }}
                >
                  <option value="">Select…</option>
                  <option>SKOPIA Lens (free)</option>
                  <option>SKOPIA Lens Pro</option>
                  <option>SKOPIA Build / Track</option>
                  <option>Helios AI</option>
                  <option>Volume / enterprise pricing</option>
                  <option>Partnership / integration</option>
                  <option>Other</option>
                </select>
              </div>

              <div>
                <label style={labelStyle} htmlFor="ct-message">Message *</label>
                <textarea
                  style={{ ...inputStyle, minHeight: 120, resize: 'vertical', fontFamily: 'var(--font-body)' }}
                  id="ct-message" name="message" required
                  placeholder={intent === 'waitlist'
                    ? 'Tell us a little about the projects you’d like to run on Build or Track…'
                    : 'How can we help?'}
                  onFocus={(e) => { e.target.style.borderColor = '#4A6FE8'; e.target.style.boxShadow = '0 0 0 3px rgba(74,111,232,0.15)'; }}
                  onBlur={(e) => { e.target.style.borderColor = '#E2E6F0'; e.target.style.boxShadow = 'none'; }}
                />
              </div>

              {error && (
                <div style={{
                  padding: '10px 14px', borderRadius: 4,
                  background: 'rgba(220,38,38,0.06)', border: '1px solid rgba(220,38,38,0.2)',
                  fontFamily: 'var(--font-body)', fontSize: 13, color: '#DC2626',
                }}>{error}</div>
              )}

              <div style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                gap: 14, marginTop: 6, flexWrap: 'wrap',
              }}>
                <p style={{
                  fontFamily: 'var(--font-body)', fontSize: 11.5, color: '#9AA0B0',
                  lineHeight: 1.5, maxWidth: 280, margin: 0,
                }}>
                  By submitting, you agree we’ll use these details to reply to you.
                  Your data isn’t shared.
                </p>
                <button
                  type="submit"
                  disabled={busy}
                  style={{
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                    padding: '13px 26px', borderRadius: 999, border: 'none',
                    fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 13, letterSpacing: 0.3,
                    background: 'var(--color-grad)', color: '#fff',
                    cursor: busy ? 'wait' : 'pointer',
                    boxShadow: '0 8px 24px rgba(42,77,204,0.25)',
                    opacity: busy ? 0.7 : 1,
                  }}
                >
                  {busy ? 'Sending…' : (
                    <>
                      {intent === 'waitlist' ? 'Join waitlist' : 'Send message'}
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
                        <path d="M5 12h14M13 6l6 6-6 6" />
                      </svg>
                    </>
                  )}
                </button>
              </div>
            </form>
          </>
        ) : (
          /* Success state */
          <div style={{ padding: '40px 32px 36px', textAlign: 'center' }}>
            <div style={{
              width: 56, height: 56, borderRadius: '50%',
              background: 'linear-gradient(135deg, rgba(30,200,212,0.12), rgba(74,111,232,0.12))',
              border: '1px solid rgba(74,111,232,0.22)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              margin: '0 auto 18px',
            }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#2A4DCC" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12.5l4 4L19 7" />
              </svg>
            </div>
            <h3 style={{
              fontFamily: 'var(--font-head)', fontWeight: 900,
              fontSize: 24, letterSpacing: -0.6, color: '#1A1A2E', marginBottom: 8,
            }}>
              Almost there — confirm in your mail app.
            </h3>
            <p style={{
              fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.55,
              color: '#6B7280', maxWidth: 380, margin: '0 auto 22px',
            }}>
              We’ve opened a pre-filled email to <strong style={{ color: '#1A1A2E' }}>{CONTACT_EMAIL}</strong>. Hit send and we’ll reply within one business day. If nothing opened, just email us directly.
            </p>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
              <a
                href={`mailto:${CONTACT_EMAIL}`}
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                  padding: '11px 20px', borderRadius: 999,
                  background: 'var(--color-grad)', color: '#fff',
                  fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 13,
                }}
              >Open mail app</a>
              <button
                onClick={() => setOpen(false)}
                style={{
                  padding: '11px 20px', borderRadius: 999,
                  background: 'transparent', color: '#1A1A2E',
                  border: '1.5px solid #E2E6F0',
                  fontFamily: 'var(--font-head)', fontWeight: 700, fontSize: 13,
                  cursor: 'pointer',
                }}
              >Close</button>
            </div>
          </div>
        )}
      </div>

      <style>{`
        @keyframes contact-backdrop-in {
          from { opacity: 0; }
          to   { opacity: 1; }
        }
        @keyframes contact-modal-in {
          from { opacity: 0; transform: translateY(16px) scale(0.97); }
          to   { opacity: 1; transform: none; }
        }
        @media (max-width: 520px) {
          .contact-row { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
};

Object.assign(window, { ContactModal });
