const { useState, useEffect, useCallback } = React;

// --- Telegram SDK -----------------------------------------------------------
const TG = window.Telegram && window.Telegram.WebApp ? window.Telegram.WebApp : null;
const INIT_DATA = TG ? TG.initData : "";
if (TG) { try { TG.ready(); TG.expand(); } catch (e) {} }

const ACCENT = "#59A4FF";
const api = (path) => fetch(path).then((r) => r.json());

// Градиент обложки коллекции по паре оттенков
function cover(hues) {
  const [a, b] = hues;
  return `radial-gradient(130% 100% at 15% 0%, oklch(0.62 0.21 ${a} / 0.9), transparent 55%), ` +
         `linear-gradient(155deg, oklch(0.5 0.21 ${a}), oklch(0.33 0.19 ${b}))`;
}

// --- Мини-рендер markdown ---------------------------------------------------
function renderInline(text, key) {
  const parts = text.split(/(\*\*[^*]+\*\*)/g).filter(Boolean);
  return parts.map((p, i) =>
    p.startsWith("**") && p.endsWith("**")
      ? <strong key={i} style={{ color: "#EDF1F9" }}>{p.slice(2, -2)}</strong>
      : <React.Fragment key={i}>{p}</React.Fragment>
  );
}
function Markdown({ text }) {
  const blocks = text.split(/\n\n+/);
  return blocks.map((block, i) => {
    if (block.startsWith("## ")) {
      return <h3 key={i} style={{ fontSize: 17, fontWeight: 700, margin: "22px 0 8px", letterSpacing: "-0.01em" }}>{block.slice(3)}</h3>;
    }
    if (block.split("\n").every((l) => l.startsWith("- "))) {
      return (
        <ul key={i} style={{ margin: "6px 0", paddingLeft: 18, display: "flex", flexDirection: "column", gap: 7 }}>
          {block.split("\n").map((l, j) => (
            <li key={j} style={{ fontSize: 14.5, lineHeight: 1.5, color: "#B7C0D4" }}>{renderInline(l.slice(2))}</li>
          ))}
        </ul>
      );
    }
    return <p key={i} style={{ fontSize: 14.5, lineHeight: 1.6, color: "#B7C0D4", margin: "8px 0" }}>{renderInline(block)}</p>;
  });
}

// --- Иконки -----------------------------------------------------------------
const IcSearch = () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#7C87A0" strokeWidth="2" strokeLinecap="round"><circle cx="11" cy="11" r="7" /><line x1="16.5" y1="16.5" x2="21" y2="21" /></svg>;
const IcBack = () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={ACCENT} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M15 5l-7 7 7 7" /></svg>;
const IcBookmark = ({ fill, stroke, size = 19 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke={stroke} strokeWidth="2" strokeLinejoin="round"><path d="M6 3h12v18l-6-4.5L6 21z" /></svg>;

// --- Теги -------------------------------------------------------------------
function fmtTag(fmt, formats) { return { t: (formats[fmt] || "") + " " + fmt, bg: "rgba(255,255,255,0.08)", fg: "#C6CEDE" }; }
function catTag(cat, cats) {
  const c = cats[cat] || { hue: 210, emoji: "" };
  return { t: (c.emoji || "") + " " + cat, bg: `oklch(0.72 0.17 ${c.hue} / 0.16)`, fg: `oklch(0.82 0.13 ${c.hue})` };
}
const Pill = ({ tag, size = 11.5 }) => (
  <span style={{ borderRadius: 999, padding: "4px 9px", fontSize: size, fontWeight: 600, whiteSpace: "nowrap", lineHeight: 1.4, background: tag.bg, color: tag.fg }}>{tag.t}</span>
);

// ============================================================================
function App() {
  const [data, setData] = useState(null);
  const [screen, setScreen] = useState("intro");
  const [stack, setStack] = useState([]);
  const [ob, setOb] = useState(-1);
  const [menuOpen, setMenuOpen] = useState(false);
  const [toast, setToast] = useState("");
  const [q, setQ] = useState("");
  const [sort, setSort] = useState("new");
  const [fMat, setFMat] = useState({});
  const [fFmt, setFFmt] = useState({});
  const [fCat, setFCat] = useState({});
  const [bookmarks, setBookmarks] = useState({});
  const [studied, setStudied] = useState({});
  const [lessons, setLessons] = useState({});
  const [curCol, setCurCol] = useState(null);
  const [curMat, setCurMat] = useState(null);
  const [activeTc, setActiveTc] = useState(-1);
  const [loadError, setLoadError] = useState(false);

  useEffect(() => {
    api("/api/bootstrap?init_data=" + encodeURIComponent(INIT_DATA))
      .then((d) => {
        setData(d);
        const toMap = (arr) => arr.reduce((m, x) => ((m[x] = true), m), {});
        setBookmarks(toMap(d.state.bookmarks));
        setStudied(toMap(d.state.studied));
        setLessons(toMap(d.state.lessons));
        // Стартовый экран и тур подсказок показываем только один раз —
        // если пользователь уже их проходил (флаг из БД), сразу открываем ленту.
        if (d.state.onboarded) { setScreen("feed"); }
      })
      .catch(() => setLoadError(true));
  }, []);

  const markOnboarded = () => {
    fetch("/api/onboarding-complete", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ init_data: INIT_DATA }),
    }).catch(() => {});
  };

  const showToast = (msg) => { setToast(msg); clearTimeout(window._tt); window._tt = setTimeout(() => setToast(""), 1600); };
  const go = (s) => { setStack((p) => [...p, screen]); setScreen(s); setMenuOpen(false); };
  const back = () => {
    const prev = stack.length ? stack[stack.length - 1] : "feed";
    setStack((p) => p.slice(0, -1));
    setScreen(prev);
  };
  const closeApp = () => { if (TG) { TG.close(); } setScreen("intro"); setStack([]); setOb(-1); };

  // Переключение статуса с синхронизацией на бэкенд
  const toggle = (kind, id, setter) => {
    setter((p) => ({ ...p, [id]: !p[id] }));
    fetch("/api/toggle", { method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ init_data: INIT_DATA, kind, id }) }).catch(() => {});
  };

  const openMaterial = (id) => {
    setActiveTc(-1);
    api("/api/material/" + id)
      .then((m) => {
        if (m && !m.error) { setCurMat(m); go("material"); }
        else { showToast("Материал недоступен"); }
      })
      .catch(() => showToast("Не удалось загрузить материал"));
  };
  const openCollection = (col) => {
    if (col.is_course && data.courses[col.id]) { setCurCol(col); go("course"); }
    else { setCurCol(col); go("collection"); }
  };

  if (loadError) {
    return <div style={{ minHeight: "100vh", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 12, color: "#7C87A0", padding: 24, textAlign: "center" }}>
      <div style={{ fontSize: 30 }}>⚠️</div>
      <div style={{ color: "#C6CEDE", fontWeight: 600 }}>Не удалось загрузить данные</div>
      <button onClick={() => location.reload()} style={{ background: "rgba(89,164,255,0.14)", border: "none", borderRadius: 12, padding: "10px 18px", color: ACCENT, fontSize: 14, fontWeight: 600, cursor: "pointer" }}>Повторить</button>
    </div>;
  }
  if (!data) {
    return <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", color: "#7C87A0" }}>Загрузка…</div>;
  }

  const { categories, formats, collections, materials, courses } = data;

  // --- Фильтрация ленты ---
  const query = q.toLowerCase();
  let feed = materials.filter((m) => {
    if (fMat.bm && !bookmarks[m.id]) return false;
    if (fMat.done && !studied[m.id]) return false;
    if (fMat.new && studied[m.id]) return false;
    const fs = Object.keys(fFmt).filter((k) => fFmt[k]);
    if (fs.length && !fs.includes(m.format)) return false;
    const cs = Object.keys(fCat).filter((k) => fCat[k]);
    if (cs.length && !m.categories.some((x) => cs.includes(x))) return false;
    if (query && !(m.title + " " + m.description).toLowerCase().includes(query)) return false;
    return true;
  });
  feed = [...feed].sort((a, b) => (a.date < b.date ? 1 : -1));
  if (sort === "old") feed.reverse();

  const activeChips = [];
  if (fMat.bm) activeChips.push({ t: "📌 В закладках", clear: () => setFMat((p) => ({ ...p, bm: false })) });
  if (fMat.done) activeChips.push({ t: "✓ Изучен", clear: () => setFMat((p) => ({ ...p, done: false })) });
  if (fMat.new) activeChips.push({ t: "○ Не изучен", clear: () => setFMat((p) => ({ ...p, new: false })) });
  Object.keys(fFmt).forEach((f) => fFmt[f] && activeChips.push({ t: formats[f] + " " + f, clear: () => setFFmt((p) => ({ ...p, [f]: false })) }));
  Object.keys(fCat).forEach((c) => fCat[c] && activeChips.push({ t: categories[c].emoji + " " + c, clear: () => setFCat((p) => ({ ...p, [c]: false })) }));
  const hasFilters = activeChips.length > 0 || sort !== "new";
  const resetAll = () => { setFMat({}); setFFmt({}); setFCat({}); setSort("new"); setQ(""); };

  // --- Карточка материала в списке ---
  const MaterialCard = (m) => {
    const tags = [fmtTag(m.format, formats), ...m.categories.map((c) => catTag(c, categories))];
    const on = bookmarks[m.id];
    return (
      <div key={m.id} onClick={() => openMaterial(m.id)}
        style={{ position: "relative", background: "#141C2D", border: "1px solid rgba(255,255,255,0.05)", borderRadius: 18, padding: "14px 44px 14px 14px", cursor: "pointer" }}>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 9 }}>{tags.map((t, i) => <Pill key={i} tag={t} />)}</div>
        <div style={{ fontSize: 16.5, fontWeight: 700, letterSpacing: "-0.01em", lineHeight: 1.25 }}>{m.title}</div>
        <div style={{ marginTop: 5, fontSize: 13, lineHeight: 1.4, color: "#8B95AC", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{m.description}</div>
        <button onClick={(e) => { e.stopPropagation(); toggle("bookmarks", m.id, setBookmarks); }}
          style={{ position: "absolute", top: 10, right: 8, background: "none", border: "none", padding: 6, cursor: "pointer" }}>
          <IcBookmark fill={on ? ACCENT : "none"} stroke={on ? ACCENT : "#7C87A0"} />
        </button>
      </div>
    );
  };

  const CollectionCard = (col, big) => (
    <div key={col.id} onClick={() => openCollection(col)}
      style={{ position: "relative", flex: big ? undefined : "none", width: big ? undefined : 132, height: big ? undefined : 172,
        aspectRatio: big ? "0.82" : undefined, borderRadius: big ? 18 : 16, overflow: "hidden", background: cover(col.hues),
        cursor: "pointer", boxShadow: "0 8px 20px rgba(0,0,0,0.35)" }}>
      <div style={{ position: "absolute", top: 8, right: 8, minWidth: 24, height: 24, borderRadius: 12, background: "rgba(8,12,20,0.5)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11.5, fontWeight: 700, padding: "0 7px" }}>{col.count}</div>
      <div style={{ position: "absolute", top: big ? 40 : 44, left: 0, right: 0, textAlign: "center", fontSize: big ? 50 : 40, filter: "drop-shadow(0 6px 12px rgba(0,0,0,0.4))" }}>{col.emoji}</div>
      <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, padding: "26px 10px 10px", background: "linear-gradient(transparent, rgba(5,8,14,0.78))", fontSize: 13, fontWeight: 700, lineHeight: 1.25 }}>{col.title}</div>
    </div>
  );

  const neutral = (on) => on ? { bg: "rgba(89,164,255,0.16)", fg: "#8CC0FF", bd: "rgba(89,164,255,0.45)" } : { bg: "#161E30", fg: "#C6CEDE", bd: "transparent" };
  const ChipBtn = ({ t, on, click, style }) => (
    <button onClick={click} style={{ borderRadius: 999, padding: "8px 13px", fontSize: 13, fontWeight: 600, whiteSpace: "nowrap", lineHeight: 1.2, fontFamily: "inherit", cursor: "pointer", ...(style || neutral(on)) }}>{t}</button>
  );

  const OB = [
    { t: "Используйте теги", d: "Фильтруйте материалы по формату и темам.", top: "212px", ax: "32px" },
    { t: "Сортируйте", d: "По дате публикации — от новых к старым и наоборот.", top: "168px", ax: "300px" },
    { t: "Ищите", d: "Умный поиск по всей базе материалов.", top: "168px", ax: "80px" },
    { t: "Изучайте", d: "Статьи, видео, стримы и курсы — всё в одном месте.", top: "492px", ax: "56px" },
  ];
  const obCur = ob >= 0 ? OB[ob] : null;

  const sectionLabel = (t) => <div style={{ marginTop: 22, fontSize: 13, fontWeight: 700, color: "#7C87A0", textTransform: "uppercase", letterSpacing: "0.06em" }}>{t}</div>;

  // ========================= РЕНДЕР =========================
  return (
    <div style={{ minHeight: "100vh", display: "flex", justifyContent: "center", background: "radial-gradient(80% 60% at 50% 0%, #0B1220, #06080F)" }}>
      <div style={{ position: "relative", width: "100%", maxWidth: 440, minHeight: "100vh", background: "#0C111D", overflow: "hidden" }}>

        {/* Фоновый паттерн */}
        <div style={{ position: "absolute", inset: 0, backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='180' height='180'%3E%3Cg fill='none' stroke='%23AAB8D9' stroke-opacity='0.05' stroke-width='1.4'%3E%3Ccircle cx='34' cy='38' r='9'/%3E%3Crect x='104' y='24' width='20' height='20' rx='6'/%3E%3Ccircle cx='142' cy='124' r='7'/%3E%3Crect x='30' y='116' width='16' height='16' rx='8'/%3E%3C/g%3E%3C/svg%3E\")", pointerEvents: "none" }} />

        {/* Хедер */}
        <div style={{ position: "relative", zIndex: 30, height: 48, marginTop: 44, display: "flex", alignItems: "center", padding: "0 14px" }}>
          <button onClick={closeApp} style={{ background: "none", border: "none", color: ACCENT, fontSize: 15, fontFamily: "inherit", padding: 0, cursor: "pointer", minWidth: 64, textAlign: "left" }}>Закрыть</button>
          <div style={{ flex: 1, textAlign: "center" }}>
            <div style={{ fontSize: 15, fontWeight: 600, lineHeight: 1.15 }}>База знаний</div>
            <div style={{ fontSize: 10.5, color: "#7C87A0" }}>мини-приложение</div>
          </div>
          <div style={{ minWidth: 64, display: "flex", justifyContent: "flex-end" }}>
            <button onClick={() => setMenuOpen((v) => !v)} style={{ width: 32, height: 32, borderRadius: 16, background: "rgba(255,255,255,0.07)", border: "none", color: "#C6CEDE", fontSize: 18, cursor: "pointer" }}>⋯</button>
          </div>
        </div>

        {/* ЛЕНТА */}
        {screen !== "intro" && screen === "feed" && (
          <div style={{ position: "absolute", top: 92, bottom: 0, left: 0, right: 0, overflowY: "auto", padding: "8px 16px 32px", animation: "screenIn 0.28s ease" }}>
            <div style={{ display: "flex", gap: 8 }}>
              <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 8, background: "#161E30", borderRadius: 12, height: 42, padding: "0 12px" }}>
                <IcSearch />
                <input placeholder="Поиск" value={q} onChange={(e) => setQ(e.target.value)} style={{ flex: 1, background: "none", border: "none", color: "#EDF1F9", fontSize: 15, fontFamily: "inherit", minWidth: 0 }} />
              </div>
              <button onClick={() => go("filter")} style={{ position: "relative", display: "flex", alignItems: "center", gap: 7, background: "#161E30", border: "none", borderRadius: 12, height: 42, padding: "0 14px", color: "#C6CEDE", fontSize: 14, fontWeight: 600, fontFamily: "inherit", cursor: "pointer" }}>
                Фильтр
                {hasFilters && <span style={{ position: "absolute", top: 8, right: 8, width: 7, height: 7, borderRadius: 4, background: ACCENT }} />}
              </button>
            </div>

            {activeChips.length > 0 && (
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 10 }}>
                {activeChips.map((ch, i) => (
                  <button key={i} onClick={ch.clear} style={{ display: "flex", alignItems: "center", gap: 6, background: "rgba(89,164,255,0.16)", border: "1px solid rgba(89,164,255,0.35)", borderRadius: 999, padding: "7px 12px", color: "#8CC0FF", fontSize: 13, fontWeight: 600, whiteSpace: "nowrap", fontFamily: "inherit", cursor: "pointer" }}>{ch.t}<span style={{ fontSize: 14, opacity: 0.8 }}>×</span></button>
                ))}
              </div>
            )}

            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginTop: 20 }}>
              <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: "-0.02em" }}>Коллекции</div>
              <button onClick={() => go("collections")} style={{ background: "none", border: "none", color: ACCENT, fontSize: 14, fontWeight: 600, fontFamily: "inherit", cursor: "pointer", padding: 0 }}>Все ›</button>
            </div>
            <div style={{ display: "flex", gap: 10, overflowX: "auto", margin: "12px -16px 0", padding: "0 16px 4px" }}>
              {collections.slice(0, 5).map((c) => CollectionCard(c, false))}
            </div>

            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginTop: 22, marginBottom: 12 }}>
              <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: "-0.02em" }}>Материалы</div>
              <div style={{ fontSize: 12, color: "#7C87A0" }}>{sort === "new" ? "От новых к старым" : "От старых к новым"}</div>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>{feed.map(MaterialCard)}</div>
            {feed.length === 0 && (
              <div style={{ textAlign: "center", padding: "36px 20px", color: "#7C87A0" }}>
                <div style={{ fontSize: 30 }}>🔍</div>
                <div style={{ marginTop: 8, fontSize: 15, fontWeight: 600, color: "#C6CEDE" }}>Ничего не найдено</div>
                <div style={{ marginTop: 4, fontSize: 13 }}>Попробуйте изменить фильтры или запрос</div>
                <button onClick={resetAll} style={{ marginTop: 14, background: "rgba(89,164,255,0.14)", border: "none", borderRadius: 12, padding: "10px 18px", color: ACCENT, fontSize: 14, fontWeight: 600, fontFamily: "inherit", cursor: "pointer" }}>Сбросить фильтры</button>
              </div>
            )}
          </div>
        )}

        {/* ФИЛЬТР */}
        {screen === "filter" && (
          <div style={{ position: "absolute", top: 92, bottom: 0, left: 0, right: 0, background: "#0C111D", animation: "screenIn 0.28s ease", zIndex: 20 }}>
            <div style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 88, overflowY: "auto", padding: "10px 16px 20px" }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em" }}>Фильтры</div>
                <button onClick={back} style={{ width: 32, height: 32, borderRadius: 16, background: "rgba(255,255,255,0.07)", border: "none", color: "#C6CEDE", fontSize: 15, cursor: "pointer" }}>✕</button>
              </div>
              {sectionLabel("Сортировка")}
              <div style={{ display: "flex", background: "#161E30", borderRadius: 12, padding: 3, marginTop: 10 }}>
                {[["new", "От новых к старым"], ["old", "От старых к новым"]].map(([k, t]) => (
                  <button key={k} onClick={() => setSort(k)} style={{ flex: 1, border: "none", borderRadius: 9, padding: "9px 4px", fontSize: 13, fontWeight: 600, fontFamily: "inherit", cursor: "pointer", background: sort === k ? "#2A3550" : "transparent", color: sort === k ? "#EDF1F9" : "#7C87A0" }}>{t}</button>
                ))}
              </div>
              {sectionLabel("Материал")}
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 10 }}>
                {[["bm", "📌 В закладках"], ["done", "✓ Изучен"], ["new", "○ Не изучен"]].map(([k, t]) => (
                  <ChipBtn key={k} t={t} on={!!fMat[k]} click={() => setFMat((p) => ({ ...p, [k]: !p[k] }))} />
                ))}
              </div>
              {sectionLabel("Форматы")}
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 10 }}>
                {Object.keys(formats).map((f) => (
                  <ChipBtn key={f} t={formats[f] + " " + f} on={!!fFmt[f]} click={() => setFFmt((p) => ({ ...p, [f]: !p[f] }))} />
                ))}
              </div>
              {sectionLabel("Категории")}
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 10 }}>
                {Object.keys(categories).map((c) => {
                  const h = categories[c].hue, on = !!fCat[c];
                  return <ChipBtn key={c} t={categories[c].emoji + " " + c} click={() => setFCat((p) => ({ ...p, [c]: !p[c] }))}
                    style={{ background: on ? `oklch(0.72 0.17 ${h} / 0.28)` : `oklch(0.72 0.17 ${h} / 0.1)`, color: `oklch(0.84 0.12 ${h})`, border: `1px solid ${on ? `oklch(0.72 0.17 ${h} / 0.6)` : "transparent"}` }} />;
                })}
              </div>
            </div>
            <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, display: "flex", gap: 10, padding: "14px 16px 26px", background: "linear-gradient(transparent, #0C111D 40%)" }}>
              <button onClick={resetAll} style={{ flex: 1, background: "#161E30", border: "none", borderRadius: 14, padding: 14, color: "#C6CEDE", fontSize: 15, fontWeight: 600, fontFamily: "inherit", cursor: "pointer" }}>Сбросить</button>
              <button onClick={back} style={{ flex: 1.5, background: ACCENT, border: "none", borderRadius: 14, padding: 14, color: "#071120", fontSize: 15, fontWeight: 700, fontFamily: "inherit", cursor: "pointer" }}>Применить</button>
            </div>
          </div>
        )}

        {/* СЕТКА КОЛЛЕКЦИЙ */}
        {screen === "collections" && (
          <div style={{ position: "absolute", top: 92, bottom: 0, left: 0, right: 0, overflowY: "auto", padding: "8px 16px 32px", animation: "screenIn 0.28s ease", background: "#0C111D", zIndex: 15 }}>
            <button onClick={back} style={{ display: "flex", alignItems: "center", gap: 2, background: "none", border: "none", color: ACCENT, fontSize: 15, fontWeight: 600, fontFamily: "inherit", cursor: "pointer", padding: "4px 0" }}><IcBack />Назад</button>
            <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em", marginTop: 8 }}>Коллекции</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 16 }}>{collections.map((c) => CollectionCard(c, true))}</div>
          </div>
        )}

        {/* ОДНА КОЛЛЕКЦИЯ */}
        {screen === "collection" && curCol && (
          <div style={{ position: "absolute", top: 92, bottom: 0, left: 0, right: 0, overflowY: "auto", padding: "8px 16px 32px", animation: "screenIn 0.28s ease", background: "#0C111D", zIndex: 15 }}>
            <button onClick={back} style={{ display: "flex", alignItems: "center", gap: 2, background: "none", border: "none", color: ACCENT, fontSize: 15, fontWeight: 600, fontFamily: "inherit", cursor: "pointer", padding: "4px 0" }}><IcBack />Назад</button>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 10 }}>
              <div style={{ width: 56, height: 56, borderRadius: 16, background: cover(curCol.hues), display: "flex", alignItems: "center", justifyContent: "center", fontSize: 28, flex: "none" }}>{curCol.emoji}</div>
              <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.15 }}>{curCol.title}</div>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 18 }}>
              {materials.filter((m) => m.collection === curCol.id).map(MaterialCard)}
            </div>
          </div>
        )}

        {/* МАТЕРИАЛ */}
        {screen === "material" && curMat && (
          <div style={{ position: "absolute", top: 92, bottom: 0, left: 0, right: 0, overflowY: "auto", padding: "8px 16px 32px", animation: "screenIn 0.28s ease", background: "#0C111D", zIndex: 15 }}>
            <button onClick={back} style={{ display: "flex", alignItems: "center", gap: 2, background: "none", border: "none", color: ACCENT, fontSize: 15, fontWeight: 600, fontFamily: "inherit", cursor: "pointer", padding: "4px 0" }}><IcBack />Назад</button>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 10 }}>
              {[fmtTag(curMat.format, formats), ...curMat.categories.map((c) => catTag(c, categories))].map((t, i) => <Pill key={i} tag={t} size={12} />)}
            </div>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 10, marginTop: 12 }}>
              <div style={{ flex: 1, fontSize: 23, fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.2 }}>{curMat.title}</div>
              <button onClick={() => showToast("Ссылка скопирована")} style={{ flex: "none", width: 34, height: 34, borderRadius: 17, background: "rgba(255,255,255,0.07)", border: "none", cursor: "pointer" }}>🔗</button>
              <button onClick={() => toggle("bookmarks", curMat.id, setBookmarks)} style={{ flex: "none", width: 34, height: 34, borderRadius: 17, background: "rgba(255,255,255,0.07)", border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <IcBookmark size={16} fill={bookmarks[curMat.id] ? ACCENT : "none"} stroke={bookmarks[curMat.id] ? ACCENT : "#C6CEDE"} />
              </button>
            </div>

            {curMat.timecodes && curMat.timecodes.length > 0 && (
              <>
                <div style={{ position: "relative", marginTop: 14, aspectRatio: "16/9", borderRadius: 18, overflow: "hidden",
                  background: "radial-gradient(120% 130% at 18% 0%, oklch(0.55 0.14 210 / 0.9), transparent 55%), linear-gradient(150deg, oklch(0.42 0.15 235), oklch(0.28 0.13 275))", boxShadow: "0 12px 28px rgba(0,0,0,0.4)" }}>
                  <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
                    <div style={{ width: 58, height: 58, borderRadius: 29, background: "rgba(255,255,255,0.16)", backdropFilter: "blur(6px)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                      <svg width="22" height="22" viewBox="0 0 24 24" fill="#fff"><path d="M8 5v14l11-7z" /></svg>
                    </div>
                  </div>
                  <div style={{ position: "absolute", left: 10, bottom: 10, background: "rgba(8,12,20,0.55)", borderRadius: 8, padding: "4px 8px", fontSize: 11.5, fontWeight: 600, color: "#C6CEDE" }}>{activeTc >= 0 ? curMat.timecodes[activeTc][0] : curMat.timecodes[0][0]}</div>
                </div>
                {sectionLabel("Содержание")}
                <div style={{ marginTop: 6 }}>
                  {curMat.timecodes.map((tc, i) => (
                    <div key={i} onClick={() => setActiveTc(i)} style={{ display: "flex", gap: 12, alignItems: "baseline", padding: "10px 8px", borderRadius: 10, cursor: "pointer", background: activeTc === i ? "rgba(89,164,255,0.1)" : "transparent", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                      <span style={{ fontSize: 13, fontWeight: 700, color: ACCENT, minWidth: 42 }}>{tc[0]}</span>
                      <span style={{ fontSize: 14.5, color: activeTc === i ? "#EDF1F9" : "#B7C0D4" }}>{tc[1]}</span>
                    </div>
                  ))}
                </div>
              </>
            )}

            <div style={{ marginTop: 18 }}><Markdown text={curMat.body} /></div>

            <div style={{ display: "flex", gap: 10, alignItems: "center", marginTop: 24 }}>
              {(() => { const done = studied[curMat.id]; return (
                <button onClick={() => toggle("studied", curMat.id, setStudied)} style={{ flex: 1, border: "none", borderRadius: 14, padding: 14, fontSize: 15, fontWeight: 700, fontFamily: "inherit", cursor: "pointer", background: done ? "rgba(96,208,150,0.18)" : ACCENT, color: done ? "#6FD9A4" : "#071120" }}>{done ? "✓ Изучено" : "Отметить изученным"}</button>
              ); })()}
              <button onClick={() => showToast("Ссылка скопирована")} title="Поделиться" style={{ flex: "none", width: 48, height: 48, borderRadius: 24, background: "#161E30", border: "none", cursor: "pointer" }}>✈️</button>
              <button onClick={() => toggle("bookmarks", curMat.id, setBookmarks)} style={{ flex: "none", width: 48, height: 48, borderRadius: 24, background: "#161E30", border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <IcBookmark size={18} fill={bookmarks[curMat.id] ? ACCENT : "none"} stroke={bookmarks[curMat.id] ? ACCENT : "#C6CEDE"} />
              </button>
            </div>
          </div>
        )}

        {/* КУРС */}
        {screen === "course" && curCol && courses[curCol.id] && (() => {
          const course = courses[curCol.id];
          const allItems = course.sections.flatMap((s) => s.items);
          const done = allItems.filter((i) => lessons[i.id]).length;
          const pct = Math.round((done / allItems.length) * 100);
          return (
            <div style={{ position: "absolute", top: 92, bottom: 0, left: 0, right: 0, overflowY: "auto", padding: "8px 16px 32px", animation: "screenIn 0.28s ease", background: "#0C111D", zIndex: 15 }}>
              <button onClick={back} style={{ display: "flex", alignItems: "center", gap: 2, background: "none", border: "none", color: ACCENT, fontSize: 15, fontWeight: 600, fontFamily: "inherit", cursor: "pointer", padding: "4px 0" }}><IcBack />Назад</button>
              <div style={{ position: "relative", marginTop: 10, height: 150, borderRadius: 20, overflow: "hidden", background: cover(curCol.hues), boxShadow: "0 12px 28px rgba(0,0,0,0.4)" }}>
                <div style={{ position: "absolute", top: 12, left: 12, borderRadius: 999, padding: "5px 10px", fontSize: 12, fontWeight: 600, background: "rgba(8,12,20,0.5)", color: "#EDF1F9" }}>📖 Курс</div>
                <div style={{ position: "absolute", right: 16, bottom: 8, fontSize: 62, filter: "drop-shadow(0 8px 14px rgba(0,0,0,0.4))" }}>{curCol.emoji}</div>
              </div>
              <div style={{ marginTop: 14, fontSize: 23, fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.2 }}>{curCol.title}</div>
              <div style={{ marginTop: 8, fontSize: 14, lineHeight: 1.45, color: "#8B95AC" }}>{course.subtitle}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 16 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: "#8CC0FF", whiteSpace: "nowrap" }}>{pct}% изучено</div>
                <div style={{ flex: 1, height: 6, borderRadius: 3, background: "#1A2336", overflow: "hidden" }}><div style={{ height: "100%", borderRadius: 3, background: "linear-gradient(90deg,#59A4FF,#7DD3C8)", transition: "width 0.35s ease", width: pct + "%" }} /></div>
              </div>
              <div style={{ marginTop: 20 }}>
                {course.sections.map((sec, si) => (
                  <div key={si} style={{ marginBottom: 18 }}>
                    <div style={{ fontSize: 16, fontWeight: 700 }}>{sec.title}</div>
                    {sec.subtitle && <div style={{ fontSize: 12.5, color: "#7C87A0", marginTop: 2, marginBottom: 10 }}>{sec.subtitle}</div>}
                    <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: sec.subtitle ? 0 : 10 }}>
                      {sec.items.map((les) => {
                        const on = !!lessons[les.id];
                        return (
                          <div key={les.id} style={{ display: "flex", alignItems: "center", gap: 12, background: "#141C2D", border: "1px solid rgba(255,255,255,0.05)", borderRadius: 14, padding: "12px 14px" }}>
                            <div onClick={() => toggle("lessons", les.id, setLessons)} style={{ flex: "none", width: 24, height: 24, borderRadius: 12, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 800, cursor: "pointer", border: `2px solid ${on ? ACCENT : "#3A4560"}`, background: on ? ACCENT : "transparent", color: "#071120" }}>{on ? "✓" : ""}</div>
                            <div style={{ flex: 1, fontSize: 14.5, fontWeight: 500, color: on ? "#8B95AC" : "#EDF1F9" }}>{les.title}</div>
                            {les.material && <button onClick={() => openMaterial(les.material)} style={{ background: "none", border: "none", color: ACCENT, fontSize: 13, fontWeight: 600, fontFamily: "inherit", cursor: "pointer" }}>Открыть ›</button>}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          );
        })()}

        {/* INTRO */}
        {screen === "intro" && (
          <div style={{ position: "absolute", inset: 0, zIndex: 40, background: "radial-gradient(90% 55% at 50% 0%, #131C31, #0A0E19 70%)", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "32px 28px 48px", textAlign: "center", animation: "fadeIn 0.4s ease" }}>
            <div style={{ width: 76, height: 76, borderRadius: 22, background: "linear-gradient(150deg, oklch(0.52 0.18 255), oklch(0.36 0.17 295))", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 36, boxShadow: "0 16px 40px rgba(40,80,180,0.35)" }}>📚</div>
            <div style={{ marginTop: 26, fontSize: 33, fontWeight: 800, letterSpacing: "-0.03em", lineHeight: 1.1 }}>Материалы базы</div>
            <div style={{ marginTop: 12, fontSize: 15, lineHeight: 1.5, color: "#8B95AC", maxWidth: 280 }}>Новый формат комьюнити — все материалы в одном месте.</div>
            <button onClick={() => { setScreen("feed"); setStack([]); setOb(0); markOnboarded(); }} style={{ marginTop: 36, width: "100%", maxWidth: 300, background: ACCENT, border: "none", borderRadius: 16, padding: 16, color: "#071120", fontSize: 16, fontWeight: 700, fontFamily: "inherit", cursor: "pointer", boxShadow: "0 12px 30px rgba(89,164,255,0.3)" }}>Открыть приложение</button>
          </div>
        )}

        {/* ОНБОРДИНГ */}
        {obCur && (
          <div style={{ position: "absolute", inset: 0, zIndex: 50, background: "rgba(4,7,13,0.62)", backdropFilter: "blur(2px)", animation: "fadeIn 0.25s ease" }}>
            <div style={{ position: "absolute", left: 20, right: 20, background: "#F3F6FC", color: "#10151F", borderRadius: 16, padding: 16, boxShadow: "0 20px 50px rgba(0,0,0,0.5)", top: obCur.top }}>
              <div style={{ position: "absolute", top: -6, width: 12, height: 12, background: "#F3F6FC", transform: "rotate(45deg)", borderRadius: 2, left: obCur.ax }} />
              <div style={{ fontSize: 16, fontWeight: 800, letterSpacing: "-0.01em" }}>{obCur.t}</div>
              <div style={{ marginTop: 5, fontSize: 13.5, lineHeight: 1.45, color: "#4A5468" }}>{obCur.d}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 14 }}>
                <div style={{ display: "flex", gap: 5, flex: 1 }}>{[0, 1, 2, 3].map((i) => <div key={i} style={{ width: 6, height: 6, borderRadius: 3, background: i === ob ? "#2264E6" : "#C3CCDC" }} />)}</div>
                <button onClick={() => setOb(-1)} style={{ background: "none", border: "none", color: "#6B7688", fontSize: 13.5, fontWeight: 600, fontFamily: "inherit", cursor: "pointer", padding: "8px 6px" }}>Пропустить</button>
                <button onClick={() => setOb((p) => (p < 3 ? p + 1 : -1))} style={{ background: "#2264E6", border: "none", borderRadius: 10, padding: "9px 16px", color: "#fff", fontSize: 13.5, fontWeight: 700, fontFamily: "inherit", cursor: "pointer" }}>{ob === 3 ? "Понятно" : "Далее"}</button>
              </div>
            </div>
          </div>
        )}

        {/* МЕНЮ */}
        {menuOpen && (
          <div style={{ position: "absolute", inset: 0, zIndex: 60 }} onClick={() => setMenuOpen(false)}>
            <div style={{ position: "absolute", top: 94, right: 12, width: 252, background: "rgba(26,33,50,0.98)", border: "1px solid rgba(255,255,255,0.07)", borderRadius: 14, boxShadow: "0 16px 50px rgba(0,0,0,0.55)", overflow: "hidden", animation: "popIn 0.18s ease", transformOrigin: "top right" }}>
              {[
                { t: "Поделиться", icon: "↗", click: () => { setMenuOpen(false); showToast("Ссылка скопирована"); } },
                { t: "Перезагрузить страницу", icon: "⟳", click: () => location.reload() },
                { t: "Добавить на главный экран", icon: "⊞", click: () => setMenuOpen(false) },
                { t: "Условия использования", icon: "§", click: () => setMenuOpen(false) },
                { t: "Политика конфиденциальности", icon: "ⓘ", click: () => setMenuOpen(false) },
              ].map((mi, i) => (
                <div key={i} onClick={mi.click} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 14px", fontSize: 14, fontWeight: 500, cursor: "pointer", borderTop: i === 0 ? "none" : "1px solid rgba(255,255,255,0.05)", color: "#EDF1F9" }}>{mi.t}<span style={{ color: "#7C87A0", fontSize: 15 }}>{mi.icon}</span></div>
              ))}
            </div>
          </div>
        )}

        {/* TOAST */}
        {toast && (
          <div style={{ position: "fixed", bottom: 40, left: "50%", transform: "translateX(-50%)", zIndex: 70, background: "rgba(26,33,50,0.97)", border: "1px solid rgba(255,255,255,0.08)", borderRadius: 999, padding: "9px 16px", fontSize: 13, fontWeight: 600, color: "#EDF1F9", boxShadow: "0 10px 30px rgba(0,0,0,0.5)", whiteSpace: "nowrap", animation: "toastIn 0.25s ease" }}>{toast}</div>
        )}

      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
