// ========= HOME SECTIONS (EN) — Austin + Chicago hosts =========

const { useState, useEffect, useRef } = React;

// Letter grade from score (0-100). Six-case system: A/B/C/D/F + fallback.
const toGrade = (s) => {
  if (s >= 90) return { g: 'A', tag: 'good', label: 'Excellent' };
  if (s >= 70) return { g: 'B', tag: 'good', label: 'Good' };
  if (s >= 50) return { g: 'C', tag: 'warn', label: 'Average' };
  if (s >= 30) return { g: 'D', tag: 'bad',  label: 'Poor' };
  return { g: 'F', tag: 'bad', label: 'Critical' };
};

// Meta Pixel helper — safe no-op if fbq hasn't loaded yet.
// Returns the event_id used so the caller can forward it to the backend
// (browser + server CAPI dedup via the same id).
const newEventId = () => {
  try {
    if (window.crypto && typeof window.crypto.randomUUID === 'function') {
      return window.crypto.randomUUID().replace(/-/g, '');
    }
  } catch (_) {}
  return 'eid_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
};
const fire = (event, props, eventId) => {
  const eid = eventId || newEventId();
  const payload = Object.assign({ content_category: 'en-us' }, props || {});
  try {
    if (typeof window.fbq === 'function') {
      window.fbq('track', event, payload, { eventID: eid });
    }
  } catch (_) { /* noop */ }
  return eid;
};

// Audit demo wired to the EN backend (/api/en/analyze).
const AUDIT_URL_RE = /airbnb\.[a-z.]{2,8}\/(?:rooms|h)\/\d+/i;
const normalizeAirbnbUrl = (raw) => {
  let u = (raw || '').trim();
  if (!u) return u;
  if (!/^https?:\/\//i.test(u)) u = 'https://' + u;
  try { const p = new URL(u); p.search = ''; p.hash = ''; return p.toString(); } catch(e) { return u; }
};
const roomIdFromUrl = (u) => { const m = String(u||'').match(/\/rooms\/(\d+)/); return m ? m[1] : ''; };

const AuditDemo = () => {
  const [url, setUrl] = useState("");
  const [phase, setPhase] = useState("idle");
  const [progress, setProgress] = useState(0);
  const [score, setScore] = useState(0);
  const [errMsg, setErrMsg] = useState("");
  const [result, setResult] = useState(null);
  const [emailSubmitted, setEmailSubmitted] = useState(false);
  const runningRef = useRef(false);

  const steps = [
    "Fetching your listing",
    "Reading photos and title",
    "Scoring 9 categories",
    "Identifying top problems",
    "Building your report",
  ];
  const [stepIdx, setStepIdx] = useState(0);

  const runAudit = async (e) => {
    e?.preventDefault?.();
    if (phase === "scanning") return;
    const u = normalizeAirbnbUrl(url);
    if (!AUDIT_URL_RE.test(u)) {
      setErrMsg("Enter a valid Airbnb URL (airbnb.com/rooms/...)");
      return;
    }
    setErrMsg("");
    setUrl(u);
    setPhase("scanning"); setProgress(0); setScore(0); setStepIdx(0); setResult(null);
    const startEid = fire('StartAudit', { content_name: 'en-home-scan', listing_url: u });

    runningRef.current = true;
    const start = performance.now();
    const tick = (now) => {
      if (!runningRef.current) return;
      const t = Math.min(0.92, (now - start) / 28000);
      const eased = 1 - Math.pow(1 - t, 2);
      setProgress(eased * 100);
      setStepIdx(Math.min(steps.length - 1, Math.floor(eased * steps.length)));
      requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);

    try {
      const r = await fetch('/api/en/analyze', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(Object.assign({ url: u, event_id: startEid }, (typeof window.getUtmData === 'function' ? window.getUtmData() : {})))
      });
      const data = await r.json().catch(() => ({}));
      runningRef.current = false;
      if (!r.ok) throw new Error(data.error || ('Error ' + r.status));
      window._lastAnalyze = data;
      setResult(data);
      setScore(Number(data.score) || 0);
      setProgress(100);
      setPhase("done");
      fire('AuditComplete',
        { value: Number(data.score) || 0, content_name: data.title || 'en-home-complete' },
        data.event_id_complete);
    } catch (err) {
      runningRef.current = false;
      setErrMsg(err.message || 'Error analyzing your listing');
      setPhase("idle");
    }
  };

  const reset = () => { runningRef.current = false; setPhase("idle"); setProgress(0); setScore(0); setUrl(""); setResult(null); setErrMsg(""); setEmailSubmitted(false); };
  const grade = toGrade(score);

  return (
    <div className="audit-demo card" id="audit">
      <div className="demo-chrome">
        <div className="demo-dots"><span></span><span></span><span></span></div>
        <div className="demo-urlbar mono">auditbnb.com / audit</div>
        <div className="demo-chrome-right mono">LIVE</div>
      </div>

      <div className="demo-body">
        {phase === "idle" && (
          <form className="demo-form" onSubmit={runAudit}>
            <label className="eyebrow" style={{marginBottom: 14}}>Free audit</label>
            <h3 className="serif" style={{fontSize: 30, margin: '0 0 8px', letterSpacing: '-0.02em'}}>
              Paste your Airbnb link
            </h3>
            <p className="muted" style={{margin: '0 0 24px', fontSize: 15}}>
              In about 90 seconds get your grade, weak spots, and
              why you are not booking at full speed.
            </p>
            <div className="demo-input-row">
              <div className="demo-input-wrap">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" style={{color:'var(--muted)'}}>
                  <path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71"/>
                  <path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71"/>
                </svg>
                <input type="text" placeholder="Paste your Airbnb listing URL (airbnb.com/rooms/...)" value={url} onChange={(e) => { setUrl(e.target.value); if (errMsg) setErrMsg(''); }} />
              </div>
              <button type="submit" className="btn btn-primary btn-lg">
                Audit my listing
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
              </button>
            </div>
            {errMsg && (
              <div style={{marginTop: 10, fontSize: 13, color: 'var(--bad, #C84A3C)'}}>{errMsg}</div>
            )}
            <div className="demo-chips">
              <span className="chip" style={{background:'transparent', border:0, color:'var(--muted)'}}>
                Built for Austin and Chicago hosts · Market benchmark in premium
              </span>
            </div>
          </form>
        )}

        {phase === "scanning" && (
          <div className="demo-scanning">
            <div className="scan-top">
              <span className="eyebrow">Auditing</span>
              <span className="mono muted" style={{fontSize: 12}}>{Math.round(progress)}%</span>
            </div>
            <div className="scan-property">
              <div className="scan-thumb" aria-hidden><div className="scan-sweep"></div></div>
              <div>
                <div style={{fontWeight:600, fontSize: 15}}>Analyzing listing #{roomIdFromUrl(url) || '—'}</div>
                <div className="muted" style={{fontSize: 13}}>{url.replace(/^https?:\/\//, '').slice(0, 48)}</div>
              </div>
            </div>
            <ul className="scan-steps">
              {steps.map((s, i) => (
                <li key={i} className={i < stepIdx ? 'done' : i === stepIdx ? 'active' : ''}>
                  <span className="scan-bullet">
                    {i < stepIdx ? (<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M20 6L9 17l-5-5"/></svg>)
                     : i === stepIdx ? (<span className="scan-spinner"></span>) : null}
                  </span>
                  {s}
                </li>
              ))}
            </ul>
            <div className="muted" style={{marginTop: 14, fontSize: 12, textAlign:'center'}}>
              This takes about 90 seconds — worth it.
            </div>
            <div className="score-bar" style={{marginTop: 16}}>
              <div className="score-bar-fill" style={{width: `${progress}%`}}></div>
            </div>
          </div>
        )}

        {phase === "done" && (() => {
          const r = result || {};
          const cats = Array.isArray(r.categories) ? r.categories : [];
          const gradeToVal = { A: 92, B: 78, C: 62, D: 40, F: 20, 'N/E': 50 };
          const visibleKeys = ['fotos', 'titulo', 'descripcion', 'resenas', 'photos', 'title', 'description', 'reviews'];
          const labelMap = {
            fotos: 'Photos', photos: 'Photos',
            titulo: 'Title', title: 'Title',
            descripcion: 'Description', description: 'Description',
            resenas: 'Reviews', reviews: 'Reviews',
          };
          // Pick up to 4 visible categories; backend may return either Spanish or English keys.
          const seen = new Set();
          const metrics = [];
          for (const c of cats) {
            const key = String(c.key || c.id || '').toLowerCase();
            if (!visibleKeys.includes(key)) continue;
            const label = labelMap[key];
            if (!label || seen.has(label)) continue;
            seen.add(label);
            const g = (c.grade || '').toUpperCase();
            const val = gradeToVal[g] != null ? gradeToVal[g] : (c.score_0_10 ? Math.round(c.score_0_10 * 10) : 55);
            metrics.push({ label, val });
            if (metrics.length >= 4) break;
          }
          const topIssues = Array.isArray(r.top_problems) && r.top_problems.length
            ? r.top_problems.slice(0, 3)
            : (Array.isArray(r.issues) ? r.issues.slice(0, 3) : []);
          return (
            <div className="demo-done">
              <div className="demo-done-head">
                <div>
                  <span className="eyebrow">AuditBnB grade</span>
                  <div style={{display:'flex', alignItems:'baseline', gap: 16, marginTop: 6}}>
                    <div className={`grade-badge grade-${grade.tag}`}>{grade.g}</div>
                    <div>
                      <div className="score-num" style={{fontSize: 42}}>{(score / 10).toFixed(1)}<sup>/10</sup></div>
                      <div className={`chip chip-${grade.tag}`} style={{marginTop: 4}}>{grade.label}</div>
                    </div>
                  </div>
                </div>
                <div style={{textAlign:'right', maxWidth: 220}}>
                  <div className="muted" style={{fontSize: 12, textTransform:'uppercase', letterSpacing: '0.08em'}}>Listing</div>
                  <div style={{fontSize: 14, marginTop: 4, fontWeight: 500, lineHeight: 1.3}}>{(r.title || '—').slice(0, 60)}</div>
                  {r.location && <div className="muted" style={{fontSize: 12, marginTop: 2}}>{r.location}</div>}
                </div>
              </div>
              <div className="score-bar" style={{marginTop: 16}}>
                <div className={`score-bar-fill is-${grade.tag}`} style={{width: `${score}%`}}></div>
              </div>
              <div className="demo-metrics">
                {metrics.map(m => {
                  const mg = toGrade(m.val);
                  return (
                    <div key={m.label} className="demo-metric">
                      <div className="flex items-center justify-between" style={{marginBottom: 6}}>
                        <span style={{fontSize: 13, color:'var(--ink-2)'}}>{m.label}</span>
                        <span className="mono" style={{fontSize: 13}}>{mg.g} · {m.val}</span>
                      </div>
                      <div className="tiny-bar">
                        <span className={`is-${mg.tag}`} style={{width: `${m.val}%`}}></span>
                      </div>
                    </div>
                  );
                })}
              </div>
              {topIssues.length > 0 && (
                <div className={`issues-container${!emailSubmitted ? ' blurred' : ''}`} style={{marginTop: 20, padding: '16px 18px', background:'rgba(0,0,0,0.03)', borderRadius: 10, position:'relative'}}>
                  <div className="eyebrow" style={{marginBottom: 10}}>Top 3 issues we found</div>
                  <ul style={{margin: 0, paddingLeft: 18, fontSize: 13, lineHeight: 1.6}}>
                    {topIssues.map((it, i) => (
                      <li key={i}>{typeof it === 'string' ? it : (it.title || it.issue || JSON.stringify(it))}</li>
                    ))}
                  </ul>
                  {!emailSubmitted && (
                    <div className="issues-lock-overlay">
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 018 0v4"/></svg>
                      <span>Enter your email below to unlock the {topIssues.length} issues</span>
                    </div>
                  )}
                </div>
              )}
              <EmailGate
                onAuditAnother={reset}
                listingUrl={url}
                score={score}
                resultData={r}
                onEmailSubmitted={() => setEmailSubmitted(true)}
              />
            </div>
          );
        })()}
      </div>
    </div>
  );
};

// Inline email gate. Two actions share the email input:
//   Primary  → /api/en/lead + redirect to /en/premium (pay)
//   Secondary → /api/en/lead + stay (receive free report)
const EMAIL_RE_V2 = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const EmailGate = ({ onAuditAnother, listingUrl, score, resultData, onEmailSubmitted }) => {
  const [mode, setMode] = useState("form");  // form | submitting | free_sent
  const [email, setEmail] = useState("");
  const [localErr, setLocalErr] = useState("");

  const buildLeadPayload = (em, eid) => Object.assign({
    email: em,
    url: listingUrl,
    score: score,
    title: resultData?.title || "",
    issues: Array.isArray(resultData?.issues) ? resultData.issues.slice(0, 5) : [],
    categories: Array.isArray(resultData?.categories) ? resultData.categories : [],
    global_grade: resultData?.global_grade || "",
    photo_report: (typeof window !== 'undefined' && window._lastAnalyze?.photo_report) || resultData?.photo_report || null,
    market_report: (typeof window !== 'undefined' && window._lastAnalyze?.market_report) || resultData?.market_report || null,
    event_id: eid,
    locale: 'en-us',
  }, (typeof window.getUtmData === 'function' ? window.getUtmData() : {}));

  const postLead = async (em) => {
    const leadEid = newEventId();
    try {
      await fetch("/api/en/lead", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(buildLeadPayload(em, leadEid)),
      });
      fire('Lead', { value: 0, currency: 'USD', content_name: 'en-home-lead' }, leadEid);
    } catch (_) { /* never block UX on logging side-effect */ }
    if (typeof onEmailSubmitted === 'function') onEmailSubmitted();
  };

  const validateEmail = () => {
    const em = (email || "").trim().toLowerCase();
    if (!EMAIL_RE_V2.test(em)) {
      setLocalErr("Enter a valid email");
      return null;
    }
    setLocalErr("");
    return em;
  };

  const handleFreeSubmit = async (e) => {
    e?.preventDefault?.();
    const em = validateEmail();
    if (!em) return;
    setMode("submitting");
    await postLead(em);
    setMode("free_sent");
  };

  const handlePremium = async () => {
    const em = validateEmail();
    if (!em) return;
    setMode("submitting");
    await postLead(em);
    // InitiateCheckout fires from the premium page once /api/en/create-checkout
    // is actually called. Here we just pass along an event_id so browser+CAPI
    // dedup against the same id.
    const checkoutEid = newEventId();
    const qs = new URLSearchParams({
      url: listingUrl,
      score: String(score),
      email: em,
      event_id: checkoutEid,
    }).toString();
    window.location.href = `/en/premium?${qs}`;
  };

  if (mode === "free_sent") {
    return (
      <div className="demo-email-gate">
        <div className="eyebrow" style={{marginBottom: 8}}>Sent</div>
        <div style={{fontSize: 15, color: 'var(--ink)', marginBottom: 14}}>
          Check your inbox at <b>{email}</b>. Your free report arrives in the next few minutes.
        </div>
        <div className="muted" style={{fontSize: 13, marginBottom: 18}}>
          Want the full audit with all 9 categories, rewritten titles and a 90-day roadmap?
        </div>
        <div className="demo-done-cta" style={{borderTop: 0, paddingTop: 0, marginTop: 0}}>
          <button type="button" className="btn btn-primary" onClick={handlePremium}>
            Get my full audit — $20 USD
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </button>
          <button className="btn btn-ghost" onClick={onAuditAnother}>Audit another</button>
        </div>
      </div>
    );
  }

  return (
    <form className="demo-email-gate" onSubmit={handleFreeSubmit}>
      <div className="eyebrow" style={{marginBottom: 8}}>Enter your email to unlock the full report</div>
      <div style={{fontSize: 15, marginBottom: 14, color: 'var(--ink-2)'}}>
        We will email you a copy — no spam, no signup.
      </div>
      <div className="demo-input-row" style={{marginBottom: 10}}>
        <div className="demo-input-wrap">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" style={{color:'var(--muted)'}}>
            <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
            <polyline points="22,6 12,13 2,6"/>
          </svg>
          <input
            type="email"
            placeholder="you@email.com"
            value={email}
            onChange={(e) => { setEmail(e.target.value); if (localErr) setLocalErr(""); }}
            disabled={mode === "submitting"}
          />
        </div>
      </div>
      {localErr && (
        <div style={{fontSize: 13, color: 'var(--bad, #C84A3C)', marginBottom: 10}}>{localErr}</div>
      )}
      <div style={{display:'flex', gap: 8, flexWrap: 'wrap'}}>
        <button
          type="button"
          className="btn btn-primary"
          onClick={handlePremium}
          disabled={mode === "submitting"}
          style={{flex:'1 1 auto'}}
        >
          {mode === "submitting" ? "Processing…" : "Get my full audit — $20 USD"}
          {mode !== "submitting" && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>}
        </button>
        <button
          type="submit"
          className="btn btn-outline"
          disabled={mode === "submitting"}
        >
          {mode === "submitting" ? "…" : "Send me my audit"}
        </button>
      </div>
      <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginTop: 12, gap: 12, flexWrap:'wrap'}}>
        <div className="muted" style={{fontSize: 12}}>
          We use your email to deliver the report. Unsubscribe anytime.
        </div>
        <button
          type="button"
          className="btn btn-ghost"
          onClick={onAuditAnother}
          style={{padding: '0 8px', height: 'auto', fontSize: 13}}
        >
          Audit another →
        </button>
      </div>
    </form>
  );
};

const Hero = () => (
  <section className="hero">
    <div className="wrap">
      <div className="hero-grid">
        <div>
          <div className="eyebrow" style={{marginBottom: 28}}>Instant audit · 90 seconds · No signup</div>
          <h1 className="display">
            Audit your US Airbnb<br/>listing <em>in 90<br/>seconds</em>.
          </h1>
          <p className="lede" style={{marginTop: 24}}>
            AI grades 9 categories — photos, title, pricing, reviews, amenities —
            and tells you exactly what to fix. Free, no signup.
          </p>
          <div className="hero-proof">
            <div className="hero-proof-avatars">
              <span style={{background:'#D9C6B0'}}>AT</span>
              <span style={{background:'#C3D1B2'}}>CH</span>
              <span style={{background:'#E4B9B9'}}>JM</span>
              <span style={{background:'#B9C7E4'}}>+</span>
            </div>
            <div>
              <div style={{fontSize: 14, fontWeight: 500}}>Built for Austin and Chicago hosts</div>
              <div className="muted" style={{fontSize: 13}}>Market benchmark included in premium</div>
            </div>
          </div>
          <div style={{marginTop: 28, display:'flex', alignItems:'center', gap: 14}}>
            <div aria-hidden="true" style={{width: 56, height: 56, borderRadius:'50%',
              background: 'conic-gradient(#E25A4A 0 72%, rgba(226,90,74,0.18) 72% 100%)',
              display:'flex', alignItems:'center', justifyContent:'center',
              fontFamily:'var(--font-serif)', fontSize: 18, fontWeight: 600, color:'#1a1a1a',
              position:'relative'}}>
              <span style={{background:'#FAF8F3', borderRadius:'50%', width: 40, height: 40,
                display:'flex', alignItems:'center', justifyContent:'center'}}>72</span>
            </div>
            <div>
              <div style={{fontSize: 13, fontWeight: 600, letterSpacing:'0.04em',
                textTransform:'uppercase', color:'rgba(250,248,243,0.7)'}}>Sample score</div>
              <div className="muted" style={{fontSize: 13, marginTop: 2}}>
                72/100 · grade B · "Good, with 3 clear wins"
              </div>
            </div>
          </div>
        </div>
        <AuditDemo />
      </div>
    </div>
  </section>
);

const LogoBand = () => {
  const logos = [
    <span key="a1" className="serif" style={{fontSize: 22}}>The Hosting Post</span>,
    <span key="a2" style={{fontWeight: 700, letterSpacing: '-0.02em', fontSize: 18}}>HOSTIFY</span>,
    <span key="a3" className="mono" style={{fontSize: 14, letterSpacing: '0.15em'}}>RENTAL · WEEKLY</span>,
    <span key="a4" className="serif" style={{fontSize: 22, fontStyle: 'italic'}}>Nomad</span>,
    <span key="a5" style={{fontWeight: 600, fontSize: 16}}>HostScale</span>,
    <span key="a6" className="serif" style={{fontSize: 22}}>Round House</span>,
    <span key="a7" style={{fontWeight: 700, letterSpacing: '0.04em', fontSize: 15}}>AIRHOST US</span>,
    <span key="a8" className="mono" style={{fontSize: 14, letterSpacing: '0.12em'}}>BOOKING · DAILY</span>,
  ];
  return (
    <section className="logoband">
      <div className="wrap">
        <div className="logoband-head">
          <span className="muted" style={{fontSize: 13}}>Hosts who use AuditBnB</span>
        </div>
      </div>
      <div className="logoband-track" aria-hidden="true">
        <div className="logoband-marquee">
          {logos.map((l, i) => <div key={`r1-${i}`} className="logoband-item">{l}</div>)}
          {logos.map((l, i) => <div key={`r2-${i}`} className="logoband-item">{l}</div>)}
        </div>
      </div>
    </section>
  );
};

// How it works — 3 steps
const HowItWorks = () => {
  const steps = [
    { n: '01', title: 'Paste your Airbnb link', body: 'No credentials, no account access. Only the public listing URL.' },
    { n: '02', title: 'Our AI analyzes it', body: 'We grade 9 categories: photos, title, description, pricing, occupancy, reviews, amenities, rules and competition.' },
    { n: '03', title: 'Get your action plan', body: 'Grade A–F, weak spots identified, and specific fixes ranked by impact.' },
  ];
  return (
    <section className="section" id="how-it-works">
      <div className="wrap">
        <div className="section-head">
          <span className="eyebrow">How it works</span>
          <h2 className="h2" style={{margin: '16px 0 0', maxWidth: 720}}>
            From a URL to an action plan<br/>in <em style={{fontStyle:'italic', color:'var(--accent)'}}>90 seconds</em>.
          </h2>
        </div>
        <div className="how-grid">
          {steps.map(s => (
            <div key={s.n} className="how-card">
              <div className="mono muted" style={{fontSize: 13}}>{s.n}</div>
              <h3 className="serif" style={{fontSize: 28, margin: '36px 0 12px', letterSpacing:'-0.02em'}}>{s.title}</h3>
              <p className="muted" style={{margin: 0, lineHeight: 1.55}}>{s.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};


const LISTING_CATS = [
  { num: 1, cat: 'Photos',       weight: 20, anchor: 'photos',      insight: '"Your cover is dark — the living-room shot converts 2x better."' },
  { num: 2, cat: 'Title',        weight: 15, anchor: 'title',       insight: '"Add «walk to 6th St» — 68% of Austin searches include a walkability cue."' },
  { num: 3, cat: 'Reviews',      weight: 10, anchor: 'reviews',     insight: '"You answer in 4h on average — better than 82% of the area."' },
  { num: 4, cat: 'Pricing',      weight: 12, anchor: 'price',       insight: '"Weekends are $38 below the neighborhood median."' },
  { num: 5, cat: 'Description',  weight: 12, anchor: 'description', insight: '"Lead with benefits, not rules. Cut 30%."' },
  { num: 6, cat: 'Amenities',    weight: 8,  anchor: 'amenities',   insight: '"Missing 3 high-impact items: coffee maker, smart thermostat, dryer."' },
  { num: 7, cat: 'Occupancy',    weight: 10, anchor: 'occupancy',   insight: '"Your calendar has 12 one-night gaps — block them or drop the minimum."' },
  { num: 8, cat: 'Rules',        weight: 7,  anchor: 'rules',       insight: '"3-night minimum costs you 23% of searches."' },
];

const CompetitionPanel = ({ active }) => (
  <aside className={`competition-panel ${active ? 'active' : ''}`} aria-label="Listing competition">
    <span className="eyebrow">vs competition in South Congress</span>
    <div className="competition-panel-label">Top listing in the area:</div>
    <div className="competition-panel-card">
      <div className="competition-panel-card-title">Modern Loft · South Congress · Balcony</div>
      <div className="competition-panel-card-meta">$182 USD · 4.82★ · 98 reviews</div>
    </div>
    <div className="competition-panel-insights">
      <span>You charge <strong>15% less</strong> than the median.</span>
      <span>Top 3 in the area charge <strong>18% more</strong>.</span>
    </div>
  </aside>
);

const AnnotationCard = ({ data, anchorRect, containerRect }) => {
  if (!data || !anchorRect || !containerRect) return null;
  const gap = 12;
  const cardWidth = 260;
  const anchorCenterY = anchorRect.top - containerRect.top + anchorRect.height / 2;
  const rightEdge = anchorRect.right - containerRect.left + gap;
  const leftEdge = anchorRect.left - containerRect.left - gap - cardWidth;
  const placeRight = (rightEdge + cardWidth) <= containerRect.width;
  const left = placeRight ? rightEdge : Math.max(0, leftEdge);
  const top = Math.max(0, anchorCenterY - 40);
  return (
    <div
      className="annotation-card visible"
      style={{ left, top, width: cardWidth }}
      role="status"
      aria-live="polite"
    >
      <div className="annotation-card-eyebrow">{String(data.num).padStart(2, '0')} · {data.weight}%</div>
      <div className="annotation-card-title">{data.cat}</div>
      <div className="annotation-card-insight">{data.insight}</div>
    </div>
  );
};

const MobileAnnotationStack = ({ activeIdx }) => {
  const refs = React.useRef({});
  React.useEffect(() => {
    if (activeIdx < 0) return;
    const el = refs.current[activeIdx];
    if (el && typeof el.scrollIntoView === 'function') {
      el.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  }, [activeIdx]);

  return (
    <ol className="mobile-annotation-stack" aria-label="List of the 9 categories we analyze">
      {LISTING_CATS.map((c, i) => (
        <li
          key={c.num}
          ref={(el) => { if (el) refs.current[i] = el; }}
          style={{
            listStyle: 'none',
            padding: '14px 16px',
            background: '#FAF8F3',
            borderRadius: 10,
            borderLeft: '3px solid ' + (i === activeIdx ? '#E25A4A' : 'rgba(26,26,26,0.08)'),
            transition: 'border-color 160ms ease',
          }}
        >
          <div style={{fontSize: 10, letterSpacing: '0.18em', textTransform:'uppercase', color:'#E25A4A', fontWeight: 600}}>
            {String(c.num).padStart(2,'0')} · {c.weight}%
          </div>
          <div style={{fontFamily: 'var(--font-serif, Georgia, serif)', fontSize: 16, marginTop: 4, color:'#1a1a1a'}}>
            {c.cat}
          </div>
          <div style={{marginTop: 6, fontSize: 12, lineHeight: 1.5, fontStyle: 'italic', color:'rgba(26,26,26,0.7)'}}>
            {c.insight}
          </div>
        </li>
      ))}
      <li
        ref={(el) => { if (el) refs.current[8] = el; }}
        style={{
          listStyle: 'none',
          padding: '14px 16px',
          background: '#FAF8F3',
          borderRadius: 10,
          borderLeft: '3px solid #E25A4A',
          transition: 'border-color 160ms ease',
        }}
      >
        <div style={{fontSize: 10, letterSpacing:'0.18em', textTransform:'uppercase', color:'#E25A4A', fontWeight:600}}>
          09 · 6% · Competition
        </div>
        <div style={{fontFamily:'var(--font-serif, Georgia, serif)', fontSize: 16, marginTop: 4, color:'#1a1a1a'}}>
          vs one comparable in your area
        </div>
        <div style={{marginTop: 6, fontSize: 12, lineHeight: 1.5, color: 'rgba(26,26,26,0.75)'}}>
          Top 3 in South Congress charge 18% more. You charge 15% below the median.
        </div>
      </li>
    </ol>
  );
};

const ListingMockup = () => {
  const [activeIdx, setActiveIdx] = React.useState(-1);
  const [autoPlayDone, setAutoPlayDone] = React.useState(false);
  const sectionRef = React.useRef(null);
  const containerRef = React.useRef(null);
  const anchorRefs = React.useRef({});
  const [rects, setRects] = React.useState({ anchor: null, container: null });

  React.useLayoutEffect(() => {
    if (activeIdx < 0 || activeIdx > 7) {
      setRects({ anchor: null, container: null });
      return;
    }
    const anchorEl = anchorRefs.current[activeIdx];
    const containerEl = containerRef.current;
    if (!anchorEl || !containerEl) return;
    setRects({
      anchor: anchorEl.getBoundingClientRect(),
      container: containerEl.getBoundingClientRect(),
    });
  }, [activeIdx]);

  const prefersReducedMotion = React.useMemo(() => {
    if (typeof window === 'undefined' || !window.matchMedia) return false;
    return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  }, []);

  const runAutoPlay = React.useCallback(() => {
    LISTING_CATS.forEach((_, i) => {
      setTimeout(() => setActiveIdx(i), i * 2000);
    });
    setTimeout(() => setActiveIdx(8), LISTING_CATS.length * 2000);
    setTimeout(() => {
      setActiveIdx(-1);
      setAutoPlayDone(true);
    }, (LISTING_CATS.length + 1) * 2000);
  }, []);

  React.useEffect(() => {
    if (prefersReducedMotion || autoPlayDone) return;
    if (!window.IntersectionObserver) {
      runAutoPlay();
      return;
    }
    const obs = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && entries[0].intersectionRatio >= 0.5) {
        obs.disconnect();
        runAutoPlay();
      }
    }, { threshold: 0.5 });
    if (sectionRef.current) obs.observe(sectionRef.current);
    return () => obs.disconnect();
  }, [autoPlayDone, prefersReducedMotion, runAutoPlay]);

  const setAnchor = (idx) => {
    if (!autoPlayDone) return;
    setActiveIdx(idx);
  };
  const clearAnchor = () => {
    if (!autoPlayDone) return;
    setActiveIdx(-1);
  };

  return (
    <section ref={sectionRef} className="section" aria-label="What we analyze in your listing">
      <div className="wrap">
        <div style={{textAlign:'center', maxWidth: 680, margin: '0 auto 48px'}}>
          <span className="eyebrow" style={{justifyContent:'center'}}>What we analyze</span>
          <h2 className="h2" style={{margin: '16px auto 0'}}>
            The <em>9 signals</em> that move your score.
          </h2>
          <p className="lede" style={{marginTop: 14, fontSize: 16}}>
            We run your listing through the same checklist top hosts already master.
          </p>
        </div>
        <div className="mockup-wrap">
          <div className={`mockup-card ${autoPlayDone ? 'autoplay-done' : ''}`} ref={containerRef}>
            {/* Photo grid */}
            <div
              className={`mockup-photos mockup-anchor ${activeIdx === 0 ? 'active' : ''}`}
              tabIndex={0}
              role="button"
              onMouseEnter={() => setAnchor(0)}
              onMouseLeave={clearAnchor}
              onFocus={() => setAnchor(0)}
              onBlur={clearAnchor}
              aria-label="Listing photos (category 1, 20% of score)"
              data-label="Photos"
              ref={(el) => { if (el) anchorRefs.current[0] = el; }}
            >
              <div className="mockup-photo-slot hero">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="12" cy="12" r="3"/><path d="M7 5l2-2h6l2 2"/></svg>
              </div>
              {['kitchen', 'bedroom', 'bath', 'balcony'].map((slot) => (
                <div key={slot} className="mockup-photo-slot">
                  <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2">
                    {slot === 'kitchen' && <path d="M4 4h16v6H4zM4 14h16v6H4zM8 4v6M16 14v6"/>}
                    {slot === 'bedroom' && <path d="M3 18v-6h18v6M6 12V8h12v4M3 18h18"/>}
                    {slot === 'bath' && <path d="M4 10h16M6 10v-4a3 3 0 013-3h0a3 3 0 013 3M6 14v3a3 3 0 003 3M18 14v3a3 3 0 01-3 3"/>}
                    {slot === 'balcony' && <path d="M3 20h18M5 20v-8h14v8M5 12V6h14v6M9 12v8M15 12v8"/>}
                  </svg>
                </div>
              ))}
            </div>

            <div className="mockup-header">
              <h3
                className={`mockup-title mockup-anchor ${activeIdx === 1 ? 'active' : ''}`}
                tabIndex={0}
                role="button"
                onMouseEnter={() => setAnchor(1)}
                onMouseLeave={clearAnchor}
                onFocus={() => setAnchor(1)}
                onBlur={clearAnchor}
                aria-label="Listing title (category 2, 15% of score)"
                data-label="Title"
                ref={(el) => { if (el) anchorRefs.current[1] = el; }}
              >
                Modern Loft · 1 block from South Congress
              </h3>
              <div className="mockup-actions" aria-hidden="true">
                <span>↑ Share</span>
                <span>♡ Save</span>
              </div>
            </div>

            <div className="mockup-detail-row">
              <span
                className={`mockup-rating mockup-anchor ${activeIdx === 2 ? 'active' : ''}`}
                tabIndex={0}
                role="button"
                onMouseEnter={() => setAnchor(2)}
                onMouseLeave={clearAnchor}
                onFocus={() => setAnchor(2)}
                onBlur={clearAnchor}
                aria-label="Listing reviews (category 3, 10% of score)"
                data-label="Reviews"
                ref={(el) => { if (el) anchorRefs.current[2] = el; }}
              >
                <span className="stars">★ 4.87</span>
                <span>· 124 reviews · Superhost</span>
              </span>
              <span>· South Congress, Austin</span>
            </div>

            <div className="mockup-body">
              <div>
                <p
                  className={`mockup-description mockup-anchor ${activeIdx === 4 ? 'active' : ''}`}
                  tabIndex={0}
                  role="button"
                  onMouseEnter={() => setAnchor(4)}
                  onMouseLeave={clearAnchor}
                  onFocus={() => setAnchor(4)}
                  onBlur={clearAnchor}
                  aria-label="Listing description (category 5, 12% of score)"
                  data-label="Description"
                  ref={(el) => { if (el) anchorRefs.current[4] = el; }}
                >
                  Wake up in South Congress with the morning light on the balcony. A 485 sq ft loft designed for two, hardwood floors, fully equipped kitchen, and a balcony overlooking the live-oak street.
                </p>

                <div
                  className={`mockup-amenities mockup-anchor ${activeIdx === 5 ? 'active' : ''}`}
                  tabIndex={0}
                  role="button"
                  onMouseEnter={() => setAnchor(5)}
                  onMouseLeave={clearAnchor}
                  onFocus={() => setAnchor(5)}
                  onBlur={clearAnchor}
                  aria-label="Listing amenities (category 6, 8% of score)"
                  data-label="Amenities"
                  ref={(el) => { if (el) anchorRefs.current[5] = el; }}
                >
                  {['Wi-Fi 300 Mbps', 'Full kitchen', 'Workspace', 'Smart TV', 'Balcony', 'Washer/Dryer'].map((a) => (
                    <span key={a} className="mockup-amenity-pill">{a}</span>
                  ))}
                </div>

                <div
                  className={`mockup-rules mockup-anchor ${activeIdx === 7 ? 'active' : ''}`}
                  tabIndex={0}
                  role="button"
                  onMouseEnter={() => setAnchor(7)}
                  onMouseLeave={clearAnchor}
                  onFocus={() => setAnchor(7)}
                  onBlur={clearAnchor}
                  aria-label="Listing rules (category 8, 7% of score)"
                  data-label="Rules"
                  ref={(el) => { if (el) anchorRefs.current[7] = el; }}
                >
                  What to know · Flexible check-in · 2-night minimum · No pets · No parties
                </div>
              </div>

              <div
                className={`mockup-price-card mockup-anchor ${activeIdx === 3 ? 'active' : ''}`}
                tabIndex={0}
                role="button"
                onMouseEnter={() => setAnchor(3)}
                onMouseLeave={clearAnchor}
                onFocus={() => setAnchor(3)}
                onBlur={clearAnchor}
                aria-label="Listing price (category 4, 12% of score)"
                data-label="Pricing"
                ref={(el) => { if (el) anchorRefs.current[3] = el; }}
              >
                <div className="mockup-price-amount">$152</div>
                <div className="mockup-price-label">USD · per night</div>
                <div
                  className={`mockup-occupancy-note mockup-anchor ${activeIdx === 6 ? 'active' : ''}`}
                  tabIndex={0}
                  role="button"
                  onMouseEnter={(e) => { e.stopPropagation(); setAnchor(6); }}
                  onMouseLeave={clearAnchor}
                  onFocus={() => setAnchor(6)}
                  onBlur={clearAnchor}
                  aria-label="Listing occupancy (category 7, 10% of score)"
                  data-label="Occupancy"
                  ref={(el) => { if (el) anchorRefs.current[6] = el; }}
                >
                  Calendar · 2-night minimum
                </div>
              </div>
            </div>
            <AnnotationCard
              data={activeIdx >= 0 && activeIdx <= 7 ? LISTING_CATS[activeIdx] : null}
              anchorRect={rects.anchor}
              containerRect={rects.container}
            />
          </div>

          <CompetitionPanel active={activeIdx === 8} />
          <MobileAnnotationStack activeIdx={activeIdx} />
        </div>
      </div>
    </section>
  );
};

// Free vs Premium comparison
const FreeVsPremium = () => (
  <section className="section">
    <div className="wrap">
      <div className="section-head" style={{textAlign:'center', margin: '0 auto 56px'}}>
        <span className="eyebrow" style={{justifyContent:'center'}}>Free vs Premium</span>
        <h2 className="h2" style={{margin: '16px auto 0', maxWidth: 680}}>
          Get the complete 9-category audit.
        </h2>
      </div>
      <div className="fvp-grid">
        <div className="fvp-card">
          <div className="chip" style={{marginBottom: 16}}>Free</div>
          <h3 className="serif" style={{fontSize: 32, margin: '0 0 8px'}}>Preview</h3>
          <p className="muted" style={{margin: '0 0 24px'}}>Overall grade + weak spots</p>
          <ul className="fvp-list">
            <li>✓ Overall grade A–F</li>
            <li>✓ Score across 9 categories</li>
            <li>✓ Top 3 issues identified</li>
            <li>— Specific fixes by category</li>
            <li>— Prioritized action plan</li>
            <li>— Competition benchmark</li>
          </ul>
          <a href="#audit" className="btn btn-outline btn-lg" style={{width:'100%', marginTop: 24}}>Audit for free</a>
        </div>
        <div className="fvp-card fvp-featured">
          <div className="chip chip-accent" style={{marginBottom: 16, background:'rgba(232,92,74,0.18)', color:'#FBE7DF'}}>Premium · $20 USD</div>
          <h3 className="serif" style={{fontSize: 32, margin: '0 0 8px'}}>Full report</h3>
          <p style={{margin: '0 0 24px', color:'rgba(250,248,243,0.65)'}}>AI action plan + market benchmark</p>
          <ul className="fvp-list">
            <li>✓ Full grades A–F on all 9 categories</li>
            <li>✓ 5 quick wins with 3 steps each</li>
            <li>✓ 3 optimized titles, ready to copy</li>
            <li>✓ Rewritten description + pricing strategy</li>
            <li>✓ Market benchmark (Austin / Chicago) + 90-day roadmap</li>
            <li>✓ Downloadable PDF report</li>
          </ul>
          <div className="muted" style={{marginTop: 16, fontSize: 12}}>
            Regular $40 USD — today $20 USD (50% OFF launch promo)
          </div>
          <a href="/en/premium" className="btn btn-accent btn-lg" style={{width:'100%', marginTop: 16}}>Get my full audit — $20 USD</a>
        </div>
      </div>
    </div>
  </section>
);

// Beta invite — replaces testimonials for the US launch.
const BetaInvite = () => (
  <section className="section section-tinted">
    <div className="wrap">
      <div className="beta-invite" style={{
        maxWidth: 760, margin: '0 auto', textAlign:'center',
        padding: '48px 32px', border: '1px solid rgba(250,248,243,0.1)',
        borderRadius: 20, background: 'rgba(250,248,243,0.03)',
      }}>
        <span className="eyebrow" style={{justifyContent:'center', marginBottom: 20}}>Early access</span>
        <h3 className="h2" style={{margin: '0 auto 16px', maxWidth: 620}}>
          Join the first 100 US hosts shaping v1.
        </h3>
        <p style={{maxWidth: 520, margin: '0 auto', color: 'rgba(250,248,243,0.75)', lineHeight: 1.6}}>
          Direct line to the founders. Text us on WhatsApp or SMS at{' '}
          <a href="https://wa.me/523319170053" style={{color:'var(--accent, #E25A4A)', fontWeight: 600}}>
            +52 33 1917 0053
          </a>.
        </p>
      </div>
    </div>
  </section>
);

const PdfPreview = () => {
  const TOTAL = 7;
  const [idx, setIdx] = React.useState(0);
  const go = (delta) => setIdx((i) => (i + delta + TOTAL) % TOTAL);
  const onKey = (e) => {
    if (e.key === 'ArrowRight') go(1);
    if (e.key === 'ArrowLeft') go(-1);
  };
  return (
    <section className="section section-tinted" style={{paddingTop: 80, paddingBottom: 80}}>
      <div className="wrap">
        <div style={{textAlign:'center', maxWidth: 680, margin:'0 auto 40px'}}>
          <span className="eyebrow" style={{justifyContent:'center'}}>What the premium report looks like</span>
          <h2 className="h2" style={{margin: '16px auto 0'}}>
            7 pages. <em>Ready to implement.</em>
          </h2>
          <p className="muted" style={{marginTop: 14, fontSize: 14}}>
            Use the arrows to browse each page of the real report.
          </p>
        </div>
        <div
          role="region"
          aria-label="Premium report carousel"
          tabIndex={0}
          onKeyDown={onKey}
          style={{position:'relative', maxWidth: 720, margin:'0 auto', outline:'none'}}
        >
          <div style={{
            position:'relative',
            aspectRatio: '3 / 4',
            background:'rgba(250,248,243,0.04)',
            borderRadius: 14,
            overflow:'hidden',
            boxShadow:'0 24px 56px rgba(0,0,0,0.4)',
          }}>
            {Array.from({length: TOTAL}).map((_, i) => (
              <img
                key={i}
                src={`/img/report/page-${i+1}.jpg`}
                alt={`AuditBnB premium report — page ${i+1} of ${TOTAL}`}
                loading={i === 0 ? 'eager' : 'lazy'}
                style={{
                  position:'absolute', top: 0, left: 0,
                  width:'100%', height:'100%', objectFit:'contain',
                  opacity: i === idx ? 1 : 0,
                  transition:'opacity 240ms ease',
                  background:'#FAF8F3',
                }}
              />
            ))}
          </div>
          <button
            type="button"
            aria-label="Previous page"
            onClick={() => go(-1)}
            style={{
              position:'absolute', top:'50%', left: -18,
              transform:'translateY(-50%)',
              width: 44, height: 44, borderRadius:'50%',
              background:'#FAF8F3', color:'#1a1a1a', border:'none',
              boxShadow:'0 6px 16px rgba(0,0,0,0.25)',
              cursor:'pointer', fontSize: 20, lineHeight: 1,
              display:'flex', alignItems:'center', justifyContent:'center',
            }}
          >‹</button>
          <button
            type="button"
            aria-label="Next page"
            onClick={() => go(1)}
            style={{
              position:'absolute', top:'50%', right: -18,
              transform:'translateY(-50%)',
              width: 44, height: 44, borderRadius:'50%',
              background:'#FAF8F3', color:'#1a1a1a', border:'none',
              boxShadow:'0 6px 16px rgba(0,0,0,0.25)',
              cursor:'pointer', fontSize: 20, lineHeight: 1,
              display:'flex', alignItems:'center', justifyContent:'center',
            }}
          >›</button>
          <div style={{
            display:'flex', justifyContent:'center', gap: 8,
            marginTop: 20,
          }}>
            {Array.from({length: TOTAL}).map((_, i) => (
              <button
                key={i}
                type="button"
                aria-label={`Go to page ${i+1}`}
                aria-current={i === idx}
                onClick={() => setIdx(i)}
                style={{
                  width: i === idx ? 24 : 8, height: 8, borderRadius: 4,
                  background: i === idx ? '#E25A4A' : 'rgba(250,248,243,0.25)',
                  border:'none', padding: 0, cursor:'pointer',
                  transition:'width 160ms ease, background 160ms ease',
                }}
              />
            ))}
          </div>
          <div className="mono muted" style={{textAlign:'center', marginTop: 10, fontSize: 12}}>
            Page {idx+1} of {TOTAL}
          </div>
        </div>
        <div style={{textAlign:'center', marginTop: 36}}>
          <a href="/en/premium" className="btn btn-accent btn-lg">
            Get the full report · Ready to implement
          </a>
        </div>
      </div>
    </section>
  );
};

const AuthorityStack = () => (
  <section className="section" style={{paddingTop: 24, paddingBottom: 24}}>
    <div className="wrap">
      <div style={{
        display:'grid',
        gridTemplateColumns:'repeat(auto-fit, minmax(240px, 1fr))',
        gap: 24,
        padding: '28px 32px',
        border: '1px solid rgba(250,248,243,0.08)',
        borderRadius: 16,
        background: 'rgba(250,248,243,0.03)',
      }}>
        <div>
          <div className="eyebrow" style={{marginBottom: 8}}>Built from the inside</div>
          <div style={{fontSize: 15, lineHeight: 1.45, color:'rgba(250,248,243,0.8)'}}>
            Built by active Airbnb hosts who manage short-term rentals at scale.
          </div>
        </div>
        <div>
          <div className="eyebrow" style={{marginBottom: 8}}>Proven engine</div>
          <div style={{fontSize: 15, lineHeight: 1.45, color:'rgba(250,248,243,0.8)'}}>
            9 categories graded with GPT-4.1 + Inside Airbnb data for Austin and Chicago.
          </div>
        </div>
        <div>
          <div className="eyebrow" style={{marginBottom: 8}}>Live today</div>
          <div style={{fontSize: 15, lineHeight: 1.45, color:'rgba(250,248,243,0.8)'}}>
            Now open to US hosts — we are onboarding the first 100.
          </div>
        </div>
      </div>
    </div>
  </section>
);

// FAQ block — short, EN-US specific.
const FaqSection = () => {
  const faqs = [
    { q: 'How does the audit work?', a: 'Paste your public Airbnb URL. We scrape the listing, then the AI grades 9 categories A–F and highlights the top problems. No account access, no credentials.' },
    { q: 'Is my email shared?', a: 'No. We only use your email to send you the report. No spam, unsubscribe anytime.' },
    { q: "What's included in the paid report?", a: '9 categories graded in full, 3 optimized titles, rewritten description, pricing strategy, market benchmark for Austin or Chicago and a 90-day roadmap.' },
    { q: 'Do you support Airbnb.com listings?', a: 'Yes — the tool is built for US hosts. Just paste the public URL.' },
    { q: 'How accurate is the AI?', a: 'We use GPT-4.1 combined with market data from Inside Airbnb for Austin and Chicago. Grades are based on concrete signals, not opinion.' },
  ];
  const [open, setOpen] = React.useState(0);
  return (
    <section className="section" id="faq">
      <div className="wrap">
        <div className="section-head" style={{textAlign:'center', margin: '0 auto 40px'}}>
          <span className="eyebrow" style={{justifyContent:'center'}}>FAQ</span>
          <h2 className="h2" style={{margin:'16px auto 0', maxWidth: 680}}>
            Common questions.
          </h2>
        </div>
        <div style={{maxWidth: 720, margin: '0 auto', display:'flex', flexDirection:'column', gap: 12}}>
          {faqs.map((f, i) => (
            <details
              key={i}
              open={open === i}
              onToggle={(e) => { if (e.currentTarget.open) setOpen(i); }}
              style={{
                border: '1px solid rgba(250,248,243,0.1)',
                borderRadius: 12,
                padding: '18px 20px',
                background: 'rgba(250,248,243,0.03)',
              }}
            >
              <summary style={{fontWeight: 600, fontSize: 16, cursor:'pointer', listStyle:'none'}}>
                {f.q}
              </summary>
              <p style={{margin: '12px 0 0', lineHeight: 1.6, color: 'rgba(250,248,243,0.75)', fontSize: 14}}>
                {f.a}
              </p>
            </details>
          ))}
        </div>
      </div>
    </section>
  );
};

const FinalCTA = () => (
  <section className="section">
    <div className="wrap">
      <div className="cta-box">
        <div>
          <h2 className="h2" style={{margin: 0, maxWidth: 640}}>
            Find out how many bookings you are leaving on the table.
          </h2>
          <p style={{marginTop: 16, maxWidth: 560, color:'rgba(250,248,243,0.65)'}}>
            Your first audit is free. No card. No Airbnb account access.
          </p>
        </div>
        <div style={{display:'flex', gap: 12}}>
          <a href="#audit" className="btn btn-primary btn-lg">Audit my listing</a>
          <a href="/en/premium" className="btn btn-outline btn-lg">See premium</a>
        </div>
      </div>
    </div>
  </section>
);

Object.assign(window, {
  Hero, LogoBand, HowItWorks, FreeVsPremium, PdfPreview,
  BetaInvite, AuthorityStack, FaqSection, FinalCTA,
  AuditDemo, ListingMockup, CompetitionPanel, AnnotationCard, MobileAnnotationStack
});
