/* CoHaven — Lead Gate (shared across all free tools)
   Branded email-capture modal + inline results gate + print branding.
   Persists to localStorage; user is only asked once per device.
   Exports to window: { LeadGateModal, useLeadGate, PrintBrand, ResultsGate } */

const { useState, useCallback, useEffect } = React;
const LG_KEY = 'cohaven.lead';

function getLead() {
  try { return JSON.parse(localStorage.getItem(LG_KEY) || 'null'); } catch(e) { return null; }
}
function saveLead(d) {
  localStorage.setItem(LG_KEY, JSON.stringify({ ...d, ts: Date.now() }));
}

function toolContextFromLocation() {
  const path = window.location.pathname;
  const year = new Date().getFullYear();
  if (path.includes('expense')) {
    return {
      toolId: 'expense_split_calculator',
      acquisitionSource: 'tool_02',
      metadata: {
        expense_split_method: 'static_tool',
        expense_split_pdf_url: 'generated_client_side',
        expense_split_csv_url: 'not_available',
      },
    };
  }
  if (path.includes('holiday')) {
    return {
      toolId: 'holiday_custody_planner',
      acquisitionSource: 'holiday_copilot',
      subBrandId: 'holiday_copilot',
      metadata: {
        holiday_year: year,
        planning_year: year,
        holiday_pattern: 'static_tool',
        holiday_calendar_export_url: 'generated_client_side',
        subbrand: 'holidaycopilot',
        sub_brand_id: 'holiday_copilot',
      },
    };
  }
  if (path.includes('shift')) {
    return {
      toolId: 'shift_worker_planner',
      acquisitionSource: 'shift_parent_os',
      subBrandId: 'shift_parent_os',
      metadata: {
        shift_pattern: 'static_tool',
        shift_length_hours: null,
        recovery_window_enabled: null,
        shift_plan_pdf_url: 'generated_client_side',
        shift_plan_ics_url: 'not_available',
        subbrand: 'shiftparent',
        sub_brand_id: 'shift_parent_os',
      },
    };
  }
  if (path.includes('checkin') || path.includes('conflict')) {
    return {
      toolId: 'conflict_score_quiz',
      acquisitionSource: 'tool_04',
      metadata: {
        conflict_band: 'static_tool_result',
        resource_list_url: '/tools/conflict-assessment#recommended-next-steps',
      },
    };
  }
  return {
    toolId: 'custody_schedule_builder',
    acquisitionSource: 'tool_01',
    metadata: {
      schedule_pattern: 'static_tool',
      export_pdf_available: true,
      export_ics_available: false,
    },
  };
}

async function captureLead(d) {
  const context = toolContextFromLocation();
  const params = new URLSearchParams(window.location.search);
  await fetch('/api/tool-email-captured', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      email: d.email,
      firstName: d.name || null,
      toolId: context.toolId,
      acquisitionSource: context.acquisitionSource,
      subBrandId: context.subBrandId || null,
      timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'America/New_York',
      emailMarketingConsent: true,
      metadata: {
        ...(context.metadata || {}),
        page_url: window.location.href,
        referrer: document.referrer || null,
        utm_source: params.get('utm_source'),
        utm_medium: params.get('utm_medium'),
        utm_campaign: params.get('utm_campaign'),
        utm_content: params.get('utm_content'),
        utm_term: params.get('utm_term'),
        tool_completed_at: new Date().toISOString(),
        captured_from: 'public_static_tool_gate',
      },
    }),
  });
}

/* ---- inject styles once ---- */
(function injectLGStyles() {
  if (document.getElementById('cohaven-lg-css')) return;
  const el = document.createElement('style');
  el.id = 'cohaven-lg-css';
  el.textContent = `
    /* === Backdrop === */
    .lg-back {
      position: fixed; inset: 0; z-index: 9000;
      background: rgba(18,48,45,.56);
      backdrop-filter: blur(8px);
      -webkit-backdrop-filter: blur(8px);
      display: grid; place-items: center; padding: 20px;
      animation: lgFadeIn .2s ease;
    }
    @keyframes lgFadeIn { from { opacity: 0; } to { opacity: 1; } }

    /* === Modal card === */
    .lg-card {
      background: var(--card, #fdfbf6);
      border: 1px solid var(--card-edge, #e7e0d2);
      border-radius: var(--r-xl, 30px);
      box-shadow: var(--shadow-lg, 0 18px 50px rgba(18,48,45,.14));
      padding: 42px 40px 34px;
      max-width: 424px; width: 100%;
      animation: lgSlideUp .28s cubic-bezier(.22,.61,.36,1);
    }
    @keyframes lgSlideUp { from { opacity: 0; transform: translateY(18px); } to { opacity: 1; transform: none; } }

    /* === Wordmark === */
    .lg-wordmark {
      display: inline-flex; align-items: center; gap: 9px;
      font-family: var(--serif, Georgia, serif);
      font-size: 18px; font-weight: 600;
      color: var(--teal-700, #1b4d4a);
      text-decoration: none;
      margin-bottom: 22px;
    }
    .lg-wordmark .lga { fill: var(--teal-700, #1b4d4a); }
    .lg-wordmark .lgb { fill: var(--clay-600, #c96f4c); }

    /* === Text === */
    .lg-headline {
      font-family: var(--serif, Georgia, serif);
      font-size: clamp(21px, 3vw, 26px);
      font-weight: 500; line-height: 1.1;
      color: var(--ink-900, #1c2b28);
      margin: 0 0 10px;
    }
    .lg-sub {
      font-size: 15px;
      color: var(--ink-500, #5f6b64);
      line-height: 1.55; margin: 0 0 24px;
    }

    /* === Form === */
    .lg-form { display: flex; flex-direction: column; gap: 10px; }
    .lg-input {
      font-family: var(--sans, system-ui, sans-serif);
      font-size: 15.5px;
      border: 1.5px solid var(--card-edge, #e7e0d2);
      background: var(--paper, #f6f2ea);
      border-radius: 11px; padding: 12px 15px;
      color: var(--ink-900, #1c2b28);
      outline: none; width: 100%; box-sizing: border-box;
      transition: border-color .18s, box-shadow .18s;
    }
    .lg-input:focus {
      border-color: var(--teal-600, #266b65);
      box-shadow: 0 0 0 3px rgba(38,107,101,.12);
    }
    .lg-err { font-size: 13.5px; color: var(--clay-700, #a8512f); margin: 0; }
    .lg-cta {
      margin-top: 2px !important;
      width: 100%; justify-content: center !important;
      font-size: 15.5px !important; padding: 14px 20px !important;
      border-radius: 999px !important;
    }
    .lg-fine { font-size: 13px; color: var(--ink-300, #8e978f); text-align: center; margin: 13px 0 0; }
    .lg-skip {
      background: none; border: none;
      font-family: var(--sans, sans-serif); font-size: 13px;
      color: var(--ink-300, #8e978f); cursor: pointer;
      text-decoration: underline; text-underline-offset: 3px;
      display: block; margin: 9px auto 0; padding: 2px;
    }
    .lg-skip:hover { color: var(--ink-500, #5f6b64); }

    /* === Inline results gate === */
    .rg-wrap { position: relative; }
    .rg-blur { filter: blur(7px); pointer-events: none; user-select: none; }
    .rg-veil {
      position: absolute; inset: 0; z-index: 6;
      display: flex; flex-direction: column;
      align-items: center; justify-content: center;
      gap: 12px; padding: 28px; text-align: center;
      background: rgba(246,242,234,.92);
      backdrop-filter: blur(2px);
      border-radius: var(--r-lg, 22px);
      border: 1px solid var(--card-edge, #e7e0d2);
    }
    .rg-veil h3 {
      font-family: var(--serif, Georgia, serif);
      font-size: clamp(17px, 2.2vw, 22px);
      color: var(--ink-900, #1c2b28); margin: 0; font-weight: 500;
    }
    .rg-veil p { font-size: 14px; color: var(--ink-500, #5f6b64); margin: 0; max-width: 22em; line-height: 1.5; }

    /* === Print branding === */
    .pb-wrap { display: none !important; }
    .lns-card {
      background: linear-gradient(145deg, var(--teal-800, #12302d), var(--teal-700, #1b4d4a));
      border-radius: var(--r-lg, 22px);
      box-shadow: var(--shadow-sm, 0 8px 26px rgba(18,48,45,.08));
      color: #fff;
      margin-top: 18px;
      padding: 24px;
    }
    .lns-card .lns-kicker {
      color: #cfe0db;
      font-family: var(--mono, monospace);
      font-size: 12px;
      font-weight: 700;
      letter-spacing: .08em;
      margin: 0 0 8px;
      text-transform: uppercase;
    }
    .lns-card h3 {
      color: #fff;
      font-family: var(--serif, Georgia, serif);
      font-size: clamp(22px, 3vw, 30px);
      line-height: 1.08;
      margin: 0;
    }
    .lns-card p:not(.lns-kicker) {
      color: #d4e3df;
      font-size: 15px;
      line-height: 1.55;
      margin: 10px 0 0;
    }
    .lns-actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 18px; }
    .lns-actions .btn-ghost { border-color: rgba(255,255,255,.35); color: #fff; }
    .lns-actions .btn-ghost:hover { background: rgba(255,255,255,.1); border-color: #fff; color: #fff; }

    @media print {
      .pb-wrap {
        display: flex !important; align-items: center;
        justify-content: space-between; gap: 16px;
        padding-bottom: 14px; margin-bottom: 18px;
        border-bottom: 1.5px solid #c8c0b0;
      }
      .pb-left { display: flex; align-items: center; gap: 9px; }
      .pb-svg .pba { fill: #1b4d4a; }
      .pb-svg .pbb { fill: #c96f4c; }
      .pb-name { font-family: Georgia, serif; font-size: 17px; font-weight: 600; color: #1b4d4a; }
      .pb-tool { font-family: monospace; font-size: 11px; color: #8e978f; letter-spacing: .07em; text-transform: uppercase; }
      .pb-right { text-align: right; }
      .pb-url { font-family: monospace; font-size: 13px; color: #1b4d4a; font-weight: 600; display: block; }
      .pb-tagline { font-family: sans-serif; font-size: 11px; color: #8e978f; display: block; margin-top: 1px; }
    }
  `;
  document.head.appendChild(el);
})();

/* ======================================================
   LeadGateModal
   Props: isOpen, onCapture, onDismiss?, headline, subline
====================================================== */
function LeadGateModal({ isOpen, onCapture, onDismiss, headline, subline }) {
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');

  if (!isOpen) return null;

  const submit = async (e) => {
    e.preventDefault();
    if (!email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
      setErr('Please enter a valid email address.');
      return;
    }
    setBusy(true);
    const lead = { email: email.trim().toLowerCase(), name: name.trim() };
    try {
      await captureLead(lead);
      saveLead(lead);
      setTimeout(() => onCapture(lead), 180);
    } catch (error) {
      setBusy(false);
      setErr('We could not unlock this yet. Please try again.');
    }
  };

  return (
    <div className="lg-back">
      <div className="lg-card">
        <a className="lg-wordmark" href="/">
          <svg viewBox="0 0 40 40" width="26" height="26" aria-hidden="true">
            <path className="lga" d="M20 4 6 15v3l14-11 14 11v-3z"/>
            <path className="lgb" d="M13 19c0-1 .8-2 2-2h10c1.2 0 2 1 2 2v13c0 1-.8 2-2 2H15c-1.2 0-2-1-2-2z" opacity=".92"/>
            <rect className="lga" x="18" y="25" width="4" height="9" rx="1"/>
          </svg>
          CoHaven
        </a>
        <h2 className="lg-headline">{headline || 'Your results are ready.'}</h2>
        <p className="lg-sub">{subline || 'Enter your email to unlock everything — and get a copy sent to you.'}</p>
        <form className="lg-form" onSubmit={submit} noValidate="">
          <input className="lg-input" type="text" placeholder="First name (optional)" value={name} onChange={e => setName(e.target.value)} autoComplete="given-name" />
          <input className="lg-input" type="email" placeholder="Email address" value={email} onChange={e => { setEmail(e.target.value); setErr(''); }} autoComplete="email" required="" />
          {err && <p className="lg-err">{err}</p>}
          <button className="btn btn-accent lg-cta" type="submit" disabled={busy}>
            {busy ? 'One moment…' : 'Unlock my results →'}
          </button>
        </form>
        <p className="lg-fine">No spam. Unsubscribe anytime.</p>
        {onDismiss && (
          <button className="lg-skip" type="button" onClick={onDismiss}>Skip for now</button>
        )}
      </div>
    </div>
  );
}

/* ======================================================
   useLeadGate — hook for any tool to use
====================================================== */
function useLeadGate() {
  const [captured, setCaptured] = useState(() => !!getLead());
  const [open, setOpen] = useState(false);
  const pendingRef = React.useRef(null);

  const gate = useCallback((action) => {
    if (captured) { if (action) action(); return; }
    pendingRef.current = action || null;
    setOpen(true);
  }, [captured]);

  const onCapture = useCallback(() => {
    setCaptured(true);
    setOpen(false);
    if (pendingRef.current) {
      const fn = pendingRef.current;
      pendingRef.current = null;
      setTimeout(fn, 80);
    }
  }, []);

  const dismiss = useCallback(() => {
    pendingRef.current = null;
    setOpen(false);
  }, []);

  return { captured, open, gate, onCapture, dismiss };
}

/* ======================================================
   PrintBrand — CoHaven header for print outputs
====================================================== */
function PrintBrand({ toolName }) {
  return (
    <div className="pb-wrap">
      <div className="pb-left">
        <svg className="pb-svg" viewBox="0 0 40 40" width="22" height="22" aria-hidden="true">
          <path className="pba" d="M20 4 6 15v3l14-11 14 11v-3z"/>
          <path className="pbb" d="M13 19c0-1 .8-2 2-2h10c1.2 0 2 1 2 2v13c0 1-.8 2-2 2H15c-1.2 0-2-1-2-2z" opacity=".92"/>
          <rect className="pba" x="18" y="25" width="4" height="9" rx="1"/>
        </svg>
        <span className="pb-name">CoHaven</span>
        <span className="pb-tool">{toolName}</span>
      </div>
      <div className="pb-right">
        <span className="pb-url">cohaven.co</span>
        <span className="pb-tagline">Generated with CoHaven free tools</span>
      </div>
    </div>
  );
}

/* ======================================================
   ResultsGate — inline blur overlay for results panels
====================================================== */
function ResultsGate({ captured, onOpen, heading, body, children }) {
  return (
    <div className="rg-wrap">
      <div className={captured ? '' : 'rg-blur'}>{children}</div>
      {!captured && (
        <div className="rg-veil">
          <h3>{heading || 'See the full breakdown.'}</h3>
          <p>{body || 'Enter your email to unlock your results and get a copy sent to you.'}</p>
          <button className="btn btn-accent" style={{ fontSize: 15 }} onClick={onOpen}>Unlock results →</button>
        </div>
      )}
    </div>
  );
}

function LeadNextStep({ captured, title, body, primaryHref, primaryLabel, secondaryHref, secondaryLabel }) {
  if (!captured) return null;
  return (
    <div className="lns-card no-print">
      <p className="lns-kicker">Unlocked</p>
      <h3>{title || 'Keep this result moving.'}</h3>
      <p>{body || 'Your result is ready. CoHaven can keep schedules, expenses, reminders, and records in one shared place.'}</p>
      <div className="lns-actions">
        <a className="btn btn-accent" href={primaryHref || '/pricing'}>{primaryLabel || 'Start 30-day trial'}</a>
        <a className="btn btn-ghost" href={secondaryHref || '/'}>{secondaryLabel || 'See how CoHaven works'}</a>
      </div>
    </div>
  );
}

Object.assign(window, { LeadGateModal, useLeadGate, PrintBrand, ResultsGate, LeadNextStep });
