/* ============================================================
   Guided Workshop — main app
   Composes: ChapterNav, content area, tabs, poll-session panel.
   Loads window.GW_CHAPTERS, window.GW_TOTAL, window.GW_ACTIONS,
   window.gwViews, and window.useTweaks / TweaksPanel.
   ============================================================ */

const { useState, useEffect, useMemo, useCallback } = React;
const { ContentView, PollView, EvidenceView, MediaView, QuestionView, PollSessionPanel, ItemTypeIcon, gwIcons, Lightbox } = window.gwViews;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "demoItemType": "question",
  "progressPreset": "mid",
  "galleryMode": "grid",
  "perspective": "completer",
  "sessionLive": true,
  "resultsLayout": "rail"
}/*EDITMODE-END*/;

/* Find an item by its id across all chapters. Returns { chapter, item, chIdx, itIdx }. */
function findItem(id) {
  for (let ci = 0; ci < GW_CHAPTERS.length; ci++) {
    const c = GW_CHAPTERS[ci];
    for (let ii = 0; ii < c.items.length; ii++) {
      if (c.items[ii].id === id) return { chapter: c, item: c.items[ii], chIdx: ci, itIdx: ii };
    }
  }
  return null;
}
/* Find first item of given type (used by the Tweaks demo cycler).
   "question-poll" is a pseudo-type meaning "question item with mode: poll". */
function firstOfType(type) {
  if (type === "question-poll") {
    for (const c of GW_CHAPTERS) {
      for (const it of c.items) if (it.type === "question" && it.mode === "poll") return it;
    }
    return null;
  }
  if (type === "question") {
    for (const c of GW_CHAPTERS) {
      for (const it of c.items) if (it.type === "question" && it.mode !== "poll") return it;
    }
    return null;
  }
  for (const c of GW_CHAPTERS) {
    for (const it of c.items) if (it.type === type) return it;
  }
  return null;
}

/* Compute pre-filled completion based on the progress preset. */
function presetCompletion(preset) {
  const ids = [];
  for (const c of GW_CHAPTERS) for (const it of c.items) ids.push(it.id);
  const set = new Set();
  let n = 0;
  if (preset === "start") n = 1;
  if (preset === "early") n = Math.max(2, Math.round(ids.length * 0.15));
  if (preset === "mid")   n = Math.round(ids.length * 0.45);
  if (preset === "late")  n = Math.round(ids.length * 0.85);
  if (preset === "done")  n = ids.length;
  for (let i = 0; i < n; i++) set.add(ids[i]);
  return set;
}

/* =====================================================================
   ChapterNav — left panel with progress + collapsible chapter sections
   ===================================================================== */
function ChapterNav({ activeId, completion, onPick }) {
  const [openChapters, setOpenChapters] = useState(
    () => new Set(GW_CHAPTERS.map(c => c.id))
  );
  const toggleChapter = (id) =>
    setOpenChapters(prev => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });

  const total = GW_TOTAL;
  const done = completion.size;
  const pct = Math.round((done / total) * 100);

  return (
    <aside className="gw-nav">
      <div className="gw-nav-progress">
        <div className="gw-progress-bar">
          <div className="gw-progress-fill" style={{ width: `${pct}%` }} />
        </div>
        <div className="gw-progress-text">
          <span><b>{done}</b>/{total} completed</span>
          <b>{pct}%</b>
        </div>
      </div>

      <div className="gw-chapters">
        {GW_CHAPTERS.map((c) => {
          const open = openChapters.has(c.id);
          const cDone = c.items.filter(it => completion.has(it.id)).length;
          return (
            <section key={c.id} className={`gw-chapter ${open ? "is-open" : ""}`}>
              <button
                className="gw-chapter-head"
                onClick={() => toggleChapter(c.id)}
                aria-expanded={open}
              >
                <span className="gw-chapter-title">
                  <span className="gw-chapter-num">{c.num}.</span> {c.title}
                </span>
                <span className="gw-chapter-meta">{cDone}/{c.items.length} completed</span>
                <span className="gw-chapter-chev">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="18 15 12 9 6 15"/></svg>
                </span>
              </button>

              {open && (
                <ul className="gw-items">
                  {c.items.map((it) => {
                    const isActive = it.id === activeId;
                    const isDone = completion.has(it.id);
                    return (
                      <li key={it.id}>
                        <button
                          className={`gw-item ${isActive ? "is-active" : ""} ${isDone ? "is-done" : ""}`}
                          onClick={() => onPick(it.id)}
                        >
                          <span className={`gw-item-icon type-${iconTypeForItem(it)}`}>
                            <ItemTypeIcon type={iconTypeForItem(it)} />
                          </span>
                          <span className="gw-item-text">
                            <span className="gw-item-title">{it.num} {it.title}</span>
                            <span className="gw-item-type">{labelForItem(it)}</span>
                          </span>
                          <span className="gw-item-status">
                            {isDone && <span className="gw-status-dot is-done" title="Completed">{gwIcons.check}</span>}
                            {!isDone && isActive && <span className="gw-status-dot is-current" title="In progress">{gwIcons.refresh}</span>}
                          </span>
                        </button>
                      </li>
                    );
                  })}
                </ul>
              )}
            </section>
          );
        })}
      </div>
    </aside>
  );
}

function labelForType(t) {
  if (t === "content") return "Content";
  if (t === "evidence") return "Evidence";
  if (t === "media") return "Media";
  if (t === "question") return "Question";
  if (t === "poll") return "Poll";
  return t;
}
function labelForItem(it) {
  if (it.type === "question") {
    const map = {
      radio:    "Multiple choice",
      rating:   "Rating",
      boolean:  "Yes / No",
      text:     "Short answer",
      textarea: "Long answer",
    };
    const sub = map[it.questionType] || "Question";
    return it.mode === "poll" ? `Poll \u00b7 ${sub}` : sub;
  }
  if (it.type === "media") return it.mediaKind === "video" ? "Video" : (Array.isArray(it.images) && it.images.length > 1 ? "Images" : "Image");
  return labelForType(it.type);
}
/* Pick the nav icon for an item — poll-mode questions get the bar-chart
   icon so workshop leaders can spot them at a glance. */
function iconTypeForItem(it) {
  if (it.type === "question" && it.mode === "poll") return "poll";
  return it.type;
}

/* =====================================================================
   ActionsTab — list of actions added during the workshop
   ===================================================================== */
function ActionsTab({ onJumpToItem }) {
  const [actions, setActions] = useState(GW_ACTIONS);
  const priorityClass = { high: "is-high", med: "is-med", low: "is-low" };
  const priorityLabel = { high: "High", med: "Medium", low: "Low" };
  const statusLabel = { "in-progress": "In progress", open: "Open", done: "Done" };

  return (
    <div className="gw-actions-tab">
      <div className="gw-actions-head">
        <div>
          <h3>Actions captured in this workshop</h3>
          <p className="gw-actions-sub">{actions.length} action{actions.length === 1 ? "" : "s"} · Add as you go, refine before submitting.</p>
        </div>
        <button className="gw-btn gw-btn-secondary">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>
          <span>Add action</span>
        </button>
      </div>

      {actions.length === 0 ? (
        <div className="gw-empty">No actions yet. Add one as the workshop surfaces remediation work.</div>
      ) : (
        <ul className="gw-action-list">
          {actions.map(a => (
            <li key={a.id} className="gw-action">
              <div className="gw-action-main">
                <div className="gw-action-title-row">
                  <h4 className="gw-action-title">{a.title}</h4>
                  <span className={`gw-pill gw-pill-priority ${priorityClass[a.priority]}`}>{priorityLabel[a.priority]} priority</span>
                </div>
                <p className="gw-action-desc">{a.desc}</p>
                <div className="gw-action-tags">
                  {a.tags.map((t, i) => <span key={i} className="gw-tag-sm">{t}</span>)}
                  {a.linkedItem && (
                    <button
                      type="button"
                      className="gw-tag-sm gw-tag-linked"
                      onClick={() => onJumpToItem && onJumpToItem(a.linkedItem)}
                      title={`Jump to ${a.linkedItem}`}
                    >
                      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
                      Linked to {a.linkedItem}
                    </button>
                  )}
                </div>
              </div>
              <div className="gw-action-meta">
                <div className="gw-action-owner">
                  <img src={a.owner.avatar} alt="" />
                  <span>{a.owner.name}</span>
                </div>
                <div className="gw-action-due">Due {a.due}</div>
                <div className={`gw-status-pill is-${a.status}`}>{statusLabel[a.status]}</div>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

/* =====================================================================
   ResultsTab — completion progress + poll results summary
   ===================================================================== */
function ResultsTab({ completion }) {
  const total = GW_TOTAL;
  const done = completion.size;
  const pct = Math.round((done / total) * 100);

  /* Aggregate counts by type */
  const byType = {
    content:  { total: 0, done: 0 },
    media:    { total: 0, done: 0 },
    question: { total: 0, done: 0 },
    poll:     { total: 0, done: 0 },
    evidence: { total: 0, done: 0 },
  };
  for (const c of GW_CHAPTERS) for (const it of c.items) {
    /* Poll-mode questions count in the poll bucket; everything else in their own. */
    const bucket = (it.type === "question" && it.mode === "poll") ? "poll" : it.type;
    if (byType[bucket]) {
      byType[bucket].total++;
      if (completion.has(it.id)) byType[bucket].done++;
    }
  }

  /* Mock poll-result bars for the polls that exist */
  const polls = [];
  for (const c of GW_CHAPTERS) for (const it of c.items) {
    if (it.type === "question" && it.mode === "poll") polls.push(it);
  }

  return (
    <div className="gw-results-tab">
      <section className="gw-results-summary">
        <div className="gw-results-circle">
          <svg viewBox="0 0 36 36">
            <circle className="gw-results-track" cx="18" cy="18" r="15" pathLength="100"/>
            <circle className="gw-results-fill"  cx="18" cy="18" r="15" pathLength="100"
              style={{ strokeDasharray: `${pct} 100` }} />
          </svg>
          <div className="gw-results-circle-num">{pct}<span>%</span></div>
        </div>
        <div className="gw-results-summary-text">
          <h3>{done} of {total} items completed</h3>
          <p>This workshop will be ready to submit once every item is marked complete.</p>
          <div className="gw-results-bytype">
            {["content", "media", "question", "poll", "evidence"].map(t => (
              byType[t].total > 0 ? (
                <div key={t} className={`gw-results-bytype-row type-${t}`}>
                  <span className="gw-results-bytype-icon"><ItemTypeIcon type={t} /></span>
                  <span className="gw-results-bytype-lbl">{labelForType(t)}</span>
                  <span className="gw-results-bytype-num">{byType[t].done}/{byType[t].total}</span>
                </div>
              ) : null
            ))}
          </div>
        </div>
      </section>

      <section className="gw-poll-results">
        <h3 className="gw-section-title">Poll responses</h3>
        {polls.length === 0 && <div className="gw-empty">No polls in this workshop.</div>}
        <div className="gw-poll-result-list">
          {polls.map((p, idx) => {
          /* deterministic mock distribution per poll — only for choice polls */
            const seed = idx + 1;
            const total = p.session?.responded || 0;
            const opts = p.options || [];
            const dist = opts.map((_, i) => {
              const x = Math.sin(seed * 17 + i * 7) * 100;
              return Math.abs(Math.round(x)) % 100;
            });
            const sum = dist.reduce((a, b) => a + b, 0) || 1;
            const norm = dist.map(v => Math.round((v / sum) * 100));
            return (
              <article key={p.id} className="gw-poll-result">
                <header className="gw-poll-result-head">
                  <span className="gw-poll-result-num">{p.num}</span>
                  <span className="gw-poll-result-title">{p.title}</span>
                  <span className="gw-poll-result-count">
                    {total > 0 ? `${total} responses` : "Not yet opened"}
                  </span>
                </header>
                {total > 0 && p.options && (
                  <ul className="gw-poll-bars">
                    {p.options.map((opt, i) => (
                      <li key={i}>
                        <span className="gw-poll-bar-lbl">{opt}</span>
                        <span className="gw-poll-bar-track">
                          <span className="gw-poll-bar-fill" style={{ width: `${norm[i]}%` }} />
                        </span>
                        <span className="gw-poll-bar-num">{norm[i]}%</span>
                      </li>
                    ))}
                  </ul>
                )}
              </article>
            );
          })}
        </div>
      </section>
    </div>
  );
}

/* =====================================================================
   App — root
   ===================================================================== */
function App() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  /* Supporter state (creator co-pilots with completer) */
  const sup = window.useSupporter(t.perspective);
  useEffect(() => { if (sup.perspective !== t.perspective) sup.setPerspective(t.perspective); /* eslint-disable-next-line */ }, [t.perspective]);
  useEffect(() => { sup.setSessionLive(t.sessionLive); /* eslint-disable-next-line */ }, [t.sessionLive]);

  /* Transcribe state */
  const tx = window.useTranscribe({ moduleName: "Asset Management" });

  /* URL-param entry point: ?as=supporter / ?as=completer overrides initial perspective.
     Lets the creator's modules list link straight into co-pilot mode. */
  useEffect(() => {
    const as = new URLSearchParams(location.search).get("as");
    if ((as === "supporter" || as === "completer") && t.perspective !== as) setTweak("perspective", as);
    // eslint-disable-next-line
  }, []);

  /* Tab state */
  const [tab, setTab] = useState("content");

  /* Active item id — defaults driven by tweaks demoItemType */
  const initialActive = useMemo(() => (firstOfType(t.demoItemType) || GW_CHAPTERS[0].items[0]).id, []);
  const [activeId, setActiveId] = useState(initialActive);

  /* When the user changes demoItemType via Tweaks, jump to that type's first item */
  useEffect(() => {
    const it = firstOfType(t.demoItemType);
    if (it && it.id !== activeId) setActiveId(it.id);
    // eslint-disable-next-line
  }, [t.demoItemType]);

  /* Completion set */
  const [completion, setCompletion] = useState(() => presetCompletion(t.progressPreset));
  /* When progressPreset changes, reset completion */
  useEffect(() => {
    setCompletion(presetCompletion(t.progressPreset));
    // eslint-disable-next-line
  }, [t.progressPreset]);

  /* Per-poll live state. true → accepting anonymous responses (panel visible).
     Independent of `complete` so the lifecycle can be:
       Never opened (live=false, complete=false)
       Live          (live=true,  complete=false)
       Closed        (live=false, complete=true)
       Reopened      (live=true,  complete=false) — same shape as Live */
  const [pollsLive, setPollsLive] = useState({});
  const isPollLive = (id) => !!pollsLive[id];
  const openPoll  = useCallback((id) => setPollsLive((p) => ({ ...p, [id]: true  })), []);
  const closePoll = useCallback((id) => setPollsLive((p) => ({ ...p, [id]: false })), []);

  /* Per-question answers — lifted here so they survive navigation */
  const [answers, setAnswers] = useState({});
  const setAnswer = useCallback((id, a) => {
    setAnswers((prev) => ({ ...prev, [id]: a }));
  }, []);

  /* Poll session panel state */

  /* Gallery mode — expose to Gallery components via window flag + event */
  useEffect(() => {
    window.__gwGalleryMode = t.galleryMode;
    window.dispatchEvent(new CustomEvent("gw-gallery-mode"));
  }, [t.galleryMode]);

  const found = findItem(activeId);
  const activeItem = found?.item;
  const sessionOpen = activeItem && activeItem.type === "question" && activeItem.mode === "poll" && isPollLive(activeItem.id);

  /* Nothing special to do when navigating away — each poll keeps its own
     pollsLive state, so the next visit shows whatever state it was left in. */

  /* Toggle completion. For a live poll, marking complete also closes the
     poll. Reopening a closed poll (via QuestionView's Reopen button) marks
     it incomplete in the same gesture — see reopenPoll below. */
  const toggleComplete = useCallback((id) => {
    setCompletion(prev => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
        /* If this is a live poll, close it too */
        if (pollsLive[id]) setPollsLive(p => ({ ...p, [id]: false }));
      }
      return next;
    });
  }, [pollsLive]);

  const reopenPoll = useCallback((id) => {
    setPollsLive(p => ({ ...p, [id]: true }));
    setCompletion(prev => {
      const next = new Set(prev);
      next.delete(id);
      return next;
    });
  }, []);

  const openSession  = useCallback(() => activeItem && openPoll(activeItem.id),  [activeItem, openPoll]);
  const closeSession = useCallback(() => activeItem && closePoll(activeItem.id), [activeItem, closePoll]);

  /* ───── Tweaks panel ───── */
  const tweaksPanel = (
    <window.TweaksPanel>
      <window.TweakSection label="Item type demo">
        <window.TweakSelect
          options={[
            { value: "content",  label: "Content (rich text + media)" },
            { value: "media",    label: "Media (image / video)" },
            { value: "evidence", label: "Evidence (file upload)" },
            { value: "question", label: "Question (individual)" },
          ]}
          value={t.demoItemType}
          onChange={(v) => setTweak("demoItemType", v)}
        />
        <div className="gw-tweak-note">Jumps to the first item of the chosen type. Poll-mode questions live in Chapter 5; individual ones in Chapter 6.</div>
      </window.TweakSection>

      <window.TweakSection label="Progress state">
        <window.TweakRadio
          options={[
            { value: "start", label: "Just started" },
            { value: "mid",   label: "Mid-flight"   },
            { value: "late",  label: "Almost done"  },
          ]}
          value={t.progressPreset}
          onChange={(v) => setTweak("progressPreset", v)}
        />
      </window.TweakSection>

      <window.TweakSection label="Image gallery">
        <window.TweakRadio
          options={[
            { value: "grid",     label: "Grid"     },
            { value: "carousel", label: "Carousel" },
            { value: "hero",     label: "Hero+strip" },
          ]}
          value={t.galleryMode}
          onChange={(v) => setTweak("galleryMode", v)}
        />
        <div className="gw-tweak-note">Affects content blocks that contain multiple images (e.g. 1.1 Introduction).</div>
      </window.TweakSection>

      <window.TweakSection label="Perspective">
        <window.TweakRadio
          options={[
            { value: "completer", label: "Completer" },
            { value: "supporter", label: "Creator (supporter)" },
          ]}
          value={t.perspective}
          onChange={(v) => setTweak("perspective", v)}
        />
        <div className="gw-tweak-note">Switch seats of a live workshop. The supporter is a creator who's dropped in to co-pilot — same UI, extra controls overlaid.</div>
      </window.TweakSection>
      <window.TweakSection label="Live session">
        <window.TweakToggle
          label="Session active"
          value={t.sessionLive}
          onChange={(v) => setTweak("sessionLive", v)}
        />
        <div className="gw-tweak-note">When off, the supporter is gone and the completer sees a normal solo workshop.</div>
      </window.TweakSection>

      <window.TweakSection label="Results layout">
        <window.TweakRadio
          options={[
            { value: "rail", label: "Sidebar + folds" },
            { value: "tabs", label: "Chapter tabs" },
          ]}
          value={t.resultsLayout}
          onChange={(v) => setTweak("resultsLayout", v)}
        />
        <div className="gw-tweak-note">Affects the Results tab. Sidebar shows a sticky chapter list with foldable chapter sections; chapter tabs swap the section for a horizontal tab strip showing one chapter at a time.</div>
      </window.TweakSection>

      {activeItem?.type === "question" && activeItem?.mode === "poll" && (
        <window.TweakSection label="Poll session">
          <window.TweakToggle
            label="Open poll"
            value={isPollLive(activeItem.id)}
            onChange={(v) => v ? openPoll(activeItem.id) : closePoll(activeItem.id)}
          />
        </window.TweakSection>
      )}
    </window.TweaksPanel>
  );

  return (
    <>
      {sup.sessionLive && <window.SupporterSessionBanner sup={sup} moduleName="Asset Management" />}
      <header className="gw-mod-head" data-screen-label="Module header">
        <div className="gw-mod-title">
          <h1>Asset Management</h1>
          <div className="gw-mod-sub">A guided diagnostic of your organizational foundations.</div>
        </div>
        <div className="gw-mod-actions">
          <window.TranscribeButton tx={tx} variant="v1" />
          <button className="gw-btn gw-btn-tonal">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>
            <span>Add action</span>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="6 9 12 15 18 9"/></svg>
          </button>
        </div>
      </header>

      <nav className="gw-tabs" role="tablist">
        <button role="tab" aria-selected={tab === "content"} className={`gw-tab ${tab === "content" ? "is-active" : ""}`} onClick={() => setTab("content")}>Content</button>
        <button role="tab" aria-selected={tab === "actions"} className={`gw-tab ${tab === "actions" ? "is-active" : ""}`} onClick={() => setTab("actions")}>
          Actions <span className="gw-tab-count">{GW_ACTIONS.length}</span>
        </button>
        <button role="tab" aria-selected={tab === "results"} className={`gw-tab ${tab === "results" ? "is-active" : ""}`} onClick={() => setTab("results")}>Results</button>
        <button role="tab" aria-selected={tab === "ai"} className={`gw-tab ${tab === "ai" ? "is-active" : ""}`} onClick={() => setTab("ai")}>
          AI report <span className="gw-tab-ai-spark" aria-hidden="true">✨</span>
        </button>
      </nav>

      {tab === "content" && (
        <div className="gw-content-area" data-screen-label="Content tab">
          <ChapterNav
            activeId={activeId}
            completion={completion}
            onPick={(id) => setActiveId(id)}
          />
          <main className="gw-viewer">
            <div className={`gw-viewer-card ${sessionOpen ? "with-side-panel" : ""}`}>
              {sup.sessionLive && activeItem && (
                <window.SupporterDock sup={sup} itemId={activeItem.id} position="tr" />
              )}
              {activeItem && <window.SupporterAskCreator sup={sup} />}
              {sup.sessionLive && activeItem && <window.SupporterGuidanceCard sup={sup} itemId={activeItem.id} />}
              {sup.sessionLive && activeItem && <window.SupporterHighlightStrip sup={sup} itemId={activeItem.id} />}
              {sup.sessionLive && activeItem && <window.SupporterTakeoverPulse sup={sup} itemId={activeItem.id} />}
              {activeItem?.type === "content"  && <ContentView  item={activeItem} complete={completion.has(activeItem.id)} onComplete={() => toggleComplete(activeItem.id)} />}
              {activeItem?.type === "evidence" && <EvidenceView item={activeItem} complete={completion.has(activeItem.id)} onComplete={() => toggleComplete(activeItem.id)} />}
              {activeItem?.type === "media"    && <MediaView    item={activeItem} complete={completion.has(activeItem.id)} onComplete={() => toggleComplete(activeItem.id)} />}
      {activeItem?.type === "question" && <QuestionView item={activeItem} complete={completion.has(activeItem.id)} pollLive={isPollLive(activeItem.id)} answer={answers[activeItem.id]} onAnswer={(a) => setAnswer(activeItem.id, a)} onComplete={() => toggleComplete(activeItem.id)} sessionOpen={sessionOpen} onOpenSession={openSession} onReopenPoll={() => reopenPoll(activeItem.id)} />}
              {activeItem && <window.SupporterStuckButton sup={sup} itemId={activeItem.id} thresholdSec={30} />}
              {sup.sessionLive && activeItem && sup.openPanel === "comments" && (
                <window.SupporterCommentPanel sup={sup} itemId={activeItem.id} onClose={() => sup.setOpenPanel(null)} />
              )}
            </div>
            {sessionOpen && activeItem?.type === "question" && activeItem?.mode === "poll" && (
              <PollSessionPanel
                item={activeItem}
                complete={completion.has(activeItem.id)}
                onClose={closeSession}
                onMarkComplete={() => { toggleComplete(activeItem.id); closeSession(); }}
              />
            )}
          </main>
        </div>
      )}

      {tab === "actions" && (
        <div className="gw-tab-pane" data-screen-label="Actions tab">
          <ActionsTab onJumpToItem={(num) => {
            /* a.linkedItem is the item.num, which matches item.id in the
               current data. Look it up to be safe across future renames. */
            const found = findItem(num);
            const id = found ? found.item.id : num;
            setActiveId(id);
            setTab("content");
          }} />
        </div>
      )}

      {tab === "results" && (
        <div className="gw-tab-pane" data-screen-label="Results tab">
          <window.ResultsTabRevamped layout={t.resultsLayout} />
        </div>
      )}

      {tab === "ai" && (
        <div className="gw-tab-pane" data-screen-label="AI report tab">
          <window.AiReportTab />
        </div>
      )}

      {sup.sessionLive && activeItem && tab === "content" && (
        <window.SupporterCoPilotBar
          sup={sup}
          itemId={activeItem.id}
          itemLabel={`${activeItem.num} ${activeItem.title}`}
        />
      )}

      {tweaksPanel}
      <Lightbox />
      <window.TranscribeDrawer tx={tx} variant="v1" />
      <window.TranscribeSummaryModal tx={tx} variant="v1" />
    </>
  );
}

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