// ── JT Atelier — Welcome offer popup (email capture, 10% off first order) ──
// Elegant entry popup, shown ONCE per visitor (~1.4s after load). Reuses the
// site's existing .modal / .modal-card / .eyebrow / .display / .field styles so
// it looks native. Posts to /api/subscribe (source: welcome-popup); on success
// reveals code WELCOME10. Dismiss = X / backdrop / ESC. Gated by localStorage.

function WelcomeOffer() {
  const [open, setOpen]       = React.useState(false);
  const [email, setEmail]     = React.useState('');
  const [sent, setSent]       = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [copied, setCopied]   = React.useState(false);

  const KEY = 'jta_welcome_v1';
  const seal = () => { try { localStorage.setItem(KEY, '1'); } catch { /* private mode */ } };
  const dismiss = () => { setOpen(false); seal(); };

  // Show once, shortly after arrival (skip if already seen this device)
  React.useEffect(() => {
    let seen = false;
    try { seen = !!localStorage.getItem(KEY); } catch { /* ignore */ }
    if (seen) return;
    const t = setTimeout(() => setOpen(true), 1400);
    return () => clearTimeout(t);
  }, []);

  // ESC to close while open
  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === 'Escape') dismiss(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open]);

  const submit = async (e) => {
    if (e) e.preventDefault();
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
      const f = document.getElementById('welcome-field');
      if (f && f.animate) f.animate([{ transform: 'translateX(-6px)' }, { transform: 'translateX(6px)' }, { transform: 'none' }], { duration: 280 });
      return;
    }
    setLoading(true);
    try {
      await fetch('/api/subscribe', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, source: 'welcome-popup' }),
      });
    } catch { /* still show success — subscribe is best-effort */ }
    setLoading(false);
    setSent(true);
    seal();
  };

  const copyCode = () => {
    try { navigator.clipboard.writeText('WELCOME10'); setCopied(true); setTimeout(() => setCopied(false), 1600); } catch { /* ignore */ }
  };

  return (
    <div className={`modal ${open ? 'on' : ''}`} onClick={dismiss}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()} style={{ textAlign: 'left' }}>
        <button className="close-x" onClick={dismiss} style={{ position: 'absolute', top: 12, right: 12 }} aria-label="Close">
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.3">
            <line x1="3" y1="3" x2="15" y2="15" /><line x1="15" y1="3" x2="3" y2="15" />
          </svg>
        </button>

        <div className="eyebrow" style={{ marginBottom: 18 }}>◇ &nbsp; {sent ? 'Welcome to the studio' : 'A welcome gift'}</div>

        {sent ? (
          <>
            <h2 className="display" style={{ fontSize: 'clamp(32px,5vw,52px)', margin: 0, lineHeight: 1.05 }}>
              You're <em className="gradient-text">in</em>.
            </h2>
            <p style={{ fontSize: 14, lineHeight: 1.65, color: 'var(--fg-2)', marginTop: 16, marginBottom: 24, maxWidth: 420 }}>
              Enter this code at checkout for <b>10% off your first order</b>.
            </p>
            <button onClick={copyCode}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 14, padding: '14px 22px', border: '1px solid var(--brass, #c6a86b)', background: 'transparent', cursor: 'pointer' }}>
              <span className="mono" style={{ fontSize: 18, letterSpacing: '.28em', color: 'var(--brass, #c6a86b)', fontWeight: 700 }}>WELCOME10</span>
              <span className="mono" style={{ fontSize: 9.5, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>{copied ? 'Copied ✓' : 'Tap to copy'}</span>
            </button>
            <div style={{ marginTop: 26 }}>
              <button className="btn" onClick={dismiss} style={{ fontSize: 12 }}>Start shopping →</button>
            </div>
          </>
        ) : (
          <>
            <h2 className="display" style={{ fontSize: 'clamp(32px,5vw,52px)', margin: 0, lineHeight: 1.05 }}>
              Your first piece,<br /><em className="gradient-text">ten percent lighter.</em>
            </h2>
            <p style={{ fontSize: 14, lineHeight: 1.65, color: 'var(--fg-2)', marginTop: 18, marginBottom: 30, maxWidth: 430 }}>
              Join the studio list for new arrivals, seasonal sales and the occasional discount — and take
              <b style={{ color: 'var(--fg)' }}> 10% off your first order</b>.
            </p>
            <form className="field" id="welcome-field" onSubmit={submit}>
              <input type="email" placeholder="your@email.com" value={email}
                onChange={(e) => setEmail(e.target.value)} autoFocus disabled={loading} />
              <button type="submit" disabled={loading}>{loading ? '…' : 'Claim 10% off →'}</button>
            </form>
            <div className="mono" style={{ color: 'var(--fg-3)', marginTop: 16, fontSize: 9.5, letterSpacing: '.08em' }}>
              One-time welcome offer · no more than two emails a month.
            </div>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { WelcomeOffer });
