/* ============================================================
   screen_content.jsx — AI генератор контента (M10)
   Форма → стриминг → редактор + SEO-оценка + мета + библиотека
   ============================================================ */
function Content({ ctx }) {
  const site = DATA.sites.find(s => s.id === ctx.site);
  const [tab, setTab] = React.useState("generate"); // generate | library
  const [phase, setPhase] = React.useState("form"); // form | streaming | done
  const [text, setText] = React.useState("");
  const [kw, setKw] = React.useState("как выбрать пластиковые окна");
  const [len, setLen] = React.useState("2000");
  const [tone, setTone] = React.useState("Экспертный");
  const [fmt, setFmt] = React.useState("Гайд");
  const [pubOpen, setPubOpen] = React.useState(false);
  const streamRef = React.useRef(null);

  function generate() {
    setPhase("streaming"); setText("");
    const full = DATA.article;
    let i = 0;
    clearInterval(streamRef.current);
    streamRef.current = setInterval(() => {
      i += Math.floor(3 + Math.random() * 6);
      setText(full.slice(0, i));
      if (i >= full.length) { clearInterval(streamRef.current); setText(full); setPhase("done"); }
    }, 16);
  }
  React.useEffect(() => () => clearInterval(streamRef.current), []);

  return (
    <div className="grid" style={{ gap: 16 }}>
      <div className="seg" style={{ alignSelf: "flex-start" }}>
        <button className={tab === "generate" ? "on" : ""} onClick={() => setTab("generate")}><Icon name="sparkles" size={14} style={{ marginRight: 5, verticalAlign: "-2px" }} />Генератор</button>
        <button className={tab === "library" ? "on" : ""} onClick={() => setTab("library")}><Icon name="file_text" size={14} style={{ marginRight: 5, verticalAlign: "-2px" }} />Библиотека контента</button>
      </div>

      {tab === "library" ? <ContentLibrary /> : (
        <div style={{ display: "grid", gridTemplateColumns: "330px 1fr", gap: 16, alignItems: "start" }}>
          {/* form */}
          <div className="card card-pad" style={{ position: "sticky", top: 0 }}>
            <h3 style={{ margin: "0 0 16px", fontSize: 15, fontWeight: 800 }}>Параметры статьи</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <div className="field">
                <label className="label">Ключевое слово</label>
                <input className="input" value={kw} onChange={e => setKw(e.target.value)} />
                <span style={{ fontSize: 11.5, color: "var(--ink-4)", fontWeight: 600 }}>Вордстат: 1 600 показов/мес · конкуренция MEDIUM</span>
              </div>
              <div className="field">
                <label className="label">Длина</label>
                <div className="seg" style={{ width: "100%" }}>
                  {["1000", "2000", "3000"].map(l => <button key={l} className={len === l ? "on" : ""} style={{ flex: 1 }} onClick={() => setLen(l)}>{l}</button>)}
                </div>
              </div>
              <div className="field">
                <label className="label">Тон</label>
                <select className="select" value={tone} onChange={e => setTone(e.target.value)}>
                  <option>Экспертный</option><option>Дружелюбный</option><option>Деловой</option><option>Продающий</option>
                </select>
              </div>
              <div className="field">
                <label className="label">Формат</label>
                <select className="select" value={fmt} onChange={e => setFmt(e.target.value)}>
                  <option>Гайд</option><option>Список</option><option>Обзорная статья</option><option>FAQ</option>
                </select>
              </div>
              <div className="field">
                <label className="label">Аудитория</label>
                <input className="input" defaultValue="Жители Калининграда, планируют ремонт" />
              </div>
              <div style={{ background: "var(--accent-softer)", borderRadius: 10, padding: "10px 12px", fontSize: 12, color: "var(--accent-ink)", fontWeight: 600, display: "flex", gap: 8, alignItems: "flex-start" }}>
                <Icon name="layers" size={15} style={{ marginTop: 1, flex: "0 0 15px" }} />
                Учтём 8 LSI-ключей кластера и предложим внутренние ссылки на страницы сайта.
              </div>
              <button className="btn btn-primary btn-block" onClick={generate} disabled={phase === "streaming"}>
                <Icon name="sparkles" size={16} />{phase === "streaming" ? "Генерируем…" : phase === "done" ? "Сгенерировать заново" : "Сгенерировать"}
              </button>
            </div>
          </div>

          {/* editor + seo */}
          <div className="grid" style={{ gap: 16 }}>
            {phase === "form" && <EditorEmpty />}
            {phase !== "form" && (
              <div style={{ display: "grid", gridTemplateColumns: "1fr 260px", gap: 16, alignItems: "start" }}>
                <div className="card">
                  <div className="card-head">
                    <Icon name="file_text" size={16} style={{ color: "var(--accent)" }} />
                    <h3>Редактор</h3>
                    <div className="spacer" />
                    {phase === "streaming" && <span className="badge b-blue"><span className="skel" style={{ width: 8, height: 8, borderRadius: 99 }} />пишем…</span>}
                    {phase === "done" && <span className="badge b-green"><Icon name="check_circle" size={12} />готово</span>}
                  </div>
                  <div className="card-pad" style={{ minHeight: 360 }}>
                    <Markdown text={text} streaming={phase === "streaming"} />
                  </div>
                </div>
                <div className="grid" style={{ gap: 14, position: "sticky", top: 0 }}>
                  <SeoScore text={text} kw={kw} />
                </div>
              </div>
            )}

            {phase === "done" && <>
              <MetaVariants />
              <div className="card card-pad" style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <div style={{ flex: 1, fontSize: 13, color: "var(--ink-2)", fontWeight: 600 }}>Статья готова. Опубликовать в WordPress или сохранить?</div>
                <button className="btn btn-ghost btn-sm"><Icon name="download" size={14} />Экспорт MD/HTML</button>
                {site.wp
                  ? <button className="btn btn-primary btn-sm" onClick={() => setPubOpen(true)}><Icon name="wordpress" size={15} />Опубликовать в WordPress</button>
                  : <span className="badge b-gray" title="У сайта не подключён WordPress">WordPress не подключён — доступен экспорт</span>}
              </div>
            </>}
          </div>
        </div>
      )}

      {pubOpen && <PublishModal site={site} kw={kw} onClose={() => setPubOpen(false)} />}
    </div>
  );
}

function EditorEmpty() {
  return (
    <div className="card">
      <div className="empty" style={{ padding: "70px 24px" }}>
        <span className="ic"><Icon name="pen" /></span>
        <h3>Здесь появится ваша статья</h3>
        <p>Заполните параметры слева и нажмите «Сгенерировать». ИИ напишет SEO-оптимизированный текст со структурой H2–H3, списками и FAQ-блоком.</p>
      </div>
    </div>
  );
}

// Minimal markdown renderer (headings, lists, bold, paragraphs)
function Markdown({ text, streaming }) {
  const blocks = React.useMemo(() => {
    const lines = text.split("\n"); const out = []; let list = null;
    lines.forEach((ln, i) => {
      if (/^# /.test(ln)) out.push({ t: "h1", c: ln.slice(2) });
      else if (/^## /.test(ln)) out.push({ t: "h2", c: ln.slice(3) });
      else if (/^- /.test(ln)) { if (!list) { list = { t: "ul", items: [] }; out.push(list); } list.items.push(ln.slice(2)); }
      else if (/^\d+\. /.test(ln)) { const c = ln.replace(/^\d+\.\s/, ""); if (!list || list.t !== "ol") { list = { t: "ol", items: [] }; out.push(list); } list.items.push(c); }
      else { list = null; if (ln.trim()) out.push({ t: "p", c: ln }); }
    });
    return out;
  }, [text]);
  const inline = s => s.split(/(\*\*[^*]+\*\*)/g).map((p, i) => /^\*\*/.test(p) ? <b key={i}>{p.slice(2, -2)}</b> : p);
  return (
    <div style={{ fontSize: 14, lineHeight: 1.65, color: "var(--ink)" }} className={streaming ? "cursor" : ""}>
      {blocks.map((b, i) => {
        if (b.t === "h1") return <h1 key={i} style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-.02em", margin: "0 0 14px" }}>{inline(b.c)}</h1>;
        if (b.t === "h2") return <h2 key={i} style={{ fontSize: 16.5, fontWeight: 800, margin: "20px 0 8px" }}>{inline(b.c)}</h2>;
        if (b.t === "ul") return <ul key={i} style={{ margin: "6px 0", paddingLeft: 22 }}>{b.items.map((it, j) => <li key={j} style={{ marginBottom: 5 }}>{inline(it)}</li>)}</ul>;
        if (b.t === "ol") return <ol key={i} style={{ margin: "6px 0", paddingLeft: 22 }}>{b.items.map((it, j) => <li key={j} style={{ marginBottom: 5 }}>{inline(it)}</li>)}</ol>;
        return <p key={i} style={{ margin: "0 0 12px", color: "var(--ink-2)" }}>{inline(b.c)}</p>;
      })}
      {blocks.length === 0 && <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>{[90, 70, 80, 60].map((w, i) => <span key={i} className="skel" style={{ height: 14, width: w + "%" }} />)}</div>}
    </div>
  );
}

function SeoScore({ text, kw }) {
  const words = text.trim() ? text.trim().split(/\s+/).length : 0;
  const kwCount = (text.toLowerCase().match(new RegExp(kw.split(" ")[0].toLowerCase(), "g")) || []).length;
  const h2 = (text.match(/^## /gm) || []).length;
  const score = Math.min(100, Math.round((Math.min(words, 500) / 500) * 50 + Math.min(kwCount, 6) / 6 * 25 + Math.min(h2, 4) / 4 * 25));
  const rows = [
    { label: "Ключ употреблён", val: kwCount, target: "5–8 раз", ok: kwCount >= 3 && kwCount <= 10, mid: kwCount > 0 && kwCount < 3 },
    { label: "Объём текста", val: words + " сл.", target: "≥ 400", ok: words >= 400, mid: words >= 200 && words < 400 },
    { label: "Подзаголовков H2", val: h2, target: "3–6", ok: h2 >= 3, mid: h2 >= 1 && h2 < 3 },
    { label: "Читаемость", val: "Хорошо", target: "лёгкая", ok: words > 100, mid: false },
  ];
  return (
    <div className="card card-pad">
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
        <Ring value={score} size={56} stroke={6} color="var(--accent)" />
        <div>
          <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-4)" }}>SEO-оценка</div>
          <div style={{ fontSize: 13.5, fontWeight: 800 }}>{score >= 80 ? "Отлично" : score >= 50 ? "Хорошо" : "Дорабатываем"}</div>
        </div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        {rows.map((r, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 9 }}>
            <span className="dot" style={{ background: r.ok ? "var(--green)" : r.mid ? "var(--yellow)" : "var(--ink-4)" }} />
            <span style={{ fontSize: 12.5, color: "var(--ink-2)", fontWeight: 600, flex: 1 }}>{r.label}</span>
            <span className="tnum" style={{ fontSize: 12.5, fontWeight: 800 }}>{r.val}</span>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--border)", fontSize: 11.5, color: "var(--ink-4)", fontWeight: 600 }}>
        Цель: ключ 5–8 раз, ≥400 слов, 3–6 подзаголовков.
      </div>
    </div>
  );
}

function MetaVariants() {
  const [sel, setSel] = React.useState(0);
  return (
    <div className="card">
      <div className="card-head"><Icon name="hash" size={16} style={{ color: "var(--accent)" }} /><h3>Варианты title и description</h3><div className="spacer" /><span style={{ fontSize: 12, color: "var(--ink-4)", fontWeight: 600 }}>выберите лучший</span></div>
      <div className="card-pad" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12 }}>
        {DATA.metaVariants.map((mv, i) => (
          <div key={i} onClick={() => setSel(i)} style={{ cursor: "pointer", border: `1.5px solid ${sel === i ? "var(--accent)" : "var(--border)"}`, background: sel === i ? "var(--accent-softer)" : "var(--surface)", borderRadius: 12, padding: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 8 }}>
              <span className={"cbx" + (sel === i ? " on" : "")} style={{ width: 16, height: 16, borderRadius: "50%" }}><Icon name="check_circle" size={10} strokeWidth={3} /></span>
              <span style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ink-4)" }}>Вариант {i + 1}</span>
            </div>
            <div style={{ fontSize: 13, fontWeight: 700, color: "#1a4ba0", lineHeight: 1.35, marginBottom: 5 }}>{mv.title}</div>
            <div style={{ fontSize: 11.5, color: "var(--ink-2)", lineHeight: 1.45, marginBottom: 9 }}>{mv.desc}</div>
            <div style={{ display: "flex", gap: 6 }}>
              <span className={"badge " + (mv.tLen <= 60 ? "b-green" : "b-orange")} style={{ height: 19, fontSize: 10.5 }}>title {mv.tLen}</span>
              <span className={"badge " + (mv.dLen >= 120 && mv.dLen <= 160 ? "b-green" : "b-orange")} style={{ height: 19, fontSize: 10.5 }}>desc {mv.dLen}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ContentLibrary() {
  const siteOf = id => DATA.sites.find(s => s.id === id);
  const stMap = { published: ["b-green", "опубликовано"], draft: ["b-gray", "черновик"], review: ["b-yellow", "на проверке"] };
  return (
    <div className="card">
      <table className="tbl">
        <thead><tr><th>Статья</th><th>Сайт</th><th>Ключ</th><th className="num">Слов</th><th>Статус</th><th className="num">Просмотры</th><th>Дата</th></tr></thead>
        <tbody>
          {DATA.contentLibrary.map((c, i) => (
            <tr key={i} className="clickable">
              <td style={{ fontWeight: 700, maxWidth: 280 }}>{c.title}</td>
              <td><span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontWeight: 600, fontSize: 12.5 }}><Favicon site={siteOf(c.site)} size={16} radius={4} />{siteOf(c.site).title}</span></td>
              <td style={{ color: "var(--ink-3)", fontSize: 12.5 }}>{c.kw}</td>
              <td className="num tnum">{c.words}</td>
              <td><span className={"badge " + stMap[c.status][0]}>{stMap[c.status][1]}</span></td>
              <td className="num tnum" style={{ fontWeight: 700 }}>{c.views || "—"}</td>
              <td style={{ color: "var(--ink-3)", fontSize: 12.5 }}>{c.date}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function PublishModal({ site, kw, onClose }) {
  const [status, setStatus] = React.useState("draft");
  const [done, setDone] = React.useState(false);
  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="modal">
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 10 }}>
          <Icon name="wordpress" size={20} style={{ color: "#21759B" }} />
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 800 }}>Публикация в WordPress</h3>
          <div style={{ flex: 1 }} /><button className="icon-btn" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>
        {done ? (
          <div className="empty" style={{ padding: "40px 24px" }}>
            <span className="ic" style={{ background: "var(--green-soft)", color: "var(--green)" }}><Icon name="check_circle" /></span>
            <h3>Опубликовано как {status === "publish" ? "запись" : "черновик"}</h3>
            <p>Статья отправлена на {site.domain}. ID записи: 412.</p>
            <button className="btn btn-primary" onClick={onClose}>Готово</button>
          </div>
        ) : (
          <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 16 }}>
            <div className="field"><label className="label">Заголовок</label><input className="input" defaultValue="Как выбрать пластиковые окна: полное руководство 2025" /></div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <div className="field"><label className="label">Рубрика</label><select className="select"><option>Блог</option><option>Полезное</option><option>Статьи</option></select></div>
              <div className="field"><label className="label">Обложка</label><button className="btn btn-ghost btn-block"><Icon name="image" size={15} />Выбрать</button></div>
            </div>
            <div className="field">
              <label className="label">Статус публикации</label>
              <div className="seg" style={{ width: "100%" }}>
                <button className={status === "draft" ? "on" : ""} style={{ flex: 1 }} onClick={() => setStatus("draft")}>Черновик</button>
                <button className={status === "review" ? "on" : ""} style={{ flex: 1 }} onClick={() => setStatus("review")}>На проверку</button>
                <button className={status === "publish" ? "on" : ""} style={{ flex: 1 }} onClick={() => setStatus("publish")}>Опубликовать</button>
              </div>
            </div>
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 4 }}>
              <button className="btn btn-ghost" onClick={onClose}>Отмена</button>
              <button className="btn btn-primary" onClick={() => setDone(true)}><Icon name="send" size={15} />Отправить</button>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

window.Content = Content;
