// Get Closure — shared components.
// Depends on system/tokens.jsx being loaded first (window.GC_P / GC_FONTS).
// Everything attached to window so it works across <script type="text/babel"> files.

const { useState: GCuseState, useRef: GCuseRef } = React;

// ── Hand-drawn pen circle (for hero phrase) ──────────────────────────────────
// Measures its parent element and draws a hand-drawn oval fitted to those exact
// pixel dimensions. ResizeObserver keeps it correct on viewport changes.
function HandCircle({ color = window.GC_P.accent, stroke = 2.2 }) {
  const ref = GCuseRef(null);
  const [dims, setDims] = GCuseState({ w: 400, h: 100 });

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const parent = el.parentElement;
    if (!parent) return;
    const update = () => {
      const r = parent.getBoundingClientRect();
      if (r.width > 0 && r.height > 0) setDims({ w: r.width, h: r.height });
    };
    update();
    const ro = new ResizeObserver(update);
    ro.observe(parent);
    return () => ro.disconnect();
  }, []);

  const { w, h } = dims;
  const cx = w / 2, cy = h / 2;
  const rx = w / 2 - 5, ry = h / 2 - 5;

  // Hand-drawn oval — 4-segment bezier, deliberately imperfect control points
  // so it reads as pen-on-paper rather than CSS border-radius
  const d = `
    M ${cx + rx * 0.82}  ${cy - ry * 0.35}
    C ${cx + rx * 1.04}  ${cy - ry * 0.75},
      ${cx + rx * 0.52}  ${cy - ry * 1.08},
      ${cx + rx * 0.02}  ${cy - ry * 1.0}
    C ${cx - rx * 0.55}  ${cy - ry * 0.92},
      ${cx - rx * 1.06}  ${cy - ry * 0.28},
      ${cx - rx * 1.0}   ${cy + ry * 0.3}
    C ${cx - rx * 0.94}  ${cy + ry * 0.88},
      ${cx - rx * 0.3}   ${cy + ry * 1.06},
      ${cx + rx * 0.38}  ${cy + ry * 1.0}
    C ${cx + rx * 0.82}  ${cy + ry * 0.92},
      ${cx + rx * 1.08}  ${cy + ry * 0.18},
      ${cx + rx * 0.82}  ${cy - ry * 0.35}
  `;

  return (
    <svg ref={ref} width="100%" height="100%" viewBox={`0 0 ${w} ${h}`}
         style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'visible' }}
         aria-hidden="true">
      <path d={d} fill="none" stroke={color} strokeWidth={stroke}
            strokeLinecap="round" strokeLinejoin="round" opacity="0.9" />
    </svg>
  );
}

// ── Hand-drawn underline (for smaller emphasis) ──────────────────────────────
// Auto-fits parent width. Put it inside a position:relative inline-block span.
// `offset` controls how far below the text baseline it sits.
function HandUnderline({ color = window.GC_P.accent, height = 12, stroke = 2.4, offset = 2 }) {
  return (
    <svg width="100%" height={height} viewBox={`0 0 100 ${height}`}
         preserveAspectRatio="none"
         style={{ position: 'absolute', left: 0, right: 0, bottom: -height + offset, pointerEvents: 'none' }}
         aria-hidden="true">
      <path d={`M 1 ${height - 3} Q 30 1, 55 ${height - 5} T 99 ${height - 3}`}
            fill="none" stroke={color} strokeWidth={stroke}
            vectorEffect="non-scaling-stroke"
            strokeLinecap="round" opacity="0.92" />
    </svg>
  );
}

// ── Small directional arrow ──────────────────────────────────────────────────
// Use once per page near the hero lede. Pair with text, never float alone.
function ArrowMark({ color = window.GC_P.accent, size = 38 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 38 38" aria-hidden="true"
         style={{ display: 'block', overflow: 'visible' }}>
      <path d="M 6 6 C 14 14, 20 22, 26 30"
            fill="none" stroke={color} strokeWidth="2.2" strokeLinecap="round" />
      <path d="M 17 27 L 26 30 L 25 21"
            fill="none" stroke={color} strokeWidth="2.2"
            strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ── Sun-over-horizon mark (wordmark + footer) ────────────────────────────────
function SunMark({ size = 32, color = window.GC_P.accent }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" aria-hidden="true">
      <circle cx="16" cy="20" r="8" fill={color} />
      <line x1="2" y1="24" x2="30" y2="24" stroke={color} strokeWidth="1.8" strokeLinecap="round" />
    </svg>
  );
}

// ── Highlighter swipe (butter yellow band behind text) ──────────────────────
// Use once per section — typically inside the founder note.
function Highlight({ children, color = window.GC_P.butterSoft }) {
  return (
    <span style={{
      background: `linear-gradient(180deg, transparent 58%, ${color} 58%, ${color} 92%, transparent 92%)`,
      padding: '0 4px',
    }}>{children}</span>
  );
}

// ── Status pill (top-right of nav) ───────────────────────────────────────────
function StatusPill({ children, dot = true }) {
  const P = window.GC_P;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      fontFamily: window.GC_FONTS.sans, fontSize: 12, color: P.soft,
      padding: '7px 14px', borderRadius: window.GC_RADIUS.pill,
      background: P.paper, border: `1px solid ${P.rule}`,
      whiteSpace: 'nowrap', letterSpacing: '0.005em',
    }}>
      {dot && <span style={{ width: 6, height: 6, borderRadius: '50%', background: P.accent }} />}
      {children}
    </span>
  );
}

// ── Eyebrow with optional rule (section labels) ──────────────────────────────
function Eyebrow({ children, fill = false }) {
  const P = window.GC_P;
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 32 }}>
      <span style={{
        fontFamily: window.GC_FONTS.sans, fontSize: 12, letterSpacing: '0.1em',
        color: P.muted, textTransform: 'uppercase', fontWeight: 500,
        whiteSpace: 'nowrap',
      }}>{children}</span>
      {fill && <span style={{ flex: 1, height: 1, background: P.rule }} />}
    </div>
  );
}

// ── Card (rounded peach surface, soft shadow) ────────────────────────────────
// Pass deep prop for the darker founder/quote block.
function Card({ children, deep = false, style = {} }) {
  const P = window.GC_P;
  return (
    <div style={{
      padding: deep ? '40px 44px 36px' : '26px 26px 28px',
      background: deep ? P.paperDeep : P.paper,
      borderRadius: deep ? window.GC_RADIUS.cardLarge : window.GC_RADIUS.card,
      border: `1px solid ${deep ? P.rule : P.ruleSoft}`,
      boxShadow: deep ? window.GC_SHADOW.founderSoft : window.GC_SHADOW.cardSoft,
      ...style,
    }}>
      {children}
    </div>
  );
}

// ── Wordmark ─────────────────────────────────────────────────────────────────
// Always top-left. Never resize the sun-mark relative to the wordmark text.
function Wordmark() {
  const P = window.GC_P;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <SunMark color={P.accent} size={28} />
      <span style={{
        fontFamily: window.GC_FONTS.serif, fontSize: 24, fontWeight: 400,
        letterSpacing: '-0.01em', color: P.ink, whiteSpace: 'nowrap',
      }}>Get Closure</span>
    </div>
  );
}

// ── Primary / secondary button ───────────────────────────────────────────────
// One primary CTA per page. Secondary kind for less critical actions.
function Button({ children, type = 'button', onClick, disabled = false, kind = 'primary' }) {
  const P = window.GC_P;
  const styles = kind === 'primary'
    ? { background: P.accent, color: P.paper, border: 0 }
    : { background: 'transparent', color: P.ink, border: `1px solid ${P.rule}` };
  return (
    <button type={type} onClick={onClick} disabled={disabled} style={{
      appearance: 'none', cursor: disabled ? 'wait' : 'pointer',
      padding: '0 22px', height: 48, borderRadius: window.GC_RADIUS.button,
      fontFamily: window.GC_FONTS.sans, fontSize: 14.5, fontWeight: 500,
      letterSpacing: '0.002em', whiteSpace: 'nowrap',
      opacity: disabled ? 0.7 : 1,
      transition: 'opacity .15s, transform .12s',
      ...styles,
    }}>{children}</button>
  );
}

// ── Email capture form ───────────────────────────────────────────────────────
// Validates, posts to /api/subscribe (same-origin Vercel function that proxies
// to Loops server-side — avoids CORS rejection of the Authorization header).
function EmailForm() {
  const P = window.GC_P;
  const FONTS = window.GC_FONTS;
  const [email, setEmail] = GCuseState('');
  const [state, setState] = GCuseState('idle');
  const inputRef = GCuseRef(null);

  const submit = async (e) => {
    e.preventDefault();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
      setState('invalid'); inputRef.current?.focus(); return;
    }
    setState('submitting');

    try {
      await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim() }),
      });
    } catch (err) {
      console.error('[GC] Subscribe failed:', err);
    }

    // Fire PostHog event if analytics are loaded
    if (typeof window.posthog !== 'undefined') {
      window.posthog.capture('email_submitted');
    }

    setState('done');
  };

  if (state === 'done') {
    return (
      <Card>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10,
          color: P.accent, fontFamily: FONTS.sans, fontSize: 12,
          letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600,
        }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: P.accent }} />
          You're on the list
        </div>
        <p style={{
          margin: 0, color: P.ink, fontFamily: FONTS.serif, fontSize: 22,
          lineHeight: 1.35, fontStyle: 'italic',
        }}>
          Thanks. I'll write when the first chapter's ready — one quiet email, nothing else.
        </p>
        <p style={{ margin: '12px 0 0', color: P.soft, fontFamily: FONTS.sans, fontSize: 14, lineHeight: 1.6 }}>
          If you're in the thick of it now, just reply to it. There's a person on the other side.
        </p>
      </Card>
    );
  }

  const error = state === 'invalid';

  return (
    <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{
        display: 'flex', gap: 8, padding: 6,
        background: P.paper, borderRadius: window.GC_RADIUS.formRow,
        border: `1px solid ${error ? P.accent : P.rule}`,
        boxShadow: window.GC_SHADOW.paperInset,
        transition: 'border-color .15s',
      }}>
        <input
          ref={inputRef} type="email" inputMode="email" autoComplete="email"
          placeholder="your email" value={email}
          onChange={(e) => { setEmail(e.target.value); if (error) setState('idle'); }}
          style={{
            flex: 1, minWidth: 0, border: 0, outline: 0, background: 'transparent',
            padding: '14px 14px', fontFamily: FONTS.sans, fontSize: 16, color: P.ink,
          }}
        />
        <Button type="submit" disabled={state === 'submitting'}>
          {state === 'submitting' ? 'Sending…' : 'Keep me posted'}
        </Button>
      </div>
      <p style={{
        margin: '0 8px', fontSize: 13, lineHeight: 1.5,
        color: error ? P.accent : P.muted, fontFamily: FONTS.sans,
        fontStyle: error ? 'normal' : 'italic',
      }}>
        {error
          ? "That doesn't look quite right — try again?"
          : "Email only. No company name, no calls. One message when it's ready."}
      </p>
    </form>
  );
}

// ── Contact modal ────────────────────────────────────────────────────────────
// Triggered from the footer. Posts to /api/contact (Vercel serverless),
// which logs the submission in Loops as a contact_message event.
function ContactModal({ onClose }) {
  const P = window.GC_P;
  const FONTS = window.GC_FONTS;
  const [fields, setFields] = GCuseState({ name: '', email: '', message: '' });
  const [state, setState] = GCuseState('idle'); // idle | submitting | done | error

  // Close on Escape
  React.useEffect(() => {
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [onClose]);

  const set = (key) => (e) => setFields((f) => ({ ...f, [key]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    setState('submitting');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(fields),
      });
      if (!res.ok) {
        setState('error');
        return;
      }
      if (typeof window.posthog !== 'undefined') {
        window.posthog.capture('contact_form_submitted');
      }
      setState('done');
    } catch (err) {
      console.error('[GC] Contact failed:', err);
      setState('error');
    }
  };

  const inputStyle = {
    width: '100%', boxSizing: 'border-box',
    border: `1px solid ${P.rule}`, borderRadius: 10,
    background: P.bg, outline: 0,
    padding: '11px 14px', fontFamily: FONTS.sans, fontSize: 15, color: P.ink,
  };

  return (
    // Backdrop
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(36,23,16,0.45)', backdropFilter: 'blur(3px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '24px',
    }}>
      {/* Panel — stop clicks propagating to backdrop */}
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 480,
        background: P.paper, borderRadius: window.GC_RADIUS.cardLarge,
        border: `1px solid ${P.rule}`,
        boxShadow: '0 24px 64px -16px rgba(120,60,20,.35)',
        padding: '36px 36px 32px',
        position: 'relative',
      }}>
        {/* Close button */}
        <button onClick={onClose} aria-label="Close" style={{
          position: 'absolute', top: 16, right: 16,
          background: 'none', border: 0, cursor: 'pointer',
          color: P.muted, fontSize: 20, lineHeight: 1, padding: 4,
        }}>✕</button>

        {state === 'done' ? (
          <>
            <div style={{ color: P.accent, fontFamily: FONTS.sans, fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: P.accent }} />
              Message sent
            </div>
            <p style={{ margin: 0, fontFamily: FONTS.serif, fontSize: 21, lineHeight: 1.35, fontStyle: 'italic', color: P.ink }}>
              Got it. I read everything — I will get back to you.
            </p>
          </>
        ) : (
          <>
            <h2 style={{ margin: '0 0 6px', fontFamily: FONTS.serif, fontSize: 24, fontWeight: 400, letterSpacing: '-0.014em', color: P.ink }}>
              Get in touch
            </h2>
            <p style={{ margin: '0 0 24px', fontFamily: FONTS.sans, fontSize: 14, color: P.muted, lineHeight: 1.5 }}>
              No form software, no ticketing system. A person will read this.
            </p>

            <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <input
                type="text" placeholder="Your name (optional)"
                value={fields.name} onChange={set('name')}
                style={inputStyle}
              />
              <input
                type="email" inputMode="email" placeholder="Your email"
                value={fields.email} onChange={set('email')} required
                style={inputStyle}
              />
              <textarea
                placeholder="What do you want to say?"
                value={fields.message} onChange={set('message')} required
                rows={5} style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.55 }}
              />
              {state === 'error' && (
                <p style={{ margin: 0, fontFamily: FONTS.sans, fontSize: 13, color: P.accent }}>
                  Something went wrong — try again in a moment.
                </p>
              )}
              <Button type="submit" disabled={state === 'submitting'}>
                {state === 'submitting' ? 'Sending…' : 'Send message'}
              </Button>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, {
  GC_HandCircle:    HandCircle,
  GC_HandUnderline: HandUnderline,
  GC_ArrowMark:     ArrowMark,
  GC_SunMark:       SunMark,
  GC_Highlight:     Highlight,
  GC_StatusPill:    StatusPill,
  GC_Eyebrow:       Eyebrow,
  GC_Card:          Card,
  GC_Wordmark:      Wordmark,
  GC_Button:        Button,
  GC_EmailForm:     EmailForm,
  GC_ContactModal:  ContactModal,
});
