// STEP 3 — Review Index (tree + summary)
const { useState: useState3, useMemo: useMemo3 } = React;

function Step3Index({ title, sections, onBack, onStart, loading, onOpenDiagrams }) {
  const [collapsed, setCollapsed] = useState3({}); // top-level chapter numbers
  const [hovered, setHovered] = useState3(null);

  const tree = useMemo3(() => buildTree(sections), [sections]);
  const chapterTags = useMemo3(() => tree.map((ch) => ch.title).slice(0, 9), [tree]);
  const totalSections = sections.length;
  const totalChapters = tree.length;
  const totalPages = sections.reduce((a, s) => a + (s.est || 0), 0);
  const wordCount = totalPages * 380; // ~380 words/page
  const estMinutes = Math.round(totalSections * 0.85);

  const toggle = (n) => setCollapsed((s) => ({ ...s, [n]: !s[n] }));

  return (
    <div className="max-w-[1180px] mx-auto px-8 pb-8 fade-up">
      <div className="mb-5">
        <div className="mono text-[11px] uppercase tracking-[0.18em] text-teal-700 mb-2">Step 03 / Index</div>
        <h1 className="text-[24px] font-semibold tracking-tight text-ink-900 leading-tight">{title}</h1>
        <p className="text-[13px] text-ink-500 mt-1">Review the proposed structure. You'll be able to reorder and edit sections after generation completes.</p>
      </div>

      <div className="grid grid-cols-[1fr_360px] gap-5">
        {/* LEFT: Tree */}
        <div className="bg-white border border-ink-100 rounded-xl shadow-card overflow-hidden">
          <div className="px-4 py-3 border-b border-ink-100 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="mono text-[11px] uppercase tracking-wider text-ink-500">Table of contents</span>
              <span className="mono text-[10px] px-1.5 py-0.5 rounded bg-teal-50 text-teal-700 border border-teal-100">
                {totalSections} sections · {totalChapters} chapters
              </span>
            </div>
            <div className="flex items-center gap-1">
              <button onClick={() => setCollapsed({})} className="h-7 px-2 text-[11.5px] text-ink-500 hover:bg-ink-50 rounded">Expand all</button>
              <button onClick={() => setCollapsed(Object.fromEntries(tree.map(c => [c.num, true])))} className="h-7 px-2 text-[11.5px] text-ink-500 hover:bg-ink-50 rounded">Collapse all</button>
            </div>
          </div>

          <div className="max-h-[560px] overflow-y-auto nice-scroll p-2">
            {tree.map((ch) => (
              <div key={ch.num} className="mb-0.5">
                <Row
                  num={ch.num} title={ch.title}
                  level={0}
                  collapsed={collapsed[ch.num]}
                  hasChildren={ch.children.length > 0}
                  onToggle={() => toggle(ch.num)}
                  est={ch.est}
                  setHovered={setHovered} hovered={hovered}/>
                {!collapsed[ch.num] && ch.children.map((s) => (
                  <Row
                    key={s.num} num={s.num} title={s.title}
                    level={1} est={s.est}
                    setHovered={setHovered} hovered={hovered}/>
                ))}
              </div>
            ))}
          </div>
        </div>

        {/* RIGHT: Summary */}
        <div className="space-y-4">
          <div className="bg-white border border-ink-100 rounded-xl shadow-card p-5">
            <div className="mono text-[10px] uppercase tracking-wider text-ink-500 mb-3">Report estimate</div>
            <div className="grid grid-cols-2 gap-y-3.5 gap-x-3">
              <Stat label="Pages" value={totalPages} hint="~380 wds / page"/>
              <Stat label="Word count" value={`~${(wordCount/1000).toFixed(1)}k`} hint="post-edit"/>
              <Stat label="Sections" value={totalSections} hint={`${totalChapters} chapters`}/>
              <Stat label="Gen. time" value={`~${estMinutes} min`} hint="parallel agents"/>
            </div>
          </div>

          <div className="bg-white border border-ink-100 rounded-xl shadow-card p-5">
            <div className="mono text-[10px] uppercase tracking-wider text-ink-500 mb-3">Key topics covered</div>
            <div className="flex flex-wrap gap-1.5">
              {chapterTags.map((t) => (
                <span key={t} className="inline-flex items-center gap-1 px-2 h-6 rounded-full bg-teal-50 text-teal-700 border border-teal-100 text-[11.5px]">
                  <Icons.Tag size={10}/> {t}
                </span>
              ))}
            </div>
          </div>

          <div className="bg-gradient-to-br from-teal-500 to-teal-700 text-white rounded-xl p-5 relative overflow-hidden">
            <div className="absolute inset-0 opacity-15"
              style={{ backgroundImage: "radial-gradient(circle at 20% 10%, white 1px, transparent 1px)", backgroundSize: "16px 16px" }}/>
            <div className="relative">
              <div className="mono text-[10px] uppercase tracking-wider opacity-80 mb-2">Ready to generate</div>
              <div className="text-[14px] leading-snug">
                Roughly <span className="mono font-semibold">{totalSections}</span> sections will be generated by our analyst agents in parallel. You can monitor progress section-by-section in the next step.
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Bottom bar */}
      <div className="mt-6 flex items-center justify-between">
        <button onClick={onBack} className="h-10 px-3.5 inline-flex items-center gap-1.5 text-[13px] text-ink-600 hover:text-ink-900">
          <Icons.ArrowLeft size={14}/> Back
        </button>

        <div className="flex items-center gap-2">
          {onOpenDiagrams && (
            <button
              onClick={onOpenDiagrams}
              className="h-11 px-4 inline-flex items-center gap-2 bg-white border border-ink-200 hover:border-teal-400 hover:bg-teal-50/40 text-ink-800 text-[13px] font-medium rounded-lg transition-colors">
              <Icons.Image size={14} className="text-teal-600"/>
              Upload Diagrams for This Report
              <Icons.ArrowRight size={14}/>
            </button>
          )}
          <button
            disabled={loading}
            onClick={onStart}
            className="h-11 px-5 inline-flex items-center gap-2 bg-gradient-to-b from-teal-500 to-teal-600 hover:from-teal-400 hover:to-teal-500 disabled:opacity-60 text-white text-[13.5px] font-semibold rounded-lg shadow-card-lg transition-colors">
            {loading ? <Icons.Loader size={15} className="spin-slow"/> : <Icons.Rocket size={15}/>}
            Start Generation
            <Icons.ArrowRight size={15}/>
          </button>
        </div>
      </div>
    </div>
  );
}

function Row({ num, title, level, est, collapsed, hasChildren, onToggle, setHovered, hovered }) {
  const isChapter = level === 0;
  const isHover = hovered === num;
  return (
    <div
      onMouseEnter={() => setHovered && setHovered(num)}
      onMouseLeave={() => setHovered && setHovered(null)}
      className={`group flex items-center gap-2 px-2 py-1.5 rounded-md transition-colors
        ${isChapter ? "hover:bg-teal-50/60" : "hover:bg-ink-50"}`}
      style={{ paddingLeft: 8 + level * 22 }}>
      {/* Drag handle (future) */}
      <span className={`h-5 w-3 grid place-items-center transition-opacity ${isHover ? "opacity-100" : "opacity-0"} text-ink-300`}>
        <Icons.GripVertical size={12}/>
      </span>

      {/* Chevron */}
      {hasChildren ? (
        <button onClick={onToggle} className="h-5 w-5 grid place-items-center rounded text-ink-400 hover:text-ink-700 hover:bg-white">
          <Icons.ChevronRight size={12} className={`transition-transform ${collapsed ? "" : "rotate-90"}`}/>
        </button>
      ) : (
        <span className="h-5 w-5 grid place-items-center">
          <span className="h-1 w-1 rounded-full bg-ink-300"/>
        </span>
      )}

      {/* Number */}
      <span className={`mono text-[11px] tabular-nums ${isChapter ? "text-teal-700 font-semibold" : "text-ink-400"} w-12`}>{num}</span>

      {/* Title */}
      <span className={`flex-1 truncate ${isChapter ? "text-[13.5px] font-semibold text-ink-900" : "text-[13px] text-ink-700"}`}>{title}</span>

      {/* Pages */}
      <span className="mono text-[10.5px] text-ink-400 tabular-nums">{est}p</span>
    </div>
  );
}

function Stat({ label, value, hint }) {
  return (
    <div>
      <div className="mono text-[10px] uppercase tracking-wider text-ink-400">{label}</div>
      <div className="text-[22px] font-semibold tracking-tight text-ink-900 mt-0.5 leading-none mono tabular-nums">{value}</div>
      <div className="text-[10.5px] text-ink-400 mt-1">{hint}</div>
    </div>
  );
}

function buildTree(sections) {
  const out = [];
  let current = null;
  for (const s of sections) {
    const parts = s.num.split(".");
    if (parts.length === 1) {
      current = { ...s, children: [] };
      out.push(current);
    } else if (current) {
      current.children.push(s);
    }
  }
  return out;
}

window.Step3Index = Step3Index;
