/* Payments, shared by the report page, the landing form, the agency form
   and the two admin pages.

   Nothing here decides who owns what: the server says (report.pay.owned) and
   refuses the spending routes with 402 "payment-required" until a purchase
   or a comp is on the record. These pieces only start a Stripe Checkout and
   confirm one when the buyer comes back. Prices come from the server too, so
   a change in Vercel changes every page at once.  */

const PAY_PRODUCT_LABEL = { full_report: 'Full report', benchmark: 'Engine benchmark add-on', benchmark_byok: 'Engine benchmark (your keys)', benchmark_managed: 'Engine benchmark (Lojo keys)' };

function usd(n) {
  if (n === null || n === undefined || n === '') return '';
  return '$' + Number(n).toLocaleString('en-US', { maximumFractionDigits: 0 });
}

/* The price of a product from a pay block, or '' when the page has none. */
function payPrice(pay, product) {
  const p = pay && pay.prices && pay.prices[product];
  return p ? usd(p.usd) : '';
}

/* Where Stripe should send the buyer back: this site. The server accepts an
   https origin or localhost and falls back to lojo.com for anything else. */
function payOrigin() { return window.location.origin; }

/* Start a Checkout Session and go to it. Resolves with the error body when
   the server refuses (already owned, needs the full report first, Stripe
   down), so the caller can show it. */
async function startCheckout(slug, product, email) {
  const d = await apiCall('/api/pay', {
    method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ action: 'checkout', slug, product, origin: payOrigin(), email: email || '' })
  });
  if (d.ok && d.url) { window.location.assign(d.url); return null; }
  return d;
}

/* The buy button. Shows the price; starts Checkout; shows why not. */
function BuyButton({ slug, product, pay, email, label, size, style, ghost }) {
  const [state, setState] = React.useState('idle');
  const [message, setMessage] = React.useState('');
  const price = payPrice(pay, product);
  const go = async () => {
    if (state === 'sending') return;
    setState('sending'); setMessage('');
    try {
      const err = await startCheckout(slug, product, email);
      if (err) { setState('idle'); setMessage(err.message || 'Could not start the payment. Try again in a moment.'); }
    } catch (e) { setState('idle'); setMessage('Could not reach the server. Try again in a moment.'); }
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'stretch', ...(style || {}) }}>
      <button className={'btn ' + (ghost ? 'btn-ghost' : 'btn-primary') + (size === 'lg' ? ' btn-lg' : '')}
        style={{ justifyContent: 'center' }} onClick={go} disabled={state === 'sending'}>
        {state === 'sending' ? 'Opening secure checkout…' : (label || `Buy the ${(PAY_PRODUCT_LABEL[product] || product).toLowerCase()}`)}
        {price && state !== 'sending' && <span style={{ opacity: 0.85 }}>· {price}</span>}
        {state !== 'sending' && <Icon name="arrow-right" size={18} />}
      </button>
      {message && <div style={{ fontSize: 13, color: 'var(--warn)', textAlign: 'center' }}>{message}</div>}
    </div>);
}

function SecurePayNote({ pay }) {
  return (
    <div style={{ display: 'flex', gap: 6, alignItems: 'flex-start', justifyContent: 'center', fontSize: 12, color: 'var(--fg-subtle)', lineHeight: 1.5, textAlign: 'center' }}>
      <Icon name="lock" size={12} style={{ flex: '0 0 auto', marginTop: 3 }} /><span>One-time payment, card or wallet, processed by Stripe. Receipt by email.
      {pay && pay.enabled && !pay.live && <span style={{ color: 'var(--warn)' }}> Test mode: cards are not charged.</span>}</span>
    </div>);
}

/* After Stripe sends the buyer back with ?paid=cs_... : confirm with the
   server (which asks Stripe, never the page) and show the outcome. The code
   comes back here only for a paid session, and is handed to the page so it
   can remember it and unlock the report when it is ready. */
function PaidBanner({ slug, sessionId, onCode, onDone }) {
  const [state, setState] = React.useState('checking');
  const [body, setBody] = React.useState(null);
  const tries = React.useRef(0);
  React.useEffect(() => {
    let stop = false;
    const check = async () => {
      try {
        const d = await apiCall('/api/pay', { method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ action: 'confirm', slug, session_id: sessionId }) });
        if (stop) return;
        if (d.ok && d.paid) { setBody(d); setState('paid'); if (d.access_code && onCode) onCode(d.access_code); if (onDone) onDone(d); return; }
        if (d.ok && !d.paid && tries.current < 10) { tries.current += 1; setTimeout(check, 3000); return; }
        setBody(d); setState('failed');
      } catch (e) { if (!stop) { setBody({ message: 'Could not reach the server.' }); setState('failed'); } }
    };
    check();
    return () => { stop = true; };
  }, [slug, sessionId]);
  const tone = state === 'paid' ? 'good' : state === 'failed' ? 'warn' : 'accent';
  const product = body && PAY_PRODUCT_LABEL[body.product];
  return (
    <div style={{ padding: '16px 18px', borderRadius: 'var(--r-md)', background: `var(--${tone}-bg)`, marginBottom: 22,
      border: '1px solid color-mix(in oklab, var(--' + tone + ') 35%, transparent)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: `var(--${tone})`, marginBottom: 6 }}>
        <Icon name={state === 'checking' ? 'spinner' : state === 'paid' ? 'check' : 'clock'} size={17} stroke={2.4} />
        <span style={{ fontWeight: 600, fontSize: 15 }}>
          {state === 'checking' ? 'Confirming your payment…' : state === 'paid' ? `Payment received: ${product || 'thank you'}` : 'We could not confirm the payment yet'}
        </span>
      </div>
      <div style={{ fontSize: 14, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
        {state === 'checking' && 'A few seconds.'}
        {state === 'paid' && body.product === 'full_report' &&
          <span>
            {body.full_status === 'ready'
              ? 'Your report is ready and this page has been unlocked for you.'
              : 'Your report is being prepared and is ready within 24 hours, usually much sooner. This page unlocks itself when it is; you can close it and come back any time.'}
            {body.access_code && <span> Your access code is <span className="mono" style={{ color: 'var(--fg)', letterSpacing: '0.06em' }}>{body.access_code}</span>. Keep it: it opens this page on any device.</span>}
            {body.emailed && ' We have also emailed it to you.'}
          </span>}
        {state === 'paid' && (body.product || '').startsWith('benchmark') && (body.product === 'benchmark_byok' ? 'The engine benchmark is yours. Add your API keys on the Engine benchmark tab; results follow within 24 hours of the keys arriving.' : 'The engine benchmark is yours. The team runs it on our keys and results appear on the Engine benchmark tab within 24 hours.')}
        {state === 'failed' && ((body && body.message) || 'If your card was charged, reply to the Stripe receipt and the team will sort it out.')}
      </div>
    </div>);
}

/* The Engine benchmark tab when the add-on is not owned: what it is, the
   two ways to buy it, and when it arrives. */
function BenchmarkUpsell({ report, admin }) {
  const pay = report.pay || {};
  const engines = ['ChatGPT', 'Perplexity', 'Gemini', 'Google AI Overviews', 'Claude'];
  const points = [
    'The questions buyers in your category ask, put to every engine several times over',
    'How often you are named, where you rank, and whether your site is cited, with ranges not single numbers',
    'Where competitors win: the prompts they are named on and you are not',
    'Live answers on demand, your name highlighted, whenever you want a fresh read',
  ];
  const needsFull = pay.enabled && !pay.has_full;
  return (
    <div style={{ maxWidth: 820 }}>
      <div style={{ padding: 'clamp(22px,3vw,32px)', borderRadius: 'var(--r-lg)', background: 'var(--navy-2)', border: '1px solid var(--accent)',
        boxShadow: 'var(--sh-accent)' }}>
        <div className="overline" style={{ marginBottom: 10 }}>Add-on · not run yet</div>
        <h3 className="display" style={{ fontSize: 'clamp(22px,3vw,30px)', margin: '0 0 10px' }}>Find out whether AI names you today.</h3>
        <p style={{ fontSize: 15, color: 'var(--fg-muted)', lineHeight: 1.65, margin: '0 0 16px' }}>
          The report tells you what engines <em>can</em> read. The benchmark measures what they actually <em>say</em>{' '}
          when buyers ask, across {engines.slice(0, -1).join(', ')} and {engines[engines.length - 1]}, and repeats
          it so you can see the fixes land. Results appear on this tab within 24 hours of purchase.
        </p>
        <ul style={{ listStyle: 'none', margin: '0 0 20px', padding: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {points.map((t) => <li key={t} style={{ display: 'flex', gap: 10, fontSize: 14.5, lineHeight: 1.5 }}>
            <span style={{ color: 'var(--accent)', flex: '0 0 auto', marginTop: 2 }}><Icon name="check" size={16} stroke={2.4} /></span>{t}</li>)}
        </ul>
        {pay.enabled
          ? <div>
              {needsFull && <div style={{ fontSize: 13.5, color: 'var(--warn)', marginBottom: 12 }}>The benchmark is an add-on to the full report. Get the full report first; this tab then offers it.</div>}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 12 }}>
                <BenchmarkOption pay={pay} slug={report.slug} product="benchmark_byok" title="On your own API keys" disabled={needsFull}
                  body="You add your OpenAI, Perplexity, Gemini and SerpApi keys on this tab after purchase; the engines bill you directly. Claude is included on ours." />
                <BenchmarkOption pay={pay} slug={report.slug} product="benchmark_managed" title="On Lojo's keys" disabled={needsFull}
                  body="Nothing to set up. We run every engine on our own keys and cover the usage." />
              </div>
              <div style={{ marginTop: 12 }}><SecurePayNote pay={pay} /></div>
            </div>
          : <div style={{ fontSize: 13.5, color: 'var(--fg-muted)' }}>Ask the Lojo team to add the benchmark to this report.</div>}
        {admin &&
        <div style={{ marginTop: 14, fontSize: 12.5, color: 'var(--fg-subtle)', lineHeight: 1.6 }}>
          Team: this record has not bought the add-on. Comp it from the Payments panel to run it without a purchase.
        </div>}
      </div>
    </div>);
}

function BenchmarkOption({ pay, slug, product, title, body, disabled }) {
  return (
    <div style={{ padding: '16px 18px', borderRadius: 'var(--r-md)', background: 'var(--navy)', border: '1px solid var(--line-strong)', display: 'flex', flexDirection: 'column', gap: 10 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10 }}>
        <div style={{ fontWeight: 600, fontSize: 15 }}>{title}</div>
        <div className="display" style={{ fontSize: 22 }}>{payPrice(pay, product)}</div>
      </div>
      <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.55, flex: 1 }}>{body}</div>
      {disabled ? <div className="btn btn-ghost" style={{ justifyContent: 'center', opacity: .5, cursor: 'default' }}>Needs the full report</div>
        : <BuyButton slug={slug} product={product} pay={pay} label="Add the benchmark" ghost={product === 'benchmark_byok'} />}
    </div>);
}

/* The Engine benchmark tab after purchase and before results: what is
   happening, and (for the own-keys variant) where the keys go. */
function BenchmarkPending({ report, state, code, admin, onUpdated }) {
  state = state || {};
  const [keys, setKeys] = React.useState({ openai: '', perplexity: '', gemini: '', serpapi: '' });
  const [busy, setBusy] = React.useState(false);
  const [flash, setFlash] = React.useState('');
  const tails = (report.engine_keys || {}).tails || {};
  const byok = state.variant === 'benchmark_byok';
  const save = async () => {
    setBusy(true); setFlash('');
    const d = await apiCall('/api/report', { method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ slug: report.slug, code, action: 'engine-keys', keys }) });
    setBusy(false);
    if (!d.ok) { setFlash(d.message || 'Could not save the keys.'); return; }
    setKeys({ openai: '', perplexity: '', gemini: '', serpapi: '' });
    setFlash('Keys saved, encrypted. The team starts the run within 24 hours.');
    if (onUpdated) onUpdated(d.report);
  };
  const labels = { openai: 'OpenAI (ChatGPT)', perplexity: 'Perplexity', gemini: 'Google Gemini', serpapi: 'SerpApi (Google AI Overviews)' };
  const since = state.requested_at ? new Date(state.requested_at) : null;
  const due = since ? new Date(since.getTime() + 24 * 3600 * 1000) : null;
  return (
    <div style={{ maxWidth: 760, display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ padding: '18px 20px', borderRadius: 'var(--r-lg)', background: 'var(--warn-bg)', border: '1px solid color-mix(in oklab, var(--warn) 40%, transparent)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--warn)', marginBottom: 6 }}>
          <Icon name={state.status === 'running' ? 'spinner' : 'clock'} size={17} stroke={2.4} />
          <span style={{ fontWeight: 600, fontSize: 15 }}>
            {state.status === 'running' ? 'Benchmark running now' : state.status === 'keys_needed' ? 'Benchmark purchased: add your API keys' : 'Benchmark purchased: results within 24 hours'}
          </span>
        </div>
        <div style={{ fontSize: 14, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
          {state.status === 'running' && 'The engines are being asked now. This tab fills in as the run completes.'}
          {state.status === 'keys_needed' && 'You bought the benchmark on your own keys. Add at least one below; the paid engines bill you directly, Claude runs on ours. The team starts the run within 24 hours of the keys arriving.'}
          {state.status === 'purchased' && <span>The Lojo team builds your prompt library, confirms your competitors and runs the engines{byok ? ' on your keys' : ' on our keys'}. Results appear here{due ? ` by ${due.toLocaleString('en-US', { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric' })}` : ' within 24 hours'}, and you are emailed when they land.</span>}
        </div>
      </div>
      {byok &&
      <div style={{ padding: '18px 20px', borderRadius: 'var(--r-lg)', background: 'var(--navy-2)', border: '1px solid var(--line)' }}>
        <div className="overline" style={{ marginBottom: 8 }}>Your API keys</div>
        <div style={{ fontSize: 13.5, color: 'var(--fg-muted)', lineHeight: 1.6, marginBottom: 12 }}>
          Stored encrypted; only the last four characters are ever shown again. Leave an engine blank to skip it. Remove a key by saving it empty after it was set.
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 10 }}>
          {Object.keys(labels).map((k) =>
          <label key={k} style={{ display: 'block', fontSize: 12.5, color: 'var(--fg-muted)' }}>
            {labels[k]}{tails[k] ? <span className="mono" style={{ color: 'var(--good)', marginLeft: 6 }}>set {tails[k]}</span> : ''}
            <input type="password" value={keys[k]} onChange={(e) => setKeys({ ...keys, [k]: e.target.value })} placeholder={tails[k] ? 'replace…' : 'paste key'} autoComplete="off"
              style={{ width: '100%', boxSizing: 'border-box', marginTop: 4, padding: '9px 11px', borderRadius: 'var(--r-md)', fontSize: 13, fontFamily: 'var(--font-mono)', color: 'var(--fg)', background: 'var(--navy)', border: '1px solid var(--line-strong)' }} />
          </label>)}
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginTop: 12, flexWrap: 'wrap' }}>
          <button className="btn btn-primary" style={{ padding: '10px 18px', fontSize: 14 }} disabled={busy || !Object.values(keys).some(Boolean)} onClick={save}>{busy ? 'Saving…' : 'Save keys'}</button>
          {flash && <span style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{flash}</span>}
        </div>
      </div>}
      {admin && <div style={{ fontSize: 12.5, color: 'var(--fg-subtle)' }}>Team: start the run from the Benchmark panel above{byok ? ' once the client has added keys (the runner uses them first)' : ''}. The 24-hour clock started {state.requested_at ? state.requested_at.slice(0, 16).replace('T', ' ') : 'at purchase'}.</div>}
    </div>);
}

Object.assign(window, { usd, payPrice, startCheckout, BuyButton, SecurePayNote, PaidBanner, BenchmarkUpsell, BenchmarkPending, PAY_PRODUCT_LABEL });
