// SQSEO marketing, interactive Free GEO Audit widget (Phase 5 lead magnet).
// Paste a URL -> POST /api/tools/geo-audit -> a REAL on-page GEO-readiness score,
// per-engine readiness (ChatGPT / Perplexity / Gemini / Google AI Overviews), and the
// top concrete fixes. No signup to run it; signup handoff for the full report.
(function init(){
if(!window.LongtailIQDesignSystem_ae8f12 || !window.LTQM){return setTimeout(init,30);}
const React = window.React;
const DS = window.LongtailIQDesignSystem_ae8f12;
const { Icon, Button } = DS;
const M = window.LTQM;

const gradeColor = (g) => (g === "A" || g === "B" ? "var(--viz-green)" : g === "C" ? "var(--amber-500)" : "var(--red-500)");
const statusMeta = { ready: ["var(--viz-green)", "Ready"], partial: ["var(--amber-500)", "Partial"], weak: ["var(--ink-400)", "Weak"] };

function ScoreRing({ score, grade }) {
  const r = 54, c = 2 * Math.PI * r;
  const col = gradeColor(grade);
  return (
    <div style={{ position: "relative", width: 140, height: 140, flex: "none" }}>
      <svg width="140" height="140" viewBox="0 0 140 140" style={{ transform: "rotate(-90deg)" }}>
        <circle cx="70" cy="70" r={r} fill="none" stroke="var(--ink-150)" strokeWidth="10" />
        <circle cx="70" cy="70" r={r} fill="none" stroke={col} strokeWidth="10" strokeLinecap="round"
          strokeDasharray={c} strokeDashoffset={c * (1 - score / 100)} style={{ transition: "stroke-dashoffset 1.1s var(--ease-out)" }} />
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", textAlign: "center" }}>
        <div>
          <div className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 34, fontWeight: 700, color: "var(--text-strong)", lineHeight: 1 }}>
            {M.Counter ? <M.Counter to={score} duration={1100} /> : score}
          </div>
          <div style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 2 }}>GEO score · {grade}</div>
        </div>
      </div>
    </div>
  );
}

function Result({ data, onReset }) {
  if (!data.ok) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 18px", border: "1px solid var(--border-strong)", borderRadius: "var(--r-lg)", background: "var(--surface-card)" }}>
        <Icon name="alert-triangle" size={18} style={{ color: "var(--amber-500)", flex: "none" }} />
        <span style={{ fontSize: 14, color: "var(--text-body)", flex: 1 }}>{data.error || "Could not fetch that URL."} Check the address and try again.</span>
        <button onClick={onReset} style={{ border: "none", background: "transparent", color: "var(--accent-600)", fontWeight: 600, fontSize: 13, cursor: "pointer" }}>Try again</button>
      </div>
    );
  }
  let host = data.url; try { host = new URL(data.finalUrl || data.url).host; } catch (e) {}
  return (
    <div className="fx-enter" style={{ border: "1px solid var(--border-subtle)", borderRadius: "var(--r-xl)", background: "var(--surface-card)", boxShadow: "var(--shadow-md)", overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "12px 18px", borderBottom: "1px solid var(--border-subtle)", background: "var(--ink-50)" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 600, color: "var(--text-strong)", minWidth: 0 }}>
          <Icon name="globe" size={15} style={{ color: "var(--text-faint)", flex: "none" }} /><span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{host}</span>
        </span>
        <button onClick={onReset} style={{ border: "none", background: "transparent", color: "var(--text-muted)", fontWeight: 600, fontSize: 12.5, cursor: "pointer", flex: "none" }}>Audit another</button>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 24, padding: 22, alignItems: "center" }} className="lt-geo-result">
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
          <ScoreRing score={data.score} grade={data.grade} />
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--text-faint)", marginBottom: 9 }}>Can these engines cite you?</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 16 }}>
            {data.engines.map((e) => {
              const [col, label] = statusMeta[e.status] || statusMeta.weak;
              return (
                <span key={e.id} title={e.score + "/100"} style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 30, padding: "0 11px", borderRadius: 999, border: "1px solid var(--border-subtle)", background: "var(--paper)", fontSize: 12.5, fontWeight: 600, color: "var(--text-body)" }}>
                  <span style={{ width: 7, height: 7, borderRadius: 999, background: col }} />{e.name}<span style={{ color: "var(--text-faint)", fontWeight: 500 }}>· {label}</span>
                </span>
              );
            })}
          </div>
          {data.topFixes && data.topFixes.length > 0 && (
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--text-faint)", marginBottom: 8 }}>Top fixes</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
                {data.topFixes.slice(0, 3).map((f, i) => (
                  <div key={i} style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 13, color: "var(--text-body)", lineHeight: 1.5 }}>
                    <Icon name="arrow-right" size={14} style={{ color: "var(--accent-500)", marginTop: 2, flex: "none" }} />{f}
                  </div>
                ))}
              </div>
            </div>
          )}
          <M.Magnetic strength={0.4}>
            <Button variant="primary" size="md" className="fx-sheen" trailingIcon="arrow-right" onClick={()=>{window.location.href="/app/register.html";}}>Fix these free with SQSEO</Button>
          </M.Magnetic>
        </div>
      </div>
    </div>
  );
}

function GeoAudit() {
  const [url, setUrl] = React.useState("");
  const [phase, setPhase] = React.useState("idle"); // idle | loading | done
  const [data, setData] = React.useState(null);
  const submit = async (e) => {
    e && e.preventDefault();
    const v = url.trim();
    if (v.length < 3 || phase === "loading") return;
    setPhase("loading");
    try {
      const res = await fetch("/api/tools/geo-audit", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url: v }) });
      const d = await res.json().catch(() => ({}));
      if (res.ok) setData(d);
      else setData({ ok: false, error: d.message || "Enter a valid URL." });
    } catch (err) {
      setData({ ok: false, error: "Could not reach the server." });
    }
    setPhase("done");
  };
  const reset = () => { setPhase("idle"); setData(null); };

  return (
    <div style={{ position: "relative", borderTop: "1px solid var(--border-subtle)", background: "var(--paper)", overflow: "hidden" }}>
      <div className="fx-bg-glow" aria-hidden style={{ position: "absolute", inset: 0, pointerEvents: "none", opacity: 0.7 }} />
      <section style={{ position: "relative", maxWidth: 820, margin: "0 auto", padding: "76px 24px", textAlign: "center" }}>
        <div className="lt-reveal" style={{ marginBottom: 18 }}>
          <span className="lt-pill-label"><span style={{ width: 7, height: 7, borderRadius: 999, background: "var(--accent-500)", boxShadow: "0 0 0 3px var(--accent-100)" }} />Free GEO audit · no signup</span>
        </div>
        <h2 className="lt-reveal lt-display" style={{ fontSize: "clamp(1.9rem,1.4rem+1.6vw,2.6rem)", fontWeight: 700, letterSpacing: "-0.025em", color: "var(--ink-900)", lineHeight: 1.08 }}>
          Do ChatGPT, Perplexity &amp; Gemini<br/><span style={{ color: "var(--ink-400)" }}>recommend your site?</span>
        </h2>
        <p className="lt-reveal" style={{ fontSize: 16, color: "var(--text-muted)", marginTop: 14, lineHeight: 1.6, maxWidth: 560, marginLeft: "auto", marginRight: "auto" }}>
          Paste your URL. We check the real on-page signals that decide whether AI engines can crawl, understand, and cite you. Real checks, no fluff.
        </p>
        <form onSubmit={submit} className="lt-reveal" style={{ display: "flex", gap: 8, justifyContent: "center", flexWrap: "wrap", margin: "26px auto 0", maxWidth: 560 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, flex: "1 1 300px", minWidth: 240, height: 50, padding: "0 14px", background: "var(--surface-card)", border: "1px solid var(--border-strong)", borderRadius: "var(--r-md)", boxShadow: "var(--shadow-xs)" }}>
            <Icon name="search" size={18} style={{ color: "var(--accent-500)", flex: "none" }} />
            <input value={url} onChange={(e)=>setUrl(e.target.value)} type="text" inputMode="url" placeholder="yourdomain.com"
              aria-label="Your website URL"
              style={{ flex: 1, minWidth: 0, height: 46, border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-sans)", fontSize: 15, fontWeight: 500, color: "var(--text-strong)" }} />
          </div>
          <Button variant="primary" size="lg" className="fx-sheen" leadingIcon={phase === "loading" ? undefined : "radar"} disabled={phase === "loading" || url.trim().length < 3} onClick={submit}>
            {phase === "loading" ? "Auditing…" : "Run free audit"}
          </Button>
        </form>
        <div style={{ marginTop: 10, fontSize: 12, color: "var(--text-faint)" }}>We fetch the page once and check 13 GEO signals. Nothing is stored.</div>

        {phase !== "idle" && (
          <div style={{ marginTop: 26, textAlign: "left" }}>
            {phase === "loading" ? (
              <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 12, padding: "40px 0", color: "var(--text-muted)" }}>
                <span className="lt-spinner" style={{ display: "inline-block", width: 20, height: 20, border: "2px solid var(--accent-200)", borderTopColor: "var(--accent-500)", borderRadius: 999 }} />
                <span style={{ fontSize: 14 }}>Fetching the page and scoring 13 GEO signals…</span>
              </div>
            ) : data ? <Result data={data} onReset={reset} /> : null}
          </div>
        )}
      </section>
    </div>
  );
}
window.LTQM = window.LTQM || {};
window.LTQM.GeoAudit = GeoAudit;
})();
