// Shared "Apply" modal — the paid-tier signup form (Origo 2.0 Onboarding).
// Mirrors AuditModal.jsx's structure exactly: same useModalA11y focus trap,
// same busy/error/sent states, same honeypot, same country dial-code picker.
// Posts straight to the CRM's public signup route (a different service and a
// different route from /api/audit, which goes through the Vercel function).
//
// Tier data (window.ORIGO_TIERS) is the single source of truth for price and
// inclusions per tier — Pricing.jsx renders the same array for its cards, so
// the modal's recap and the pricing cards can never drift apart.
window.ORIGO_TIERS = [
  {
    id: 'tier1',
    name: 'Tier 1',
    price: '$499',
    period: '/ month',
    tag: 'Self-serve. You run it, we build the engine.',
    features: [
      'Origo Engine configured for your brand',
      '25 buyer-intent prompts tracked',
      'Monitoring across ChatGPT, Perplexity and Google AI Overview and AI Mode',
      'Automated run every week, scheduled to your local time',
      'Full dashboard: citations, competitors and recommendations',
      'Generate content briefs and schema fixes on demand, your team implements',
    ],
  },
  {
    id: 'tier2',
    name: 'Tier 2',
    price: '$999',
    period: '/ month',
    tag: 'More prompts, more platform coverage.',
    features: [
      'Origo Engine configured for your brand',
      '50 buyer-intent prompts tracked',
      'Monitoring across ChatGPT, Perplexity, Google AI Overview, AI Mode and Gemini',
      'Claude available as a paid add-on',
      'Automated run every week, scheduled to your local time',
      'Full dashboard: citations, competitors and recommendations',
      'Generate content briefs and schema fixes on demand, your team implements',
    ],
  },
  {
    id: 'enterprise',
    name: 'Enterprise',
    price: 'From $5,000',
    period: '/ month',
    tag: 'Fully managed, end to end.',
    features: [
      'Origo Engine configured for your brand',
      'Monitoring across ChatGPT, Perplexity, Gemini and Claude',
      'Custom prompt count, scoped to your program',
      'GEO content written and published every month by our team',
      'Schema and llms.txt implemented by our team',
      'Human QC on every citation and recommendation',
      'Dedicated account manager, direct Slack or WhatsApp access',
    ],
  },
];

// The CRM's public signup route. Local dev runs the CRM API on :8003; the
// site itself (this file) is served from :3000 (vercel dev), a different
// origin, so this can't be a relative /api path like /api/audit is. The
// site doesn't have an existing env-detection helper, so this is the
// smallest sensible check: dev is whichever hostname vercel dev serves the
// site from locally, everything else is production.
function origoSignupUrl() {
  const h = location.hostname;
  const isLocal = h === 'localhost' || h === '127.0.0.1';
  return (isLocal ? 'http://localhost:8003' : 'https://crm.origolabs.ai') + '/api/public/signup';
}

// The three tiers as a comparison matrix rather than one tier's bullet list:
// a buyer choosing a plan needs to see what the OTHER plans give them, which a
// single list structurally cannot show. Rows are the capabilities that differ;
// a row that is identical across all three is not worth a row.
const TIER_MATRIX = [
  { label: 'Prompts tracked', v: { tier1: '25', tier2: '50', enterprise: 'Custom' } },
  { label: 'ChatGPT, Perplexity, Google AI Overview + AI Mode', v: { tier1: true, tier2: true, enterprise: true } },
  { label: 'Gemini', v: { tier1: false, tier2: true, enterprise: true } },
  { label: 'Claude', v: { tier1: false, tier2: 'Add-on', enterprise: true } },
  { label: 'Weekly automated run', v: { tier1: true, tier2: true, enterprise: true } },
  { label: 'Full dashboard', v: { tier1: true, tier2: true, enterprise: true } },
  { label: 'Content briefs and schema fixes', v: { tier1: 'You implement', tier2: 'You implement', enterprise: 'We implement' } },
  { label: 'Content written and published monthly', v: { tier1: false, tier2: false, enterprise: true } },
  { label: 'Human QC on every citation', v: { tier1: false, tier2: false, enterprise: true } },
  { label: 'Dedicated account manager', v: { tier1: false, tier2: false, enterprise: true } },
];

function MatrixCell({ value }) {
  if (value === true) {
    return <span className="tm-yes" aria-label="Included"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2.6" aria-hidden="true"><path d="M20 6L9 17l-5-5" /></svg></span>;
  }
  if (value === false) return <span className="tm-no" aria-label="Not included">&ndash;</span>;
  return <span className="tm-txt">{value}</span>;
}

// Rendered on the pricing page, not in the form: someone opening Apply has
// already chosen. See Pricing.jsx.
function TierMatrix({ tierId, onPick }) {
  return (
    <div className="tiermatrix" role="table" aria-label="Plan comparison">
      <div className="tm-head" role="row">
        <span role="columnheader" />
        {window.ORIGO_TIERS.map(t => (
          <button
            key={t.id}
            type="button"
            role="columnheader"
            className={'tm-col' + (tierId === t.id ? ' on' : '')}
            onClick={() => onPick(t.id)}
          >
            <span className="tm-name">{t.name}</span>
            <span className="tm-price">{t.price === 'From $5,000' ? 'from $5,000' : t.price}</span>
          </button>
        ))}
      </div>
      {TIER_MATRIX.map((row, i) => (
        <div className="tm-row" role="row" key={i}>
          <span className="tm-label" role="cell">{row.label}</span>
          {window.ORIGO_TIERS.map(t => (
            <span key={t.id} className={'tm-cell' + (tierId === t.id ? ' on' : '')} role="cell">
              <MatrixCell value={row.v[t.id]} />
            </span>
          ))}
        </div>
      ))}
    </div>
  );
}

function ApplyModal({ tier, initialInterval, onClose }) {
  const [sent, setSent] = React.useState(false);
  const [sentEmail, setSentEmail] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  const ref = useModalA11y(onClose);
  const [selectedTier, setSelectedTier] = React.useState(tier && window.ORIGO_TIERS.some(t => t.id === tier) ? tier : 'tier1');
  const [isAgency, setIsAgency] = React.useState(false);
  // Billing interval: the pricing page's Monthly/Annual toggle carries in as initialInterval;
  // the CRM charges whatever is stored on the lead (staff can still change it before sending the link).
  const [interval, setBillingInterval] = React.useState(initialInterval === 'annual' ? 'annual' : 'monthly');
  // analytics: modal open / close-without-submit — same pattern as AuditModal, its own flags.
  React.useEffect(() => {
    window.__origoApplyOpen = true;
    window.__origoApplySubmitted = false;
    if (window.__origoUser) { window.__origoUser.apply_opened = true; window.__origoSaveUser && window.__origoSaveUser(); }
    window.otrack && window.otrack('apply_modal_open', { tier: selectedTier, returning_opener: !!(window.__origoUser && window.__origoUser.visits > 1) });
    return () => { window.__origoReportAbandon && window.__origoReportAbandon('apply'); };
    // eslint-disable-next-line
  }, []);
  const countries = window.ORIGO_COUNTRIES || [{ n: 'United States', d: '+1' }];
  const [ci, setCi] = React.useState(typeof window.__origoGeoIdx === 'number' ? window.__origoGeoIdx : Math.max(0, countries.findIndex(c => c.n === 'United States')));
  const companyR = React.useRef(null), siteR = React.useRef(null), nameR = React.useRef(null), emailR = React.useRef(null), phoneR = React.useRef(null);
  const promptR = React.useRef(null);
  const agHolderR = React.useRef(null), agPersonR = React.useRef(null), agEmailR = React.useRef(null), agIndustryR = React.useRef(null);
  const hpR = React.useRef(null);

  // Turnstile renders itself only for widgets present when its script loads.
  // This modal mounts later, so it must be rendered explicitly, and the
  // widget id kept so getResponse reads THIS widget rather than guessing.
  const tsBoxR = React.useRef(null);
  const tsIdR = React.useRef(null);
  React.useEffect(() => {
    let cancelled = false;
    function render() {
      if (cancelled || !tsBoxR.current || tsIdR.current !== null) return true;
      if (!(window.turnstile && window.turnstile.render)) return false;
      tsIdR.current = window.turnstile.render(tsBoxR.current, {
        // Cloudflare's own documented ALWAYS-PASSES test key. Correct for
        // localhost and a demo; swap for the real sitekey before publishing
        // or this gate protects nothing.
        sitekey: '0x4AAAAAAE9Bz7I-9PIwcSN6',
        theme: 'dark',
      });
      return true;
    }
    if (!render()) {
      // The script tag is async, so it may not be there on first paint.
      const t = setInterval(() => { if (render()) clearInterval(t); }, 150);
      setTimeout(() => clearInterval(t), 10000);
      return () => { cancelled = true; clearInterval(t); };
    }
    return () => { cancelled = true; };
  }, []);

  const submit = async () => {
    if (busy) return;
    setErr('');
    const phoneNum = ((phoneR.current && phoneR.current.value) || '').trim();
    const emailRe = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
    const payload = {
      tier: selectedTier,
      billing_interval: interval,
      company_name: ((companyR.current && companyR.current.value) || '').trim(),
      website: ((siteR.current && siteR.current.value) || '').trim(),
      contact_name: ((nameR.current && nameR.current.value) || '').trim(),
      contact_email: ((emailR.current && emailR.current.value) || '').trim(),
      contact_phone: phoneNum ? (((countries[ci] && countries[ci].d) || '') + ' ' + phoneNum) : null,
      is_agency: isAgency,
      enterprise_prompt_count: null,
      agency_account_holder: null,
      agency_contact_person: null,
      agency_contact_email: null,
      agency_client_industry: null,
      // Honeypot. A real visitor never sees or fills this field (hidden off-
      // screen below); a form-filling bot usually does. Matches the CRM's
      // public signup "hp" field so both sides agree on the name.
      hp: ((hpR.current && hpR.current.value) || '').trim(),
    };
    if (!payload.company_name || !payload.website || !payload.contact_name || !payload.contact_email) {
      setErr('Please fill in all required fields.');
      window.otrack && window.otrack('apply_form_error', { error_type: 'missing_required' });
      return;
    }
    if (!emailRe.test(payload.contact_email)) {
      setErr('Please enter a valid work email.');
      window.otrack && window.otrack('apply_form_error', { error_type: 'invalid_email' });
      return;
    }
    if (selectedTier === 'enterprise') {
      const n = parseInt((promptR.current && promptR.current.value) || '', 10);
      if (!n || n < 1) {
        setErr('Please enter how many prompts you need.');
        window.otrack && window.otrack('apply_form_error', { error_type: 'invalid_enterprise_count' });
        return;
      }
      payload.enterprise_prompt_count = n;
    }
    if (isAgency) {
      payload.agency_account_holder = ((agHolderR.current && agHolderR.current.value) || '').trim();
      payload.agency_contact_person = ((agPersonR.current && agPersonR.current.value) || '').trim();
      payload.agency_contact_email = ((agEmailR.current && agEmailR.current.value) || '').trim();
      payload.agency_client_industry = ((agIndustryR.current && agIndustryR.current.value) || '').trim() || null;
      if (!payload.agency_account_holder || !payload.agency_contact_person || !payload.agency_contact_email) {
        setErr('Please fill in the agency details.');
        window.otrack && window.otrack('apply_form_error', { error_type: 'missing_agency_fields' });
        return;
      }
      if (!emailRe.test(payload.agency_contact_email)) {
        setErr('Please enter a valid agency contact email.');
        window.otrack && window.otrack('apply_form_error', { error_type: 'invalid_agency_email' });
        return;
      }
    }
    setBusy(true);
    window.otrack && window.otrack('apply_submit_attempt', { tier: selectedTier, is_agency: isAgency, has_phone: !!payload.contact_phone });
    try {
      const r = await fetch(origoSignupUrl(), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
      const body = await r.json().catch(() => null);
      if (!r.ok) {
        const serverMessage = body && body.error && body.error.message;
        throw new Error(serverMessage || 'failed');
      }
      setSentEmail(payload.contact_email);
      setSent(true);
      window.__origoApplySubmitted = true;
      if (window.__origoUser) { window.__origoUser.apply_submitted = true; window.__origoSaveUser && window.__origoSaveUser(); }
      const value = selectedTier === 'enterprise' ? 5000 : (selectedTier === 'tier2' ? 999 : 499);
      window.otrack && window.otrack('generate_lead', {
        lead_type: 'apply', tier: selectedTier, is_agency: isAgency,
        visits_before_convert: (window.__origoUser && window.__origoUser.visits) || 1,
        value, currency: 'USD',
      });
    } catch (e) {
      setErr((e && e.message && e.message !== 'failed') ? e.message : 'Something went wrong. Please email admin@origolabs.ai directly.');
      window.otrack && window.otrack('apply_form_error', { error_type: 'request_failed' });
    } finally { setBusy(false); }
  };

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal modal-lg" ref={ref} tabIndex={-1} style={{ position: 'relative' }} role="dialog" aria-modal="true" aria-label="Apply" onClick={e => e.stopPropagation()}>
        <button className="modal-x" onClick={onClose} aria-label="Close">×</button>
        {!sent ? (
          <React.Fragment>
            <h3>Apply now</h3>
            <p>Tell us about the company. We will review it and follow up.</p>

            <div className="field-row" style={{ '--d': '.04s' }}>
              <label className="flbl">Plan<span className="req">*</span></label>
              <div className="tierpick" role="radiogroup" aria-label="Plan">
                {window.ORIGO_TIERS.map(t => (
                  <button
                    key={t.id}
                    type="button"
                    role="radio"
                    aria-checked={selectedTier === t.id}
                    className={'tierpick-opt' + (selectedTier === t.id ? ' on' : '')}
                    onClick={() => setSelectedTier(t.id)}
                  >
                    <span className="tp-name">{t.name}</span>
                    <span className="tp-price">{t.price === 'From $5,000' ? 'from $5,000' : t.price + '/mo'}</span>
                  </button>
                ))}
              </div>
              <div className="tierpick" role="radiogroup" aria-label="Billing" style={{ gridTemplateColumns: 'repeat(2,minmax(0,1fr))', marginTop: 8 }}>
                {[{ v: 'monthly', t: 'Monthly', s: 'billed monthly' }, { v: 'annual', t: 'Annual', s: 'save 15%' }].map(o => (
                  <button
                    key={o.v}
                    type="button"
                    role="radio"
                    aria-checked={interval === o.v}
                    className={'tierpick-opt' + (interval === o.v ? ' on' : '')}
                    onClick={() => setBillingInterval(o.v)}
                  >
                    <span className="tp-name">{o.t}</span>
                    <span className="tp-price">{o.s}</span>
                  </button>
                ))}
              </div>
            </div>

            <div className="field-row" style={{ '--d': '.08s' }}><label className="flbl">Company name<span className="req">*</span></label><input ref={companyR} className="field" placeholder="Acme Inc." maxLength={255} /></div>
            <div className="field-row" style={{ '--d': '.12s' }}><label className="flbl">Website<span className="req">*</span></label><div className="field field-pre"><span className="pre">https://</span><input ref={siteR} placeholder="yourbrand.com" maxLength={300} /></div></div>
            <div className="field-row" style={{ '--d': '.16s' }}><label className="flbl">Contact name<span className="req">*</span></label><input ref={nameR} className="field" placeholder="Jane Mercer" maxLength={255} /></div>
            <div className="field-row" style={{ '--d': '.20s' }}><label className="flbl">Work email<span className="req">*</span></label><input ref={emailR} type="email" className="field" placeholder="jane@company.com" maxLength={255} /></div>
            <div className="field-row" style={{ '--d': '.24s' }}><label className="flbl">Phone<span className="opt">optional</span></label><div className="field field-pre"><select className="pre pre-sel" value={ci} onChange={e => setCi(+e.target.value)} aria-label="Country dial code">{countries.map((c, i) => <option key={c.n} value={i}>{c.d}  {c.n}</option>)}</select><input ref={phoneR} placeholder="555 0142" /></div></div>

            {selectedTier === 'enterprise' && (
              <div className="field-row" style={{ '--d': '.28s' }}><label className="flbl">Prompts needed<span className="req">*</span></label><input ref={promptR} type="number" min="1" step="1" className="field" placeholder="e.g. 200" /></div>
            )}

            <label className="chk-row">
              <input type="checkbox" className="chk" checked={isAgency} onChange={e => setIsAgency(e.target.checked)} />
              <span className="chk-box" aria-hidden="true">
                <svg viewBox="0 0 16 16" fill="none"><path d="M3.5 8.4l3 3 6-6.5" stroke="currentColor" strokeWidth="2.1" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </span>
              <span>I'm applying on behalf of a client</span>
            </label>

            {isAgency && (
              <div className="agency-fields">
                <div className="field-row"><label className="flbl">Agency name<span className="req">*</span></label><input ref={agHolderR} className="field" placeholder="Your agency" maxLength={255} /></div>
                <div className="field-row"><label className="flbl">Contact person<span className="req">*</span></label><input ref={agPersonR} className="field" placeholder="Who we should talk to" maxLength={255} /></div>
                <div className="field-row"><label className="flbl">Agency contact email<span className="req">*</span></label><input ref={agEmailR} type="email" className="field" placeholder="you@agency.com" maxLength={255} /></div>
                <div className="field-row"><label className="flbl">Client's industry<span className="opt">optional</span></label><input ref={agIndustryR} className="field" placeholder="e.g. hospitality" maxLength={255} /></div>
              </div>
            )}

            {/* Honeypot: off-screen, unfocusable, never shown to a sighted or keyboard user. */}
            <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', top: 'auto', width: 1, height: 1, overflow: 'hidden' }}>
              <label htmlFor="origo-apply-hp">Leave this field blank</label>
              <input id="origo-apply-hp" ref={hpR} name="hp" tabIndex={-1} autoComplete="off" />
            </div>
            {/* Cloudflare Turnstile. The engine verifies this token server
                side and fails CLOSED, so an empty one is refused rather than
                waved through. The sitekey below is Cloudflare's own
                documented ALWAYS-PASSES test key: correct for localhost and
                for a demo, and it must be swapped for the real sitekey
                before this page is published, or the gate protects nothing. */}
            <div ref={tsBoxR} style={{ margin: '4px 0 10px' }} />
            {err && <p style={{ color: '#ff6b6b', fontSize: '13px', margin: '0 0 8px' }}>{err}</p>}
            <button className="btn btn-primary btn-md" style={{ width: '100%', marginTop: '4px', '--d': '.36s' }} onClick={submit} disabled={busy}>{busy ? 'Sending…' : 'Submit application'}</button>
          </React.Fragment>
        ) : (
          <div className="modal-ok">
            <div className="check">Check your email</div>
            <h3>Your application is not complete yet.</h3>
            <p style={{ margin: '0 auto' }}>We sent a confirmation link to <strong>{sentEmail}</strong>. Open it and confirm your email, and we will start reviewing your application.</p>
            <button className="btn btn-ghost btn-md" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ApplyModal });

window.TierMatrix = TierMatrix;
