// Hero console rebuilt as an actual lead-magnet: free instant website audit
const HeroAudit = () => {
  const isMobile = useIsMobile();
  const [stage, setStage] = useState('input'); // input | running | gated
  const [domain, setDomain] = useState('');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [output, setOutput] = useState([]);
  const [sent, setSent] = useState(false);
  const [err, setErr] = useState('');

  const cleanDomain = (d) => d.replace(/^https?:\/\//, '').replace(/^www\./, '').replace(/\/.*$/, '').trim().toLowerCase();

  const runAudit = () => {
    const d = cleanDomain(domain);
    if (!d || !/\./.test(d)) { setErr('Looks like we need a real domain (e.g. acme.com.au)'); return; }
    setErr('');
    setStage('running');
    setOutput([]);

    const script = [
      { t: 200,  l: `$ pp audit ${d}`, kind: 'cmd' },
      { t: 700,  l: 'fetching homepage…', kind: 'sys' },
      { t: 1300, l: '✓ SSL valid, TLS 1.3', kind: 'ok' },
      { t: 1700, l: '⚠ LCP 3.4s on 4G — slower than 72% of sites', kind: 'warn' },
      { t: 2200, l: '✓ schema: LocalBusiness detected', kind: 'ok' },
      { t: 2700, l: '⚠ 14 winnable keywords you\'re not ranking for', kind: 'warn' },
      { t: 3200, l: '⚠ title tags missing on 6 pages', kind: 'warn' },
      { t: 3700, l: '→ 4 quick wins worth an estimated $2–4k/mo', kind: 'hi' },
      { t: 4200, l: 'full report ready · enter email to unlock', kind: 'hi' },
    ];
    script.forEach(({ t, l, kind }) => {
      setTimeout(() => setOutput(prev => [...prev, { l, kind }]), t);
    });
    setTimeout(() => setStage('gated'), 4400);
  };

  const submitEmail = async (e) => {
    e.preventDefault();
    if (!name.trim()) { setErr('What\'s your first name?'); return; }
    if (!/^\S+@\S+\.\S+$/.test(email)) { setErr('That email doesn\'t look right'); return; }
    setErr('');
    try {
      const res = await fetch('https://api.theprofitplatform.com.au/api/v2/audit/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          url: 'https://' + cleanDomain(domain),
          email: email.trim(),
          contactName: name.trim(),
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || data.success === false) {
        setErr((data.errors && data.errors[0]) || data.error || 'Something went wrong — try again?');
        return;
      }
      setSent(true);
    } catch (e) {
      setErr('Network error. Email us directly: hello@theprofitplatform.com.au');
    }
  };

  const kindStyle = {
    cmd: { color: 'var(--fg)' },
    sys: { color: 'var(--fg-3)' },
    ok:  { color: 'var(--good)' },
    warn:{ color: 'var(--warn)' },
    hi:  { color: 'var(--accent)', fontWeight: 500 }
  };

  return (
    <div className="glass" style={{ padding: 0, overflow: 'hidden', position: 'relative' }}>
      {/* chrome */}
      <div style={{
        display:'flex', alignItems:'center', gap: 12,
        padding: isMobile ? '12px 14px' : '14px 18px', borderBottom: '1px solid var(--line)'
      }}>
        <div style={{display:'flex', gap:6}}>
          <span style={{width:11,height:11,borderRadius:'50%',background:'oklch(0.7 0.16 25)'}}/>
          <span style={{width:11,height:11,borderRadius:'50%',background:'oklch(0.82 0.15 85)'}}/>
          <span style={{width:11,height:11,borderRadius:'50%',background:'oklch(0.75 0.17 145)'}}/>
        </div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--fg-3)', flex: 1, textAlign:'center' }}>
          {isMobile ? 'free audit · 60s' : 'free instant audit · no credit card · no spam'}
        </div>
        <div className="mono" style={{ fontSize: 11, color: stage === 'running' ? 'var(--accent)' : 'var(--fg-3)', display:'flex', alignItems:'center', gap:6 }}>
          <span style={{width:6,height:6,borderRadius:'50%',background: stage === 'running' ? 'var(--accent)' : 'var(--good)'}}/>
          {stage === 'running' ? 'running' : 'ready'}
        </div>
      </div>

      <div style={{
        padding: isMobile ? '24px 20px' : '32px 30px',
        background: 'var(--terminal-bg)',
        minHeight: isMobile ? 360 : 460,
        display:'flex', flexDirection:'column'
      }}>
        {/* pitch */}
        <div style={{ marginBottom: isMobile ? 20 : 26 }}>
          <div className="mono" style={{ fontSize: 11, color:'var(--accent)', letterSpacing:'.18em', textTransform:'uppercase', fontWeight: 500 }}>
            Free website audit · 60 seconds
          </div>
          <div style={{
            fontFamily:'var(--serif)',
            fontSize: 'clamp(26px, 7vw, 38px)',
            letterSpacing:'-0.025em', marginTop: 10, lineHeight: 1.08
          }}>
            See what we'd fix first <span style={{fontStyle:'italic', color:'var(--accent)'}}>on your site.</span>
          </div>
          <div style={{
            fontSize: isMobile ? 14 : 15,
            color:'var(--fg-2)', marginTop: 12, lineHeight: 1.5, maxWidth: '95%'
          }}>
            Speed, SEO, missed keywords, quick wins — the full PDF in your inbox in 5 minutes.
          </div>
        </div>

        {/* INPUT */}
        {stage === 'input' && (
          <form onSubmit={(e) => { e.preventDefault(); runAudit(); }} style={{ display:'flex', flexDirection:'column', gap: 12 }}>
            <div style={{
              display: 'flex',
              flexDirection: isMobile ? 'column' : 'row',
              alignItems: 'stretch',
              border:'1px solid var(--line-2)', borderRadius: 12,
              background: 'var(--input-bg)', overflow:'hidden',
              boxShadow: '0 1px 0 oklch(1 0 0 / .04) inset',
            }}>
              <div style={{ display: 'flex', alignItems: 'stretch', flex: 1 }}>
                <span className="mono" style={{
                  padding: '16px 12px 16px 16px', color:'var(--fg-3)', fontSize: 14,
                  borderRight:'1px solid var(--line)', background:'var(--card-bg-2)',
                  display:'flex', alignItems:'center', flexShrink: 0,
                }}>https://</span>
                <input
                  value={domain}
                  onChange={e => setDomain(e.target.value)}
                  placeholder="yourbusiness.com.au"
                  autoComplete="off"
                  className="mono"
                  style={{
                    flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'transparent',
                    padding: '16px 14px', color: 'var(--fg)', fontSize: 16,
                  }}/>
              </div>
              <button type="submit" className="btn btn-accent" style={{
                borderRadius: 0,
                padding: isMobile ? '14px 22px' : '0 26px',
                fontSize: 15, fontWeight: 500,
                justifyContent: 'center',
                borderTop: isMobile ? '1px solid var(--line-2)' : 'none',
              }}>
                Run audit <Icon name="arrow" size={16}/>
              </button>
            </div>
            {err && <div className="mono" style={{ fontSize: 12, color: 'var(--warn)' }}>⚠ {err}</div>}
            <div className="mono" style={{ fontSize: 11, color:'var(--fg-3)', letterSpacing:'.06em' }}>
              try it with any site — ours, a competitor's, your old one
            </div>
          </form>
        )}

        {/* RUNNING / GATED */}
        {stage !== 'input' && (
          <>
            <div className="mono" style={{ fontSize: isMobile ? 12 : 13, lineHeight: 1.9, flex: 1 }}>
              {output.map((o, i) => (
                <div key={i} style={{...kindStyle[o.kind], opacity: 0, animation: 'fadein .3s forwards'}}>
                  <span style={{color:'var(--fg-3)', marginRight:10}}>{String(i+1).padStart(2,'0')}</span>
                  {o.l}
                </div>
              ))}
              {stage === 'running' && <span className="cursor" style={{height:14, verticalAlign:'middle'}}/>}
            </div>

            {stage === 'gated' && !sent && (
              <form onSubmit={submitEmail} style={{
                marginTop: 18, paddingTop: 18, borderTop: '1px dashed var(--line-2)',
                display:'flex', flexDirection:'column', gap: 10,
              }}>
                <div className="mono" style={{ fontSize: 10, color:'var(--fg-3)', letterSpacing:'.12em', textTransform:'uppercase' }}>
                  where should we send the full report?
                </div>
                <div style={{
                  display:'flex', alignItems:'stretch',
                  border:'1px solid var(--line-2)', borderRadius: 10,
                  background: 'var(--input-bg)', overflow:'hidden',
                }}>
                  <input
                    value={name}
                    onChange={e => setName(e.target.value)}
                    placeholder="Your first name"
                    autoComplete="given-name"
                    style={{
                      flex: 1, border: 'none', outline: 'none', background: 'transparent',
                      padding: '14px 16px', color: 'var(--fg)', fontSize: 16,
                    }}/>
                </div>
                <div style={{
                  display:'flex', flexDirection: isMobile ? 'column' : 'row',
                  alignItems:'stretch',
                  border:'1px solid var(--line-2)', borderRadius: 10,
                  background: 'var(--input-bg)', overflow:'hidden',
                }}>
                  <input
                    value={email}
                    onChange={e => setEmail(e.target.value)}
                    placeholder="you@yourbusiness.com.au"
                    type="email"
                    autoComplete="email"
                    style={{
                      flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'transparent',
                      padding: '14px 16px', color: 'var(--fg)', fontSize: 16,
                    }}/>
                  <button type="submit" className="btn btn-accent" style={{
                    borderRadius: 0,
                    padding: isMobile ? '14px 22px' : '0 22px',
                    fontSize: 13,
                    justifyContent: 'center',
                    borderTop: isMobile ? '1px solid var(--line-2)' : 'none',
                  }}>
                    Email me the PDF <Icon name="arrow" size={14}/>
                  </button>
                </div>
                {err && <div className="mono" style={{ fontSize: 11, color: 'var(--warn)' }}>⚠ {err}</div>}
                <div className="mono" style={{ fontSize: 10, color:'var(--fg-3)' }}>
                  one email, the report, no mailing list. promise.
                </div>
              </form>
            )}

            {sent && (
              <div style={{
                marginTop: 18, paddingTop: 18, borderTop: '1px dashed var(--line-2)',
                display:'flex', gap: 12, alignItems:'flex-start',
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: '50%', background:'var(--good)',
                  display:'flex', alignItems:'center', justifyContent:'center', color:'var(--bg)', flexShrink: 0,
                }}>
                  <Icon name="check" size={18} stroke={2.5}/>
                </div>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 500 }}>Thanks {name.split(' ')[0]} — report is on its way to {email}.</div>
                  <div style={{ fontSize: 13, color:'var(--fg-2)', marginTop: 4, lineHeight: 1.5 }}>
                    Arrives in about 5 minutes. If you want to chat through it, just reply — Sam or Avani will pick it up.
                  </div>
                  <button onClick={() => { setStage('input'); setDomain(''); setName(''); setEmail(''); setSent(false); setOutput([]); }}
                    className="mono" style={{
                      marginTop: 10, padding: 0, background: 'none', border: 'none',
                      color: 'var(--accent)', fontSize: 11, cursor: 'pointer', textDecoration: 'underline',
                    }}>
                    audit another site →
                  </button>
                </div>
              </div>
            )}
          </>
        )}

        {stage === 'input' && (
          <div className="grid-3" style={{ marginTop: 'auto', paddingTop: 26 }}>
            {[
              ['speed', 'real LCP / 4G'],
              ['SEO', '12 checks'],
              ['keywords', 'missed wins'],
            ].map(([a, b]) => (
              <div key={a} style={{
                padding: '14px 14px', borderRadius: 10,
                background:'var(--card-bg-2)', border:'1px solid var(--line)',
              }}>
                <div className="mono" style={{ fontSize: 11, color:'var(--accent)', letterSpacing:'.14em', textTransform:'uppercase', fontWeight: 500 }}>{a}</div>
                <div style={{ fontSize: 13, color:'var(--fg-2)', marginTop: 4 }}>{b}</div>
              </div>
            ))}
          </div>
        )}
      </div>

      <style>{`@keyframes fadein { to { opacity: 1; } }`}</style>
    </div>
  );
};

const Hero = () => {
  const ref = useReveal();
  const isMobile = useIsMobile();
  return (
    <section id="hero" style={{
      paddingTop: isMobile ? 100 : 140,
      paddingBottom: isMobile ? 40 : 60,
      position: 'relative',
    }}>
      <div className="container" style={{ position: 'relative', zIndex: 1 }}>
        <div ref={ref} className="reveal split">
          <div>
            <div style={{display:'flex', gap:10, marginBottom: 28, flexWrap:'wrap'}}>
              <span className="chip">
                <span style={{width:6,height:6,borderRadius:'50%',background:'var(--good)'}}/>
                taking on 2 new clients this month
              </span>
            </div>
            <h1 className="h-display">
              A small studio that does the <span className="serif-i" style={{color:'var(--accent)'}}>unglamorous</span> work of growing a business.
            </h1>
            <p style={{
              fontSize: isMobile ? 16 : 19, lineHeight: 1.5, color: 'var(--fg-2)',
              maxWidth: 540, marginTop: 28, marginBottom: 36
            }}>
              Websites, ads, SEO, social, IT and a bit of AI — handled by two people who pick up the phone. No account managers, no slide decks, no retainers we can't explain.
            </p>
            <div style={{ display:'flex', gap: 12, flexWrap:'wrap' }}>
              <a href="#contact" className="btn btn-accent">Say hello <Icon name="arrow" size={14}/></a>
              <a href="#work" className="btn btn-ghost">See what we've shipped</a>
            </div>
          </div>

          <HeroAudit />
        </div>
      </div>
    </section>
  );
};

window.Hero = Hero;
