window.Kit.Audit = function Audit({ onBooked }) {
  const { Button, Card, Input, Select, Radio, Checkbox, Badge, Eyebrow, Dialog } = window.DS;
  const { Icon, Mask, CountStat, data } = window.Kit;
  const [form, setForm] = React.useState({ domain: '', email: '', budget: '2', goal: 'found', consent: true });
  const [state, setState] = React.useState('idle'); // idle | sending | done | error
  const [showChecks, setShowChecks] = React.useState(false);
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.type === 'checkbox' ? e.target.checked : e.target.value }));
  const valid = /@/.test(form.email) && form.consent;
  const submit = async (e) => {
    e.preventDefault();
    if (!valid) return;
    setState('sending');
    try {
      const response = await fetch('/api/lead', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) });
      if (!response.ok) throw new Error('delivery_failed');
      setState('done');
      onBooked && onBooked(form);
    } catch (_) {
      setState('error');
    }
  };
  const checks = ['Site speed, mobile and accessibility', 'Google Business Profile and map pack', 'Keywords you rank for — and the ones you should', 'Reviews: count, rating and reply rate by location', 'Google Ads: wasted spend and missing tracking', 'Social profiles, posting cadence and reply time', 'Analytics: what is tracked, what is missing', 'Listings consistency across 40+ directories'];
  return (
    <main>
      <section className="section section--first">
        <div className="container grid grid-2" style={{ gap: 'var(--space-16)', alignItems: 'start' }}>
          <div className="stack" style={{ gap: 'var(--space-8)' }}>
            <div className="reveal"><Eyebrow dot pulse>Free · 20 minutes · no deck</Eyebrow></div>
            <h1 className="display"><Mask text="Find out what's holding" delay={60} /><br /><Mask text="your business back." delay={280} /></h1>
            <p className="lead reveal" data-d="2" style={{ maxWidth: '44ch' }}>Tell us your domain. Before the call we run the full audit; on the call we show you what to fix first and what it would cost to have us do it.</p>
            <div className="reveal" data-d="3"><button type="button" className="link" style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer', font: 'inherit' }} onClick={() => setShowChecks(true)}>What we check <span className="arr">→</span></button></div>
            <div className="grid grid-2 reveal" data-d="4" style={{ borderTop: '1px solid var(--border)', paddingTop: 'var(--space-6)', gap: 'var(--space-8)' }}>
              <CountStat value="42" label="Audits this quarter" size="md" />
              <CountStat value="19" label="Days to launch, avg." size="md" />
            </div>
          </div>

          <div className="reveal" data-d="2">
            {state === 'done' ? (
              <Card variant="inverse" padding="lg" className="scale-in">
                <div className="row between"><Eyebrow>Booked</Eyebrow><Badge tone="success" dot>Confirmed</Badge></div>
                <h2 className="h2">We're on it.</h2>
                <p className="body">The audit for <span className="mono" style={{ color: 'var(--text)' }}>{form.domain || 'your site'}</span> starts now. A calendar invite is on its way to <span style={{ color: 'var(--text)', fontWeight: 600 }}>{form.email}</span>.</p>
                <ul className="feature-list">{checks.slice(0, 3).map((c) => <li key={c}><Icon name="Check" size={16} strokeWidth={2.5} />{c}</li>)}</ul>
                <div className="row"><Button variant="primary" href="#/pricing" arrow>See plans meanwhile</Button><Button variant="ghost" onClick={() => setState('idle')}>Book another</Button></div>
              </Card>
            ) : (
              <Card padding="lg">
                <form className="stack" style={{ gap: 'var(--space-5)' }} onSubmit={submit}>
                  <div className="row between"><Eyebrow>Book your audit</Eyebrow><span className="caption mono">Step 01 / 01</span></div>
                  <Input size="lg" label="Your website" placeholder="yourbusiness.com" icon={<Icon name="Globe" size={18} />} value={form.domain} onChange={set('domain')} hint="No site yet? Leave it blank — we'll start from the name." />
                  <Input label="Work email" type="email" placeholder="you@company.com" required value={form.email} onChange={set('email')} error={form.email && !/@/.test(form.email) ? 'Enter a valid email.' : undefined} />
                  <Select label="Monthly budget" value={form.budget} onChange={set('budget')} options={[{ value: '1', label: 'Under $500 / mo' }, { value: '2', label: '$500 – $1,500 / mo' }, { value: '3', label: '$1,500 – $4,000 / mo' }, { value: '4', label: '$4,000+ / mo' }]} />
                  <div className="stack" style={{ gap: 8 }}>
                    <span style={{ fontSize: 'var(--fs-label)', fontWeight: 600, letterSpacing: 'var(--ls-label)', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Main goal</span>
                    <div className="grid grid-2" style={{ gap: 8 }}>
                      {[['found', 'Get found', 'Rank and show up on maps'], ['site', 'A real website', 'Replace the DIY one'], ['leads', 'More leads', 'Calls and forms, tracked'], ['reviews', 'More reviews', 'Asked, collected, answered'], ['social', 'Social handled', 'Posting, replies, monitoring'], ['time', 'My time back', 'Stop managing vendors']].map(([v, l, d]) => (
                        <Radio key={v} name="goal" card label={l} description={d} value={v} checked={form.goal === v} onChange={set('goal')} />
                      ))}
                    </div>
                  </div>
                  <Checkbox label="Email me the audit even if we don't talk." checked={form.consent} onChange={set('consent')} />
                  <Button type="submit" size="xl" fullWidth arrow loading={state === 'sending'} disabled={!valid}>Book the free audit</Button>
                  {state === 'error' && <p role="alert" className="body-sm" style={{ color: 'var(--status-red)' }}>We could not send this yet. Please email hello@l3v3l.com and we will help.</p>}
                  <p className="caption" style={{ textAlign: 'center' }}>No sales deck, no commitment. We reply within one business day.</p>
                </form>
              </Card>
            )}
          </div>
        </div>
      </section>

      <Dialog open={showChecks} onClose={() => setShowChecks(false)} eyebrow="The audit" title="Eight things we check." description="Everything is scored and shown on one page before the call." footer={<Button arrow onClick={() => setShowChecks(false)}>Got it</Button>}>
        <ul className="feature-list" style={{ gap: 12 }}>{checks.map((c) => <li key={c} style={{ fontSize: 'var(--fs-body)', color: 'var(--text)' }}><Icon name="Check" size={18} strokeWidth={2.5} />{c}</li>)}</ul>
      </Dialog>
    </main>
  );
};
