// Contact modal — a single, shared, on-brand modal that lets a visitor send a
// message WITHOUT the site exposing Spencer's email address publicly. Mounted
// once (see app.jsx) and opened from anywhere via window.openContactModal()
// (optional arg: { reason } to seed the subject line, e.g. for the gated
// "request access" CTAs). Mirrors the lightbox's mount/enter/leave/Esc/scroll-
// lock pattern so it feels like part of the same system.
//
// DELIVERY: this prototype simulates a successful send (no backend). To make it
// live on the static site, set FORM_ENDPOINT to a form-to-email service URL
// (Formspree, Basin, Web3Forms, etc.) — the submit handler already POSTs the
// payload there when the endpoint is set, and falls back to the simulated
// success when it isn't. The visitor never sees Spencer's address either way.
const FORM_ENDPOINT = '';   // e.g. 'https://formspree.io/f/xxxx…'

function ContactModal() {
  const [state, setState] = React.useState(null);    // null | { reason }
  const [shown, setShown] = React.useState(false);
  const [phase, setPhase] = React.useState('form');  // 'form' | 'sending' | 'sent' | 'error'
  const [form, setForm] = React.useState({ name: '', email: '', message: '' });
  const closeTimer = React.useRef(0);
  const firstField = React.useRef(null);
  const mobile = window.useIsMobile ? window.useIsMobile() : false;
  const reduce = typeof window.matchMedia === 'function'
    && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const ease = 'cubic-bezier(.16,1,.3,1)';

  // Register the global opener.
  React.useEffect(() => {
    window.openContactModal = (opts = {}) => {
      clearTimeout(closeTimer.current);
      setPhase('form');
      setForm({ name: '', email: '', message: opts.reason ? `Re: ${opts.reason}\n\n` : '' });
      setState({ reason: opts.reason || null });
      setTimeout(() => setShown(true), 20);
    };
    return () => { try { delete window.openContactModal; } catch (e) {} };
  }, []);

  const close = React.useCallback(() => {
    setShown(false);
    clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setState(null), reduce ? 0 : 300);
  }, [reduce]);

  // Keyboard + body scroll lock + focus the first field while open.
  React.useEffect(() => {
    if (!state) return;
    const onKey = (e) => { if (e.key === 'Escape') close(); };
    window.addEventListener('keydown', onKey);
    const prevOverflow = document.documentElement.style.overflow;
    document.documentElement.style.overflow = 'hidden';
    const f = setTimeout(() => { if (firstField.current) firstField.current.focus(); }, 80);
    return () => {
      window.removeEventListener('keydown', onKey);
      document.documentElement.style.overflow = prevOverflow;
      clearTimeout(f);
    };
  }, [state, close]);

  const set = (k) => (e) => setForm((s) => ({ ...s, [k]: e.target.value }));
  const valid = form.name.trim() && /\S+@\S+\.\S+/.test(form.email) && form.message.trim().length > 1;

  const submit = async (e) => {
    e.preventDefault();
    if (!valid || phase === 'sending') return;
    setPhase('sending');
    try {
      if (FORM_ENDPOINT) {
        const res = await fetch(FORM_ENDPOINT, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
          body: JSON.stringify({ ...form, _subject: state && state.reason ? `Portfolio — ${state.reason}` : 'Portfolio enquiry' }),
        });
        if (!res.ok) throw new Error('bad status');
      } else {
        await new Promise((r) => setTimeout(r, 850));   // simulate the round-trip
      }
      setPhase('sent');
    } catch (err) {
      setPhase('error');
    }
  };

  if (!state) return null;

  const labelStyle = {
    fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--ink-3)',
    letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 7, display: 'block',
  };
  const fieldStyle = {
    width: '100%', boxSizing: 'border-box', fontFamily: 'var(--font-primary)',
    fontSize: 15, color: 'var(--ink)', background: 'var(--paper-2)',
    border: '1px solid var(--rule)', borderRadius: 0, padding: '11px 12px',
    outline: 'none', transition: 'border-color .15s',
  };
  const onFocus = (e) => { e.target.style.borderColor = 'var(--ink-2)'; };
  const onBlur = (e) => { e.target.style.borderColor = 'var(--rule)'; };

  const insta = (window.META && window.META.insta) || '@spencerrussell';
  const instaUrl = (window.META && window.META.instaUrl) || 'https://instagram.com';

  return (
    <div
      onClick={close}
      style={{
        position: 'fixed', inset: 0, zIndex: 9100,
        display: 'flex', alignItems: mobile ? 'flex-end' : 'center', justifyContent: 'center',
        padding: mobile ? 0 : 'clamp(16px, 5vw, 56px)', boxSizing: 'border-box',
        background: 'oklch(20% 0.02 140 / 0.78)',
        backdropFilter: shown ? 'blur(8px)' : 'blur(0px)', WebkitBackdropFilter: shown ? 'blur(8px)' : 'blur(0px)',
        opacity: shown ? 1 : 0,
        transition: reduce ? 'none' : 'opacity .3s ease, backdrop-filter .3s ease',
      }}>

      <div
        onClick={(e) => e.stopPropagation()}
        role="dialog" aria-modal="true" aria-label="Contact Spencer Russell"
        style={{
          position: 'relative', width: mobile ? '100%' : 'min(460px, 100%)',
          maxHeight: mobile ? '92vh' : 'none', overflowY: 'auto',
          background: 'var(--paper)', color: 'var(--ink)',
          border: '1px solid var(--rule)',
          boxShadow: '0 30px 80px -20px oklch(20% 0.02 140 / 0.5)',
          padding: mobile ? '26px 22px calc(26px + env(safe-area-inset-bottom))' : '34px 34px 30px',
          opacity: shown ? 1 : 0,
          transform: reduce ? 'none' : (shown ? 'translateY(0) scale(1)' : (mobile ? 'translateY(24px) scale(1)' : 'translateY(10px) scale(.97)')),
          transition: reduce ? 'none' : `opacity .3s ease, transform .38s ${ease}`,
        }}>

        {/* close */}
        <button onClick={close} aria-label="Close"
          style={{ position: 'absolute', top: 14, right: 14, width: 34, height: 34, cursor: 'pointer',
            border: '1px solid var(--rule)', background: 'transparent', color: 'var(--ink-2)',
            fontSize: 15, lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'background .15s, color .15s' }}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--paper-2)'; e.currentTarget.style.color = 'var(--ink)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ink-2)'; }}>✕</button>

        <div className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)', letterSpacing: 0.6,
          textTransform: 'uppercase', marginBottom: 14 }}>§ 05 / Contact</div>

        {phase === 'sent' ? (
          <div style={{ paddingBottom: 6 }}>
            <div style={{ fontSize: 26, fontWeight: 500, letterSpacing: -0.8, lineHeight: 1.05, marginBottom: 12 }}>
              Message sent.
            </div>
            <div style={{ fontSize: 15, lineHeight: 1.5, color: 'var(--ink-2)', textWrap: 'pretty', marginBottom: 24 }}>
              Thanks{form.name ? `, ${form.name.split(' ')[0]}` : ''} — I’ll get back to you soon. No newsletter, no list, just a reply.
            </div>
            <button onClick={close} className="mono"
              style={{ fontFamily: 'var(--font-mono)', fontSize: 13, padding: '12px 18px', cursor: 'pointer',
                border: '1px solid var(--ink)', background: 'var(--ink)', color: 'var(--paper)' }}>
              Close
            </button>
          </div>
        ) : (
          <React.Fragment>
            <div style={{ fontSize: 27, fontWeight: 500, letterSpacing: -0.9, lineHeight: 1.04, marginBottom: 8 }}>
              Get in touch
            </div>
            <div style={{ fontSize: 14.5, lineHeight: 1.5, color: 'var(--ink-2)', textWrap: 'pretty', marginBottom: 22 }}>
              {state.reason
                ? `Requesting access to ${state.reason}. Drop a line below and I’ll send credentials.`
                : 'For project enquiries, collaborations, or access requests. Goes straight to my inbox.'}
            </div>

            <form onSubmit={submit} noValidate>
              <div style={{ marginBottom: 16 }}>
                <label style={labelStyle} htmlFor="cf-name">Name</label>
                <input id="cf-name" ref={firstField} type="text" value={form.name} onChange={set('name')}
                  onFocus={onFocus} onBlur={onBlur} style={fieldStyle} autoComplete="name" />
              </div>
              <div style={{ marginBottom: 16 }}>
                <label style={labelStyle} htmlFor="cf-email">Your email</label>
                <input id="cf-email" type="email" value={form.email} onChange={set('email')}
                  onFocus={onFocus} onBlur={onBlur} style={fieldStyle} autoComplete="email"
                  placeholder="so I can reply" />
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={labelStyle} htmlFor="cf-message">Message</label>
                <textarea id="cf-message" rows={mobile ? 4 : 5} value={form.message} onChange={set('message')}
                  onFocus={onFocus} onBlur={onBlur} style={{ ...fieldStyle, resize: 'vertical', minHeight: 96, lineHeight: 1.5 }} />
              </div>

              {phase === 'error' && (
                <div className="mono" style={{ fontSize: 12, color: 'var(--accent-c)', marginBottom: 14, lineHeight: 1.4 }}>
                  Something went wrong sending that. Try again, or reach me on Instagram below.
                </div>
              )}

              <button type="submit" disabled={!valid || phase === 'sending'} className="mono"
                style={{ fontFamily: 'var(--font-mono)', fontSize: 13, width: '100%', padding: '14px 16px',
                  border: '1px solid var(--ink)',
                  background: valid && phase !== 'sending' ? 'var(--ink)' : 'var(--paper-2)',
                  color: valid && phase !== 'sending' ? 'var(--paper)' : 'var(--ink-3)',
                  cursor: valid && phase !== 'sending' ? 'pointer' : 'not-allowed',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
                  transition: 'background .15s, color .15s', letterSpacing: 0.3 }}>
                <span>{phase === 'sending' ? 'Sending…' : 'Send message'}</span>
                <span style={{ opacity: 0.7 }}>{phase === 'sending' ? '·' : '→'}</span>
              </button>
            </form>

            <div className="mono" style={{ fontSize: 11.5, color: 'var(--ink-3)', letterSpacing: 0.2,
              marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--rule)', lineHeight: 1.5 }}>
              Prefer DMs? Find me on{' '}
              <a href={instaUrl} target="_blank" rel="noopener"
                style={{ color: 'var(--ink)', textDecoration: 'underline', textUnderlineOffset: 3 }}>
                Instagram {insta}
              </a> ↗
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

window.ContactModal = ContactModal;
