// SQSEO Site Audit — deterministic technical on-page audit.
// Reads the site scan's profile.audit (server/siteaudit.ts): a health score plus
// concrete on-page issues (titles, meta, H1, canonical, structured data, thin
// content, orphans) with the affected pages. 100% software, no LLM. Registered
// on window.LTQ.SiteAudit.
(function init() {
  if (!window.LongtailIQDesignSystem_ae8f12 || !window.LTQ || !window.LTQ.useApi || !window.LTQ.SectionTitle) { return setTimeout(init, 30); }
  const React = window.React;
  const DS = window.LongtailIQDesignSystem_ae8f12;
  const { Card, Icon, Badge } = DS;
  const { SectionTitle, useApi, EmptyState } = window.LTQ;
  const t = (k, v) => (window.LTQ.t ? window.LTQ.t(k, v) : k);

  const pathOf = (u) => { try { const x = new URL(u); return (x.pathname + x.search) || "/"; } catch (e) { return u; } };

  // severity → { tone (Badge), color, icon }
  const SEV = {
    high: { tone: "red", color: "var(--viz-red,#e5484d)", icon: "octagon-alert" },
    warn: { tone: "amber", color: "var(--amber-500,#f59e0b)", icon: "triangle-alert" },
    info: { tone: "neutral", color: "var(--text-faint)", icon: "info" },
  };
  const sevLabel = (s) => t("audit.sev_" + s);

  // Circular health-score gauge (stroke-dashoffset draw), colored by band.
  function ScoreGauge({ score }) {
    const R = 34, C = 2 * Math.PI * R;
    const band = score >= 90 ? "var(--viz-green,#30a46c)" : score >= 70 ? "var(--amber-500,#f59e0b)" : "var(--viz-red,#e5484d)";
    const reduced = typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const [drawn, setDrawn] = React.useState(reduced);
    React.useEffect(() => { if (reduced) return; const id = setTimeout(() => setDrawn(true), 80); return () => clearTimeout(id); }, []);
    const Odometer = window.LTQ.Odometer;
    const off = drawn ? C * (1 - score / 100) : C;
    return (
      <div style={{ position: "relative", width: 92, height: 92, flex: "none" }}>
        <svg width="92" height="92" viewBox="0 0 92 92">
          <circle cx="46" cy="46" r={R} fill="none" stroke="var(--ink-100)" strokeWidth="7" />
          <circle cx="46" cy="46" r={R} fill="none" stroke={band} strokeWidth="7" strokeLinecap="round"
            strokeDasharray={C} strokeDashoffset={off} transform="rotate(-90 46 46)"
            style={{ transition: reduced ? "none" : "stroke-dashoffset 1s var(--ease-spring)" }} />
        </svg>
        <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center" }}>
          {Odometer ? <Odometer value={score} className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 26, fontWeight: 700, color: "var(--text-strong)" }} />
            : <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 26, fontWeight: 700, color: "var(--text-strong)" }}>{score}</span>}
        </div>
      </div>
    );
  }

  function MiniStat({ label, value }) {
    const Odometer = window.LTQ.Odometer;
    const ns = { fontFamily: "var(--font-mono)", fontSize: 22, fontWeight: 700, color: "var(--text-strong)", letterSpacing: "-0.02em" };
    return (
      <div style={{ flex: 1, minWidth: 0 }}>
        {Odometer ? <Odometer value={Number(value) || 0} className="lt-num" style={ns} /> : <div className="lt-num" style={ns}>{value}</div>}
        <div style={{ fontSize: 12, color: "var(--text-muted)", fontWeight: 600, marginTop: 2 }}>{label}</div>
      </div>
    );
  }

  function PageRow({ p }) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 0", borderTop: "1px solid var(--border-subtle)" }}>
        <a href={p.url} target="_blank" rel="noopener noreferrer" title={p.url} style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 1, textDecoration: "none" }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: "var(--text-strong)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.title}</span>
          <span className="lt-num" style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{pathOf(p.url)}</span>
        </a>
        {p.detail && <span className="lt-num" style={{ flex: "none", fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-muted)", background: "var(--ink-50)", border: "1px solid var(--border-subtle)", borderRadius: 6, padding: "2px 7px", maxWidth: 200, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.detail}</span>}
      </div>
    );
  }

  function IssueCard({ iss, delay }) {
    const [open, setOpen] = React.useState(false);
    const s = SEV[iss.severity] || SEV.info;
    const shown = open ? iss.pages : iss.pages.slice(0, 5);
    return (
      <Card pad={0} className="lt-card-3d fx-enter" style={{ overflow: "hidden", "--enter-delay": (delay || 0) + "ms" }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "14px 18px" }}>
          <span style={{ width: 30, height: 30, flex: "none", borderRadius: 8, display: "grid", placeItems: "center", background: "var(--ink-50)", color: s.color }}>
            <Icon name={s.icon} size={16} />
          </span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
              <span style={{ fontSize: 14, fontWeight: 700, color: "var(--text-strong)" }}>{t("audit." + iss.id)}</span>
              <Badge tone={s.tone} variant="soft" dot>{sevLabel(iss.severity)}</Badge>
              <span style={{ fontSize: 12, color: "var(--text-faint)", fontWeight: 600 }}>{t("audit.affected", { n: iss.count })}</span>
            </div>
            <div style={{ fontSize: 12.5, color: "var(--text-muted)", marginTop: 3, lineHeight: 1.5 }}>{t("audit." + iss.id + "_d")}</div>
          </div>
        </div>
        <div style={{ padding: "0 18px 12px" }}>
          {shown.map((p) => <PageRow key={p.url} p={p} />)}
          {iss.count > 5 && (
            <button onClick={() => setOpen((o) => !o)} style={{ marginTop: 9, height: 30, padding: "0 12px", borderRadius: 8, border: "1px solid var(--border-subtle)", background: "var(--paper)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600, color: "var(--text-body)" }}>
              {open ? t("audit.affected", { n: iss.count }) : t("audit.show_all", { n: iss.count })}
            </button>
          )}
        </div>
      </Card>
    );
  }

  const Skel = ({ h = 90 }) => <span className="lt-shimmer" style={{ display: "block", height: h, borderRadius: 12, background: "var(--ink-100)" }} />;

  function SiteAudit() {
    const { loading, data } = useApi("/api/site-intel/profile");
    const profile = data && data.profile;
    const a0 = profile && profile.audit;
    // Profiles scanned before this feature may carry a partial audit blob.
    const a = a0 ? { ...a0, issues: a0.issues || [], passed: a0.passed || [] } : a0;

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        <SectionTitle eyebrow={t("audit.eyebrow")} title={t("nav.audit")} sub={t("audit.sub")} />

        {loading && (
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <Skel h={120} /><Skel h={110} /><Skel h={110} />
          </div>
        )}

        {!loading && !a && (
          <Card pad={0}><EmptyState icon="clipboard-check" sq="search" title={t("audit.empty_title")} body={t("audit.empty_body")} /></Card>
        )}

        {!loading && a && (
          <>
            <Card pad={22} className="lt-card-3d">
              <div style={{ display: "flex", alignItems: "center", gap: 22, flexWrap: "wrap" }}>
                <ScoreGauge score={a.score} />
                <div style={{ flex: 1, minWidth: 220 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--text-faint)", marginBottom: 12 }}>{t("audit.score")}</div>
                  <div style={{ display: "flex", gap: 20 }}>
                    <MiniStat label={t("audit.stat_pages")} value={a.pages} />
                    <MiniStat label={t("audit.stat_issues")} value={a.issues.length} />
                    <MiniStat label={t("audit.stat_passed")} value={a.passed.length} />
                  </div>
                </div>
              </div>
            </Card>

            {a.issues.length === 0 ? (
              <Card pad={0}><EmptyState icon="shield-check" sq="idle" title={t("audit.none_title")} body={t("audit.none_body")} /></Card>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {a.issues.map((iss, i) => <IssueCard key={iss.id} iss={iss} delay={Math.min(i, 8) * 40} />)}
              </div>
            )}

            {a.passed.length > 0 && (
              <div>
                <h3 style={{ fontSize: 13, fontWeight: 700, color: "var(--text-strong)", marginBottom: 10 }}>{t("audit.passed_title")}</h3>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                  {a.passed.map((id) => (
                    <span key={id} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 11px", borderRadius: 999, border: "1px solid var(--border-subtle)", background: "var(--paper)", fontSize: 12.5, fontWeight: 600, color: "var(--text-muted)" }}>
                      <Icon name="check" size={13} style={{ color: "var(--viz-green,#30a46c)" }} />{t("audit." + id)}
                    </span>
                  ))}
                </div>
              </div>
            )}
          </>
        )}
      </div>
    );
  }
  window.LTQ.SiteAudit = SiteAudit;
})();
