/* ============================================================
   screens-detail.jsx — Material detail + Add material
   ============================================================ */
const React = window.React;
const { useState } = React;
const Icon = window.Icon;
const A = window.PlannerActions;

function MaterialScreen({ state, id, nav }) {
  const Cmp = window;
  const m = state.materials.find((x) => x.id === id);
  const [qOpen, setQOpen] = useState(false);
  const [qText, setQText] = useState("");
  const [qPage, setQPage] = useState("");
  const [qNote, setQNote] = useState("");
  if (!m) return <div className="page"><div className="empty">Материал не найден.</div></div>;

  const linked = m.links.map((lid) => window.PlannerLookup.entity(state, lid)).filter(Boolean);
  // back-links: who references this material
  const backlinks = [
    ...state.materials.filter((x) => x.links.includes(m.id)).map((x) => ({ ...x, _kind: "material" })),
    ...state.courses.filter((x) => x.links.includes(m.id)).map((x) => ({ ...x, _kind: "course" })),
    ...state.notes.filter((x) => x.links.includes(m.id)).map((x) => ({ ...x, _kind: "note" })),
  ].filter((x) => !m.links.includes(x.id));
  const kick = { fiction: "Художественная литература", science: "Научная литература", video: "Видео / лекция" }[m.type];
  const pct = Math.round((m.progress.current / m.progress.total) * 100);

  const saveQuote = () => {
    if (!qText.trim()) return;
    A.addQuote(m.id, { text: qText.trim(), page: Number(qPage) || 0, note: qNote.trim() });
    setQText(""); setQPage(""); setQNote(""); setQOpen(false);
  };

  return (
    <div className="page page--wide screen-enter">
      <div className="row-3" style={{ marginBottom: "var(--s-5)" }}>
        <span className="task__link" onClick={() => nav({ screen: "library" })}><Icon name="back" size={14} />Библиотека</span>
      </div>

      <div className="cols cols--detail">
        {/* LEFT column: cover + stats */}
        <div className="stack-4">
          <Cmp.Cover m={m} showBar={false} />
          <Cmp.GButton variant="ghost" style={{ fontSize: "var(--t-small)" }}
            onClick={() => { const inp = document.createElement("input"); inp.type = "file"; inp.accept = "image/*"; inp.onchange = (ev) => { const file = ev.target.files[0]; if (!file) return; const r = new FileReader(); r.onload = (re) => A.setMaterialCoverImg(m.id, re.target.result); r.readAsDataURL(file); }; inp.click(); }}>
            Загрузить обложку
          </Cmp.GButton>
          <div className="task" style={{ display: "block", padding: "var(--s-5)" }}>
            <div className="e-label" style={{ marginBottom: 8 }}>Прогресс</div>
            <div className="row-3" style={{ justifyContent: "space-between", marginBottom: 8 }}>
              <span className="ring-total" style={{ fontSize: 34 }}>{pct}%</span>
              <span className="meter-num">{m.progress.current} / {m.progress.total} {m.progress.unit}</span>
            </div>
            <Cmp.ProgressBar value={m.progress.current} total={m.progress.total} />
            <div className="row-2" style={{ marginTop: "var(--s-4)", gap: 8 }}>
              <Cmp.GButton variant="ghost" onClick={() => A.updateProgress(m.id, m.progress.current - stepFor(m))}>−{stepFor(m)}</Cmp.GButton>
              <Cmp.GButton variant="ink" icon="arrowUp" onClick={() => A.updateProgress(m.id, m.progress.current + stepFor(m))}>+{stepFor(m)} {m.progress.unit}</Cmp.GButton>
            </div>
          </div>

          <div className="task" style={{ display: "block", padding: "var(--s-5)" }}>
            <div className="row-3" style={{ justifyContent: "space-between", marginBottom: 12 }}>
              <span className="e-label">Статус</span><Cmp.StatusBadge status={m.status} />
            </div>
            <div className="row-3" style={{ justifyContent: "space-between", marginBottom: 12 }}>
              <span className="e-label">Моя оценка</span><Cmp.RatingPips value={m.rating} onChange={(v) => A.setRating(m.id, v)} />
            </div>
            <div className="row-2 wrap gap-2">{m.tags.map((tg) => <Cmp.GTag key={tg}>{tg}</Cmp.GTag>)}</div>
          </div>

          <Cmp.TimeBlock log={m.timeLog} todayIdx={state.todayIdx} timer={state.timer} kind="material" id={m.id} label="Время на чтение"
            onStart={(k, i) => A.startTimer(k, i)} onStop={() => A.stopTimer()} onAdd={(sec) => A.logTime("material", m.id, sec)} />
        </div>

        {/* RIGHT column: title, note, quotes, connections */}
        <div className="stack-5">
          <div>
            <div className="eyebrow-mono" style={{ marginBottom: 8 }}>{kick}</div>
            <h1 className="page-title" style={{ marginBottom: 8 }}>{m.title}</h1>
            <div className="row-3" style={{ gap: 14 }}>
              <span style={{ fontSize: "var(--t-body-lg)", color: "var(--text-secondary)" }}>{m.author}</span>
              <Cmp.GButton variant="signal" icon="plus" style={{ marginLeft: "auto" }} onClick={() => nav({ screen: "today" })}>В задачи на сегодня</Cmp.GButton>
            </div>
          </div>

          {m.note && <div className="quote" style={{ borderLeftColor: "var(--ink-100)" }}><div className="note-card__hand">{m.note}</div></div>}

          {/* Quotes */}
          <div>
            <Cmp.SectionRule kicker="Выписки" right={<span className="task__link" onClick={() => setQOpen((v) => !v)}><Icon name="plus" size={13} />Цитата</span>}>Цитаты и заметки</Cmp.SectionRule>
            {qOpen && (
              <div className="task" style={{ display: "block", padding: "var(--s-4)", marginBottom: 12 }}>
                <textarea value={qText} onChange={(e) => setQText(e.target.value)} placeholder="Текст цитаты…" rows={2}
                  style={{ width: "100%", border: "1px solid var(--ink-100)", padding: 8, fontFamily: "var(--font-slab)", fontSize: "var(--t-body)", background: "var(--paper-00)", resize: "vertical" }} />
                <div className="row-3" style={{ marginTop: 8, gap: 10 }}>
                  <input value={qPage} onChange={(e) => setQPage(e.target.value)} placeholder={"№ " + m.progress.unit}
                    style={{ width: 90, border: "1px solid var(--ink-100)", padding: "6px 8px", fontFamily: "var(--font-mono)", background: "var(--paper-00)" }} />
                  <input value={qNote} onChange={(e) => setQNote(e.target.value)} placeholder="Моя заметка (необязательно)"
                    style={{ flex: 1, border: "1px solid var(--ink-100)", padding: "6px 8px", fontFamily: "var(--font-slab)", background: "var(--paper-00)" }} />
                  <Cmp.GButton variant="signal" onClick={saveQuote}>Сохранить</Cmp.GButton>
                </div>
              </div>
            )}
            <div className="stack-4">
              {m.quotes.length === 0 && !qOpen && <div className="empty" style={{ padding: "var(--s-5)" }}>Пока нет выписок. Добавьте первую цитату.</div>}
              {m.quotes.map((q) => (
                <div className="quote" key={q.id}>
                  <div className="quote__text">«{q.text}»</div>
                  <div className="quote__meta">{m.progress.unit} {q.page}{q.note ? "  ·  " : ""}{q.note && <span className="hand" style={{ fontSize: "1.05rem", color: "var(--ink-100)" }}>{q.note}</span>}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Connections */}
          <div>
            <Cmp.SectionRule kicker="Связи">Связано с</Cmp.SectionRule>
            <div className="row-2 wrap gap-3">
              {linked.length === 0 && backlinks.length === 0 && <span className="muted">Нет связей. Откройте граф, чтобы связать материалы.</span>}
              {linked.map((e) => <Cmp.LinkChip key={e.id} entity={e} onClick={() => navTo(nav, e)} />)}
            </div>
            {backlinks.length > 0 && (
              <>
                <div className="e-label" style={{ margin: "16px 0 8px" }}>↩ Упоминается в</div>
                <div className="row-2 wrap gap-3">
                  {backlinks.map((e) => <Cmp.LinkChip key={e.id} entity={e} onClick={() => navTo(nav, e)} />)}
                </div>
              </>
            )}
            <div style={{ marginTop: 16 }}>
              <Cmp.GButton variant="ghost" icon="graph" onClick={() => nav({ screen: "graph", focus: m.id })}>Открыть в графе связей</Cmp.GButton>
            </div>
          </div>

          <div style={{ marginTop: "var(--s-4)" }}>
            <Cmp.GButton variant="ghost" icon="close" onClick={() => { if (confirm("Удалить «" + m.title + "» из библиотеки?")) { A.removeMaterial(m.id); nav({ screen: "library" }); } }}
              style={{ color: "var(--signal)", fontSize: "var(--t-small)" }}>Удалить из библиотеки</Cmp.GButton>
          </div>
        </div>
      </div>
    </div>
  );
}

function navTo(nav, e) {
  if (e._kind === "course") nav({ screen: "course", id: e.id });
  else if (e._kind === "note") nav({ screen: "notes", id: e.id });
  else nav({ screen: "material", id: e.id });
}
function stepFor(m) { return m.type === "video" ? (m.progress.unit === "мин" ? 5 : 1) : 10; }

/* ---- Add material -------------------------------------------- */
function AddMaterialScreen({ nav }) {
  const Cmp = window;
  const [type, setType] = useState("fiction");
  const [title, setTitle] = useState("");
  const [author, setAuthor] = useState("");
  const [total, setTotal] = useState(300);
  const [colorKey, setColorKey] = useState("oxblood");
  const [coverImg, setCoverImg] = useState(null);
  const colorKeys = Object.keys(window.CV);

  const submit = () => {
    if (!title.trim()) return;
    const unit = type === "video" ? "мин" : "стр.";
    const mat = { type, title: title.trim(), author: author.trim() || "—", total: Number(total) || 100, unit, cover: window.CV[colorKey] };
    if (coverImg) mat.coverImg = coverImg;
    A.addMaterial(mat);
    nav({ screen: "library" });
  };

  const pickImage = () => {
    const inp = document.createElement("input");
    inp.type = "file"; inp.accept = "image/*";
    inp.onchange = (ev) => {
      const file = ev.target.files[0]; if (!file) return;
      const r = new FileReader();
      r.onload = (re) => setCoverImg(re.target.result);
      r.readAsDataURL(file);
    };
    inp.click();
  };

  const preview = { type, title: title || "Название материала", author, cover: window.CV[colorKey], coverImg: coverImg || undefined,
    progress: { current: 0, total: Number(total) || 100, unit: type === "video" ? "мин" : "стр." } };

  return (
    <div className="page screen-enter" style={{ maxWidth: 920 }}>
      <div className="row-3" style={{ marginBottom: "var(--s-5)" }}>
        <span className="task__link" onClick={() => nav({ screen: "library" })}><Icon name="back" size={14} />Библиотека</span>
      </div>
      <h1 className="page-title" style={{ marginBottom: "var(--s-6)" }}>Новый материал</h1>
      <div className="cols cols--detail">
        <div><Cmp.Cover m={preview} showBar={false} /></div>
        <div className="stack-4">
          <div>
            <div className="e-label" style={{ marginBottom: 8 }}>Тип</div>
            <div className="seg">
              {[["fiction", "Худлит", "book"], ["science", "Наука", "flask"], ["video", "Видео", "film"]].map(([v, l, ic]) => (
                <button key={v} className={"seg__btn" + (type === v ? " seg__btn--on" : "")} onClick={() => setType(v)}><Icon name={ic} size={14} />{l}</button>
              ))}
            </div>
          </div>
          <Field label="Название"><input value={title} onChange={(e) => setTitle(e.target.value)} autoFocus className="g-input" placeholder="Например, Бесы" /></Field>
          <Field label="Автор"><input value={author} onChange={(e) => setAuthor(e.target.value)} className="g-input" placeholder="Ф. Достоевский" /></Field>
          <Field label={type === "video" ? "Длительность (мин)" : "Всего страниц"}><input type="number" value={total} onChange={(e) => setTotal(e.target.value)} className="g-input" style={{ width: 140 }} /></Field>
          <div>
            <div className="e-label" style={{ marginBottom: 8 }}>Цвет обложки</div>
            <div className="row-2 wrap gap-2">
              {colorKeys.map((k) => (
                <button key={k} onClick={() => setColorKey(k)} title={k}
                  style={{ width: 30, height: 30, border: colorKey === k ? "2px solid var(--ink-100)" : "1px solid var(--ink-40)", background: `linear-gradient(150deg, ${window.CV[k].from}, ${window.CV[k].to})`, cursor: "pointer", boxShadow: colorKey === k ? "var(--shadow-tap)" : "none" }} />
              ))}
            </div>
          </div>
          <div>
            <div className="e-label" style={{ marginBottom: 8 }}>Обложка (изображение)</div>
            <div className="row-3" style={{ gap: 12, alignItems: "center" }}>
              <Cmp.GButton variant="ghost" onClick={pickImage}>{coverImg ? "Заменить фото" : "Загрузить фото"}</Cmp.GButton>
              {coverImg && <span className="muted" style={{ fontSize: "var(--t-small)" }}>Фото загружено</span>}
              {coverImg && <span className="task__link" onClick={() => setCoverImg(null)} style={{ fontSize: "var(--t-small)" }}><Icon name="close" size={12} />убрать</span>}
            </div>
          </div>
          <div className="row-2 gap-3" style={{ marginTop: 8 }}>
            <Cmp.GButton variant="signal" icon="plus" onClick={submit}>Добавить в библиотеку</Cmp.GButton>
            <Cmp.GButton variant="ghost" onClick={() => nav({ screen: "library" })}>Отмена</Cmp.GButton>
          </div>
        </div>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return <div><div className="e-label" style={{ marginBottom: 8 }}>{label}</div>{children}</div>;
}

window.Screens = Object.assign(window.Screens || {}, {
  material: MaterialScreen, addMaterial: AddMaterialScreen,
});
