/* Aevitan website — Verify: public authenticity portal, wired to the live verify_serial() backend. */
const DSv = window.AevitanDesignSystem_6a042d;

function Verify() {
  const { Kicker, Input, Button, KeyValue, Card } = DSv;
  // B34 M1: no pre-filled demo code — submitting the old default returned an alarming
  // "Not recognized" card to every curious visitor.
  const [code, setCode] = React.useState('');
  const [phase, setPhase] = React.useState('idle'); // idle | loading | done | disabled
  const [data, setData] = React.useState(null);
  const [hint, setHint] = React.useState('');

  const run = async () => {
    if (!code.trim()) {
      setHint('Enter your code first.');
      setData(null);
      setPhase('idle');
      return;
    }
    setHint('');
    setPhase('loading');
    try {
      const r = await fetch('/api/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code }),
      });
      const j = await r.json();
      if (!j.enabled) { setPhase('disabled'); return; }
      setData(j.result);
      setPhase('done');
    } catch (e) {
      setData({ result: 'not_recognized' });
      setPhase('done');
    }
  };

  const res = data && data.result;
  const genuine = res === 'genuine' || res === 'already_verified';

  return (
    <section className="aevsite-band aevsite-band--top">
      <div className="aevsite-wrap aevsite-reveal aevsite-verifybox">
        <Kicker>Authenticity</Kicker>
        <h2 className="aevsite-h2 big">Verify your product.</h2>
        <p className="muted">Enter the code printed on your packaging to confirm it's genuine and view its certificate.</p>
        <div className="aevsite-vinput">
          <Input mono value={code} placeholder="e.g. AEV-1234-ABCD" onChange={e => setCode(e.target.value)} aria-label="Verification code" />
          <Button variant="primary" onClick={run}>{phase === 'loading' ? 'Checking…' : 'Verify'}</Button>
        </div>
        <p className="muted sm" style={{ marginTop: 8 }}>Find the code printed on your packaging.</p>
        {hint && (
          <p className="muted sm" role="alert" style={{ marginTop: 6 }}>{hint}</p>
        )}

        {phase === 'disabled' && (
          <p className="muted sm" style={{ marginTop: 14 }}>
            Product verification is launching soon. Every Aevitan unit is serialized and traceable, and every batch ships with a third-party Certificate of Analysis.
          </p>
        )}
        {phase !== 'disabled' && (
          <p className="muted sm" style={{ marginTop: 14 }}>
            Every Aevitan unit is serialized and traceable, and every batch ships with a third-party Certificate of Analysis.
          </p>
        )}

        {phase === 'done' && data && (
          <div className="aevsite-vresult">
            <Card accent>
              {genuine ? (
                <div>
                  <div className="aevsite-vstatus">
                    <div className="aevsite-disc ok">✓</div>
                    <div>
                      <div className="aevsite-vstatus__t ok">Genuine: verified by the Aevitan platform</div>
                      <div className="muted sm">{res === 'genuine' ? 'First verification of this unit' : 'This unit has been verified before'}</div>
                    </div>
                  </div>
                  <KeyValue rows={[
                    { label: 'Product', value: (data.product_name || '') + (data.sku ? ' · ' + data.sku : '') },
                    { label: 'Batch', value: data.batch_code || '—', mono: true },
                    { label: 'Serial', value: code, mono: true },
                    { label: 'Third-party CoA', value: data.coa_available ? 'Issued for this batch · on file' : 'Not yet posted' },
                    { label: 'Status', value: 'Sealed · serialized · traceable' },
                  ]} />
                </div>
              ) : (
                <div>
                  <div className="aevsite-vstatus">
                    <div className="aevsite-disc warn">!</div>
                    <div>
                      <div className="aevsite-vstatus__t warn">Not recognized</div>
                      <div className="muted sm">This code was not recognized. If you believe this is an error, contact us before using the product.</div>
                    </div>
                  </div>
                </div>
              )}
            </Card>
          </div>
        )}
      </div>
    </section>
  );
}

window.Verify = Verify;
