/* ============================================================
   screen_audit.jsx — Технический аудит (M5)
   Состояния: idle → scanning → results, раскрытие ошибки
   ============================================================ */
function Audit({ ctx }) {
  const site = DATA.sites.find(s => s.id === ctx.site);
  const [phase, setPhase] = React.useState("results"); // idle | scanning | results
  const [scanned, setScanned] = React.useState(0);
  const [filter, setFilter] = React.useState("all");
  const [openId, setOpenId] = React.useState("i1");
  const [toast, setToast] = React.useState(null);

  const issues = DATA.issues;
  const counts = {
    critical: issues.filter(i => i.sev === "critical").length,
    important: issues.filter(i => i.sev === "important").length,
    minor: issues.filter(i => i.sev === "minor").length,
  };

  React.useEffect(() => {
    if (phase !== "scanning") return;
    setScanned(0);
    const total = 500;
    const iv = setInterval(() => {
      setScanned(s => {
        const next = s + Math.floor(18 + Math.random() * 34);
        if (next >= total) { clearInterval(iv); setTimeout(() => setPhase("results"), 500); return total; }
        return next;
      });
    }, 120);
    return () => clearInterval(iv);
  }, [phase]);

  const shown = filter === "all" ? issues.filter(i => i.sev !== "good") : issues.filter(i => i.sev === filter);

  function makeTask(issue) {
    setToast(`Задача создана: «${issue.title}»`);
    setTimeout(() => setToast(null), 2800);
  }

  if (phase === "idle") return <AuditIdle site={site} onStart={() => setPhase("scanning")} />;
  if (phase === "scanning") return <AuditScanning site={site} scanned={scanned} />;

  return (
    <div className="grid" style={{ gap: 18 }}>
      {toast && <Toast text={toast} />}
      {/* header summary */}
      <div className="card" style={{ overflow: "hidden" }}>
        <div style={{ display: "flex", gap: 28, padding: "22px 24px", alignItems: "center", flexWrap: "wrap" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
            <Ring value={site.health} size={104} stroke={10} label="из 100" />
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: ".05em" }}>Health Score</div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 4 }}>
                <Favicon site={site} size={18} radius={5} />
                <span style={{ fontWeight: 700, fontSize: 14 }}>{site.title}</span>
              </div>
              <div style={{ marginTop: 8, display: "flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--green-ink)", fontWeight: 700 }}>
                <Icon name="arrow_up" size={14} />+12 пунктов с прошлого аудита
              </div>
            </div>
          </div>
          <div style={{ width: 1, alignSelf: "stretch", background: "var(--border)" }} />
          <div style={{ display: "flex", gap: 12, flex: 1 }}>
            <SevTile sev="critical" n={counts.critical} active={filter} setFilter={setFilter} />
            <SevTile sev="important" n={counts.important} active={filter} setFilter={setFilter} />
            <SevTile sev="minor" n={counts.minor} active={filter} setFilter={setFilter} />
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-end" }}>
            <div style={{ fontSize: 12, color: "var(--ink-4)", fontWeight: 600 }}>Последний аудит: сегодня, 09:00</div>
            <button className="btn btn-ghost btn-sm" onClick={() => setPhase("idle")}><Icon name="refresh" size={14} />Запустить заново</button>
          </div>
        </div>
        {/* compare strip */}
        <div style={{ display: "flex", gap: 18, padding: "12px 24px", background: "var(--green-soft)", borderTop: "1px solid var(--border)", fontSize: 13, fontWeight: 600, color: "var(--green-ink)", alignItems: "center" }}>
          <Icon name="check_circle" size={16} />
          Со времени прошлого аудита: <b>исправлено&nbsp;8&nbsp;ошибок</b>, появилось <b style={{ color: "var(--orange-ink)" }}>2&nbsp;новых</b>. Хорошая динамика!
        </div>
      </div>

      {/* filters */}
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <div className="chips">
          <button className={"chip" + (filter === "all" ? " on" : "")} onClick={() => setFilter("all")}>Все <span className="cnt">{counts.critical + counts.important + counts.minor}</span></button>
          <button className={"chip" + (filter === "critical" ? " on" : "")} onClick={() => setFilter("critical")}><span className="dot d-red" />Критичные <span className="cnt">{counts.critical}</span></button>
          <button className={"chip" + (filter === "important" ? " on" : "")} onClick={() => setFilter("important")}><span className="dot d-orange" />Важные <span className="cnt">{counts.important}</span></button>
          <button className={"chip" + (filter === "minor" ? " on" : "")} onClick={() => setFilter("minor")}><span className="dot d-yellow" />Желательные <span className="cnt">{counts.minor}</span></button>
        </div>
        <div style={{ flex: 1 }} />
        <button className="btn btn-ghost btn-sm"><Icon name="download" size={14} />Экспорт</button>
      </div>

      {/* issues accordion */}
      <div className="card">
        {shown.map((iss, i) => <IssueRow key={iss.id} iss={iss} open={openId === iss.id} onToggle={() => setOpenId(openId === iss.id ? null : iss.id)} onTask={() => makeTask(iss)} last={i === shown.length - 1} />)}
        {shown.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>Ошибок этого типа не найдено 🎉</div>}
      </div>
    </div>
  );
}

function SevTile({ sev, n, active, setFilter }) {
  const m = severityMeta[sev];
  const on = active === sev;
  return (
    <button onClick={() => setFilter(on ? "all" : sev)}
      style={{ flex: 1, textAlign: "left", border: `1px solid ${on ? m.color : "var(--border)"}`, background: on ? `color-mix(in srgb, ${m.color} 8%, white)` : "var(--surface)", borderRadius: 12, padding: "12px 14px", cursor: "pointer", transition: "all .12s" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 6 }}>
        <span className="dot" style={{ background: m.color }} />
        <span style={{ fontSize: 12, fontWeight: 700, color: "var(--ink-2)" }}>{m.label}</span>
      </div>
      <div className="tnum" style={{ fontSize: 26, fontWeight: 800, color: m.color, lineHeight: 1 }}>{n}</div>
    </button>
  );
}

function IssueRow({ iss, open, onToggle, onTask, last }) {
  const m = severityMeta[iss.sev];
  return (
    <div style={{ borderBottom: last ? "none" : "1px solid var(--border)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 13, padding: "15px 18px", cursor: "pointer" }} onClick={onToggle}>
        <div className="prio-bar" style={{ background: m.color, height: 30 }} />
        <span className={"badge b-" + m.cls} style={{ flex: "0 0 auto" }}>{m.label}</span>
        <span style={{ fontSize: 14, fontWeight: 700, flex: 1, color: "var(--ink)" }}>{iss.title}</span>
        {iss.count > 0 && <span style={{ fontSize: 12, color: "var(--ink-4)", fontWeight: 600 }}>{iss.count} {plural(iss.count, "страница","страницы","страниц")}</span>}
        <span style={{ color: "var(--ink-4)", transform: open ? "rotate(90deg)" : "none", transition: "transform .18s" }}><Icon name="chevron_right" size={18} /></span>
      </div>
      {open && (
        <div style={{ padding: "4px 18px 20px 34px", animation: "rfade .2s ease" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
            <Anatomy icon="info" color="var(--ink-3)" label="Что не так" text={iss.what} />
            <Anatomy icon="alert_triangle" color="var(--orange)" label="Почему это важно" text={iss.why} />
          </div>
          {iss.fix.length > 0 && (
            <div style={{ background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 12, padding: "14px 16px", marginBottom: 14 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 10, fontSize: 12.5, fontWeight: 700, color: "var(--accent-ink)" }}><Icon name="wrench" size={15} />Как исправить</div>
              <ol style={{ margin: 0, paddingLeft: 20, display: "flex", flexDirection: "column", gap: 7 }}>
                {iss.fix.map((f, i) => <li key={i} style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.45 }}>{f}</li>)}
              </ol>
              {iss.code && <CodeBlock code={iss.code} />}
            </div>
          )}
          {iss.pages.length > 0 && (
            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 8 }}>Затронутые страницы</div>
              <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>
                {iss.pages.map((p, i) => <span key={i} style={{ fontFamily: "ui-monospace, monospace", fontSize: 12, background: "var(--bg-sunken)", padding: "4px 9px", borderRadius: 7, color: "var(--ink-2)", fontWeight: 600 }}>{p}</span>)}
              </div>
            </div>
          )}
          <div style={{ display: "flex", gap: 10 }}>
            <button className="btn btn-primary btn-sm" onClick={onTask}><Icon name="plus" size={14} />Создать задачу</button>
            {iss.id === "i5" && <button className="btn btn-soft btn-sm"><Icon name="sparkles" size={14} />Сгенерировать alt через ИИ</button>}
            <button className="btn btn-ghost btn-sm">Игнорировать</button>
          </div>
        </div>
      )}
    </div>
  );
}

function Anatomy({ icon, color, label, text }) {
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 7, fontSize: 12.5, fontWeight: 700, color }}><Icon name={icon} size={15} />{label}</div>
      <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>{text}</div>
    </div>
  );
}

function CodeBlock({ code }) {
  const [copied, setCopied] = React.useState(false);
  return (
    <div style={{ marginTop: 12, position: "relative" }}>
      <pre style={{ margin: 0, background: "#1E2430", color: "#E4E8F0", padding: "12px 14px", borderRadius: 10, fontSize: 12, fontFamily: "ui-monospace, SFMono-Regular, monospace", overflowX: "auto", lineHeight: 1.55 }}>{code}</pre>
      <button className="icon-btn" style={{ position: "absolute", top: 8, right: 8, background: "rgba(255,255,255,.1)", border: "none", color: "#cfd6e2" }}
        onClick={() => { navigator.clipboard?.writeText(code); setCopied(true); setTimeout(() => setCopied(false), 1500); }}>
        <Icon name={copied ? "check_circle" : "copy"} size={15} />
      </button>
    </div>
  );
}

function AuditIdle({ site, onStart }) {
  return (
    <div className="card" style={{ padding: "56px 30px", textAlign: "center" }}>
      <div className="empty" style={{ padding: 0 }}>
        <span className="ic" style={{ width: 64, height: 64 }}><Icon name="stethoscope" size={30} /></span>
        <h3 style={{ fontSize: 19 }}>Запустить технический аудит</h3>
        <p style={{ maxWidth: 420 }}>Просканируем до 500 страниц сайта <b>{site.domain}</b>: статус-коды, скорость, индексацию, мета-теги и структуру. Найдём проблемы и предложим, как их исправить.</p>
        <button className="btn btn-primary btn-lg" onClick={onStart}><Icon name="play" size={16} />Запустить аудит</button>
        <div style={{ marginTop: 24, display: "inline-flex", gap: 24, padding: "12px 20px", background: "var(--bg-sunken)", borderRadius: 12 }}>
          <Mini label="Прошлый аудит" value="3 недели назад" />
          <div style={{ width: 1, background: "var(--border-strong)" }} />
          <Mini label="Тогда Health Score" value="70 / 100" />
          <div style={{ width: 1, background: "var(--border-strong)" }} />
          <Mini label="Исправлено с тех пор" value="8 ошибок" />
        </div>
      </div>
    </div>
  );
}

function Mini({ label, value }) {
  return <div style={{ textAlign: "left" }}>
    <div style={{ fontSize: 11, color: "var(--ink-4)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em" }}>{label}</div>
    <div style={{ fontSize: 14, fontWeight: 700, marginTop: 3 }}>{value}</div>
  </div>;
}

function AuditScanning({ site, scanned }) {
  const total = 500;
  const pct = Math.min(100, (scanned / total) * 100);
  const findings = [
    { sev: "critical", t: "Найден noindex на /proekty/dom-iz-brusa", at: 88 },
    { sev: "important", t: "Страница без H1: /uslugi/remont", at: 64 },
    { sev: "minor", t: "Изображение без alt: kuhnya-1.jpg", at: 40 },
    { sev: "critical", t: "Ошибка 404: /galereya/2022", at: 22 },
  ].filter(f => scanned > f.at);
  return (
    <div className="card card-pad" style={{ padding: "30px 28px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
        <span className="ic" style={{ width: 44, height: 44, borderRadius: 12, background: "var(--accent-soft)", color: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="search" size={22} /></span>
        <div>
          <div style={{ fontSize: 17, fontWeight: 800 }}>Сканируем {site.domain}…</div>
          <div style={{ fontSize: 13, color: "var(--ink-3)", fontWeight: 600 }}>Просканировано <b className="tnum">{scanned}</b> из ~{total} страниц</div>
        </div>
        <div style={{ flex: 1 }} />
        <span className="tnum" style={{ fontSize: 28, fontWeight: 800, color: "var(--accent)" }}>{Math.round(pct)}%</span>
      </div>
      <div className="bar" style={{ height: 10 }}><i style={{ width: pct + "%" }} /></div>
      <div style={{ marginTop: 20 }}>
        <div style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 10 }}>Лог находок</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {findings.map((f, i) => {
            const m = severityMeta[f.sev];
            return <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, animation: "rfade .25s ease" }}>
              <span className="dot" style={{ background: m.color }} /><span style={{ color: "var(--ink-2)", fontWeight: 500 }}>{f.t}</span>
            </div>;
          })}
          <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, color: "var(--ink-4)" }}>
            <span className="skel" style={{ width: 8, height: 8, borderRadius: 99 }} /><span className="skel" style={{ width: 240, height: 13 }} />
          </div>
        </div>
      </div>
    </div>
  );
}

function Toast({ text }) {
  return (
    <div style={{ position: "fixed", bottom: 24, left: "50%", transform: "translateX(-50%)", zIndex: 200, background: "var(--ink)", color: "#fff", padding: "12px 18px", borderRadius: 12, boxShadow: "var(--sh-pop)", display: "flex", alignItems: "center", gap: 10, fontSize: 13.5, fontWeight: 600, animation: "pop .2s ease" }}>
      <span style={{ color: "var(--green)" }}><Icon name="check_circle" size={18} /></span>{text}
    </div>
  );
}

window.Audit = Audit;
window.Toast = Toast;
window.CodeBlock = CodeBlock;
