// ─────────────────────────────────────────────────────────
//  AI Site Audit — paste URL → Claude analyzes → 3 fixes
// ─────────────────────────────────────────────────────────

const { useState: useStateAU } = React;

const AUDIT_STEPS = [
  'Probing TTFB across 4 regions',
  'Running Lighthouse heuristics',
  'Scanning lead-capture surfaces',
  'Synthesizing improvement vectors',
];

function AISiteAudit() {
  const [url, setUrl] = useStateAU('');
  const [phase, setPhase] = useStateAU(-1);       // -1 idle, 0..3 step, 4 done
  const [result, setResult] = useStateAU(null);
  const [error, setError] = useStateAU(null);

  const run = async () => {
    let cleanUrl = url.trim();
    if (!cleanUrl) return;
    if (!/^https?:\/\//i.test(cleanUrl)) cleanUrl = 'https://' + cleanUrl;
    setError(null);
    setResult(null);
    setPhase(0);

    // animate steps while we call Claude
    let stepIdx = 0;
    const stepTimer = setInterval(() => {
      stepIdx++;
      if (stepIdx >= AUDIT_STEPS.length) {
        clearInterval(stepTimer);
      } else {
        setPhase(stepIdx);
      }
    }, 900);

    try {
      const prompt = `You are a senior conversion-architecture consultant at WebBrandify (Rohit Sharma's studio). A visitor has requested a free site audit for: ${cleanUrl}

Without actually visiting the URL, infer a plausible audit based on the domain name and common patterns for that industry. Return STRICTLY valid JSON in this exact shape (no markdown, no commentary). The "fixes" array MUST contain EXACTLY 3 items — no more, no less:

{
  "verdict": "one sentence, <20 words, blunt but professional",
  "fixes": [
    {"severity":"high|med|low","title":"<6 words>","detail":"<35 words explaining the issue and the fix>"},
    {"severity":"high|med|low","title":"<6 words>","detail":"<35 words>"},
    {"severity":"high|med|low","title":"<6 words>","detail":"<35 words>"}
  ]
}

Make the fixes specific (mention metrics like LCP/CLS/TTFB, or concrete UX changes — not generic advice). Use British/Indian English. No emoji.`;

      const raw = await window.claude.complete(prompt);
      // strip code fences if any
      const jsonMatch = raw.match(/\{[\s\S]*\}/);
      if (!jsonMatch) throw new Error('Could not parse audit');
      const parsed = JSON.parse(jsonMatch[0]);

      // Wait for step animation to roughly finish before showing
      const minWait = 3600;
      const elapsed = (Date.now() - performance.now()) % minWait;
      setTimeout(() => {
        clearInterval(stepTimer);
        setPhase(4);
        setResult(parsed);
      }, Math.max(0, 3200 - elapsed));
    } catch (e) {
      clearInterval(stepTimer);
      setPhase(-1);
      setError("Couldn't reach the audit model. Try again in a moment.");
    }
  };

  return (
    <section className="section shell" data-screen-label="AI Audit">
      <div>
        <div className="kicker">§01.5 · Live · AI-powered</div>
        <h2 style={{
          fontFamily:'var(--serif)', fontWeight:400,
          fontSize:'clamp(40px, 5vw, 76px)', lineHeight:1.0,
          letterSpacing:'-0.02em', margin:'18px 0 0', maxWidth:'18ch',
          textWrap:'balance',
        }}>
          Drop a URL.<br/>
          <span style={{fontStyle:'italic', color:'var(--accent)'}}>See the leak.</span>
        </h2>
        <p style={{
          marginTop:24, color:'var(--muted)', fontSize:17, lineHeight:1.55, maxWidth:'52ch',
        }}>
          Our Claude-trained audit pass surfaces the three biggest conversion leaks on
          any production site in under sixty seconds. No login, no card. Just receipts.
        </p>
      </div>

      <div className="audit-wrap">
        <div className="audit-head">
          <span className="l">studio.webbrandify.com / audit</span>
          <span className="pulse">model · sonnet-4.5</span>
        </div>

        <div className="audit-body">
          <div className="audit-form">
            <input
              type="text"
              value={url}
              onChange={e => setUrl(e.target.value)}
              placeholder="yourcompany.com"
              onKeyDown={e => e.key === 'Enter' && phase < 0 && run()}
              spellCheck={false}
            />
            <button
              className="magnetic-trigger"
              onClick={run}
              disabled={!url.trim() || (phase >= 0 && phase < 4)}
            >
              {phase >= 0 && phase < 4 ? 'Scanning…' : 'Run audit'} <span>→</span>
            </button>
          </div>

          {phase >= 0 && phase < 4 && (
            <div className="audit-status">
              {AUDIT_STEPS.map((s, i) => (
                <div key={i} className={`step ${i < phase ? 'done' : ''} ${i === phase ? 'active' : ''}`}>
                  <span className="dot"/>
                  <span>{i < phase ? '✓ ' : ''}{s}{i === phase ? '…' : ''}</span>
                </div>
              ))}
            </div>
          )}

          {error && (
            <div className="audit-empty" style={{color:'#FFB4B4'}}>{error}</div>
          )}

          {result && phase === 4 && (
            <>
              <div style={{
                marginTop:28, padding:'18px 22px',
                border:'1px solid var(--accent-dim)', borderRadius:14,
                background:'rgba(0,242,254,0.04)',
                fontFamily:'var(--serif)', fontSize:22, lineHeight:1.3,
                letterSpacing:'-0.01em',
              }}>
                <span style={{
                  fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.16em',
                  textTransform:'uppercase', color:'var(--accent)', display:'block',
                  marginBottom:8,
                }}>Verdict</span>
                {result.verdict}
              </div>

              <div className="audit-result">
                {result.fixes.slice(0, 3).map((fix, i) => (
                  <div key={i} className="audit-card">
                    <div className="audit-i">Fix {String(i+1).padStart(2,'0')}</div>
                    <span className={`sev ${fix.severity}`}>{fix.severity}</span>
                    <h4>{fix.title}</h4>
                    <p>{fix.detail}</p>
                  </div>
                ))}
              </div>

              <div style={{
                marginTop:28, padding:'20px 24px',
                border:'1px solid var(--line)', borderRadius:14,
                display:'flex', justifyContent:'space-between', alignItems:'center',
                background:'#00000050',
              }}>
                <div>
                  <div style={{
                    fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.16em',
                    textTransform:'uppercase', color:'var(--muted)',
                  }}>Want the full 23-point audit?</div>
                  <div style={{
                    fontFamily:'var(--serif)', fontSize:22, marginTop:4,
                  }}>14 minutes. With me. On the calendar below.</div>
                </div>
                <a href="#booking" className="magnetic-trigger" style={{
                  background:'var(--accent)', color:'var(--bg)',
                  padding:'14px 22px', borderRadius:999,
                  fontFamily:'var(--sans)', fontSize:14, fontWeight:500,
                  letterSpacing:'-0.01em',
                  display:'inline-flex', alignItems:'center', gap:10,
                }}>
                  Book now <span>→</span>
                </a>
              </div>
            </>
          )}

          {phase === -1 && !error && (
            <div className="audit-empty">
              Paste any URL above. Audit runs against a Claude-tuned heuristic — no scraping, no logins.
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

window.AISiteAudit = AISiteAudit;
