/* Nutshell shell prototype — OVERLAYS & PANELS
   Chat (shared body), Audience, Nuggets, Source, Library, Compose,
   Progress, Settings, CommandPalette. window.SHELL_OVERLAYS */
(function () {
  const { Icon } = window.NSIcons;
  const C = window.SHELL_CORE;
  const useEngine = C.useEngine;
  const { IBtn, Pill, Avatar } = C;
  const D = window.SHELL;

  const TYPE_ICON = { youtube: "youtube", graph: "graph", text: "text" };

  // ---- generic wrappers ---------------------------------------------------
  function Scrim({ onClose, children, blur, center }) {
    return (
      <div className={"scrim" + (blur ? " scrim--blur" : "")} onPointerDown={(e) => { if (e.target === e.currentTarget) onClose && onClose(); }}
        style={center ? { display: "flex", alignItems: "center", justifyContent: "center" } : null}>
        {children}
      </div>
    );
  }
  function ModalHead({ title, sub, onClose, icon }) {
    return (
      <div className="mhead">
        {icon && <span className="mhead-ic"><Icon name={icon} size={17} /></span>}
        <div><div className="mhead-t">{title}</div>{sub && <div className="mhead-s">{sub}</div>}</div>
        <button className="ib mhead-x" onClick={onClose} aria-label="Close"><Icon name="x" size={16} /></button>
      </div>
    );
  }

  // =========================================================================
  //  CHAT  — shared body; concepts wrap it (drawer / dock / floating)
  // =========================================================================
  function ChatBody({ onClose, variant, unifiedHead }) {
    const e = useEngine();
    const [msgs, setMsgs] = React.useState([{ role: "assistant", text: "What would you like to ask about?" }]);
    const [draft, setDraft] = React.useState("");
    const [speak, setSpeak] = React.useState(true);
    const [speaking, setSpeaking] = React.useState(false);
    const [thinking, setThinking] = React.useState(false);
    const listRef = React.useRef(null);
    const speakTimer = React.useRef(null);
    React.useEffect(() => { if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight; }, [msgs, thinking]);
    React.useEffect(() => () => clearTimeout(speakTimer.current), []);

    const startSpeak = () => {
      setSpeaking(true);
      clearTimeout(speakTimer.current);
      speakTimer.current = setTimeout(() => setSpeaking(false), 4200);
    };
    const stopSpeak = () => { setSpeaking(false); clearTimeout(speakTimer.current); };
    const toggleSpeak = () => setSpeak((s) => { if (s) stopSpeak(); return !s; });

    const send = (text) => {
      const t = (text ?? draft).trim(); if (!t) return;
      setMsgs((m) => [...m, { role: "user", text: t }]); setDraft(""); setThinking(true);
      setTimeout(() => { setThinking(false);
        setMsgs((m) => [...m, { role: "assistant", text: "Good question — in this walkthrough that's handled by the memory store: it keeps a single summarized record, then recall pulls from it on demand.", cite: "Ch. " + (e.ci + 1) }]);
        if (speak) startSpeak();
      }, 1300);
    };

    return (
      <div className={"chat chat--" + (variant || "panel")}>
        <div className="chat-head">
          <button className={"speak-tgl" + (speak ? " speak-tgl--on" : "")} onClick={toggleSpeak} role="switch" aria-checked={speak}>
            <span className="speak-knob"><i /></span>
            Speak answers
          </button>
          {speaking && (
            <button className="speak-stop" onClick={stopSpeak}>
              <span className="speak-stop-ic" /> Stop speaking
            </button>
          )}
          <span className="chat-head-spacer" />
          <IBtn icon="x" label="Close chat" onClick={onClose} />
        </div>
        <div className="chat-list" ref={listRef}>
          {msgs.map((m, i) => (
            <div key={i} className={"bub bub--" + m.role}>
              {m.text}
              {m.cite && <span className="bub-cite"><Icon name="link" size={10} />{m.cite}</span>}
            </div>
          ))}
          {thinking && <div className="bub bub--assistant bub--think"><i /><i /><i /></div>}
        </div>
        <div className="chat-foot">
          <div className="chat-compose">
            <button className="ib" title="Dictate" aria-label="Speak your question"><Icon name="mic" size={15} /></button>
            <input value={draft} onChange={(ev) => setDraft(ev.target.value)} placeholder="Ask anything about this run…"
              onKeyDown={(ev) => { if (ev.key === "Enter") send(); }} />
            <button className="chat-send" onClick={() => send()} aria-label="Send"><Icon name="arrowUp" size={15} /></button>
          </div>
        </div>
      </div>
    );
  }

  // =========================================================================
  //  AUDIENCE  — preset chips + free text + Regenerate
  // =========================================================================
  function AudienceModal() {
    const e = useEngine();
    const [sel, setSel] = React.useState(e.audience);
    const [free, setFree] = React.useState("");
    const [speed, setSpeed] = React.useState(1);  // 0 Fast · 1 Normal · 2 Smart
    const [level, setLevel] = React.useState(1);  // 0 Easy · 1 Normal · 2 Technical
    const [dd, setDd] = React.useState(null);      // open dropdown: "speed" | "level" | null
    const SPEED = ["Fast", "Normal", "Smart"];
    const LEVEL = ["Easy", "Normal", "Technical"];
    const SPEED_D = ["Quick draft, lowest cost", "Balanced quality", "Deepest reasoning"];
    const LEVEL_D = ["Plain language", "General audience", "Full depth & jargon"];
    return (
      <Scrim onClose={e.closeOverlay} blur center>
        <div className="modal modal--aud" onPointerDown={(ev) => ev.stopPropagation()}>
          <ModalHead title="Change audience" sub="Rewrite the narration for who's listening" onClose={e.closeOverlay} icon="wand" />
          <div className="compose-fields">
            <div className={"ddfield" + (dd === "speed" ? " open" : "")}>
              <button type="button" className="popbtn ddfield-trig" onClick={() => setDd(dd === "speed" ? null : "speed")}>
                <span>Intelligence</span><b>{SPEED[speed]}</b><Icon name="chevronDown" size={12} />
              </button>
              {dd === "speed" && (
                <div className="ddmenu">
                  {SPEED.map((t, i) => (
                    <button key={t} type="button" className={"ddmenu-item" + (i === speed ? " on" : "")} onClick={() => { setSpeed(i); setDd(null); }}>
                      <b>{t}</b><span>{SPEED_D[i]}</span><i className="ddtick" />
                    </button>
                  ))}
                </div>
              )}
            </div>
            <div className={"ddfield" + (dd === "level" ? " open" : "")}>
              <button type="button" className="popbtn ddfield-trig" onClick={() => setDd(dd === "level" ? null : "level")}>
                <span>Difficulty</span><b>{LEVEL[level]}</b><Icon name="chevronDown" size={12} />
              </button>
              {dd === "level" && (
                <div className="ddmenu">
                  {LEVEL.map((t, i) => (
                    <button key={t} type="button" className={"ddmenu-item" + (i === level ? " on" : "")} onClick={() => { setLevel(i); setDd(null); }}>
                      <b>{t}</b><span>{LEVEL_D[i]}</span><i className="ddtick" />
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
          <input className="field-lg" placeholder="…or describe one: “explain like I'm 5”, “for a skeptical CFO”"
            value={free} onChange={(ev) => setFree(ev.target.value)} style={{ marginTop: "14px" }} />
          <div className="modal-foot">
            <span className="modal-status">Current: {SPEED[speed]} intelligence · {LEVEL[level]} difficulty</span>
            <Pill variant="pri" icon={e.regenerating ? "refresh" : "wand"} onClick={() => e.regenerate(free.trim() || sel)} style={e.regenerating ? { opacity: .7, pointerEvents: "none" } : null}>
              {e.regenerating ? "Working…" : "Regenerate copy"}
            </Pill>
          </div>
        </div>
      </Scrim>
    );
  }

  // =========================================================================
  //  NUGGETS popover
  // =========================================================================
  function NuggetsBody({ onClose }) {
    return (
      <div className="pop pop--nug">
        <ModalHead title="Gold nuggets" sub="The takeaways worth remembering" onClose={onClose} icon="sparkles" />
        <ol className="nug-list">
          {D.nuggets.map((n, i) => <li key={i}><span className="nug-n">{i + 1}</span><span>{n}</span></li>)}
        </ol>
        <div className="pop-foot">
          <Pill>Copy</Pill><Pill>Download .md</Pill>
        </div>
      </div>
    );
  }

  // =========================================================================
  //  SOURCE transcript popover (+ full modal)
  // =========================================================================
  function SourceBody({ onClose, openFull }) {
    return (
      <div className="pop pop--src">
        <ModalHead title="Original source" onClose={onClose} icon="youtube" />
        <div className="src-card">
          <Icon name="youtube" size={22} />
          <div><div className="src-t">{D.source.title}</div><div className="src-m">{D.source.origin}</div></div>
        </div>
        <div className="pop-foot">
          <Pill icon="expand" onClick={openFull}>View</Pill><Pill icon="link">Copy</Pill><Pill icon="arrowUp">Download</Pill>
        </div>
      </div>
    );
  }
  function SourceFull() {
    const e = useEngine();
    return (
      <Scrim onClose={e.closeOverlay} blur center>
        <div className="modal modal--src" onPointerDown={(ev) => ev.stopPropagation()}>
          <ModalHead title={D.source.title} sub={D.source.origin} onClose={e.closeOverlay} icon="youtube" />
          <div className="src-body">{D.source.body.split("\n\n").map((p, i) => <p key={i}>{p}</p>)}</div>
          <div className="modal-foot"><span className="modal-status">Captured transcript</span><Pill icon="link">Copy</Pill><Pill icon="arrowUp">Download</Pill></div>
        </div>
      </Scrim>
    );
  }

  // =========================================================================
  //  LIBRARY  (list + search + filter + row actions + empty)
  // =========================================================================
  function LibraryBody({ onClose, spotlight, centered }) {
    const e = useEngine();
    const [q, setQ] = React.useState("");
    const [filter, setFilter] = React.useState("All");
    const [empty, setEmpty] = React.useState(false);
    const full = !spotlight;                  // tabs / badges / hover-actions
    const focus = spotlight || centered;      // autofocus + esc affordance
    const rows = D.library.filter((r) =>
      (filter === "All" || (filter === "Active" && r.state === "active") || (filter === "Saved" && r.state === "saved")) &&
      r.title.toLowerCase().includes(q.toLowerCase()));
    const searchField = (
      <div className="field">
        <Icon name="search" size={15} />
        <input placeholder="Search walkthroughs…" value={q} onChange={(ev) => setQ(ev.target.value)} autoFocus={focus} />
        {focus && <kbd>esc</kbd>}
      </div>);
    return (
      <div className={"lib" + (spotlight ? " lib--spot" : "") + (centered ? " lib--center" : "")}>
        {centered ?
        <React.Fragment>
            <ModalHead title="Library" sub="Every walkthrough you’ve made" icon="collection" onClose={onClose} />
            <div className="lib-toolbar">
              {searchField}
              {e.ytEnabled
                ? <button className="lib-import" onClick={() => e.openOverlay("youtube")} title="Import from YouTube"><Icon name="youtube" size={15} /><span>Import</span></button>
                : <button className="lib-import lib-import--locked" onClick={() => { e.setSettingsTab("plugins"); e.openOverlay("settings"); }} title="YouTube Import — unlock in Settings › Plugins"><Icon name="youtube" size={15} /><span>Import</span><span className="pro pro--sm">Pro</span></button>}
            </div>
          </React.Fragment> :
        <div className="lib-head">
            {!spotlight && <b className="lib-title">Library</b>}
            {searchField}
            {full && !centered && <Pill variant="pri" icon="plus" onClick={() => e.openOverlay("compose")}>New</Pill>}
            {full && !centered && <button className="ib" title={empty ? "Show items" : "Preview empty"} onClick={() => setEmpty((x) => !x)}><Icon name="info" size={15} /></button>}
          </div>
        }
        {full && <div className="seg seg--filter">{["All", "Active", "Saved"].map((s) => <button key={s} className={filter === s ? "on" : ""} onClick={() => setFilter(s)}>{s}</button>)}</div>}
        {empty ? (
          <div className="lib-empty">
            <img src="../../assets/nutshell-icon.svg" width="56" height="56" alt="" />
            <b>Nothing in here yet</b>
            <span>Capture a diagram, a video, or some notes and Nutshell narrates it.</span>
            <Pill variant="pri" icon="plus" onClick={() => e.openOverlay("compose")}>Create your first walkthrough</Pill>
            <span className="kbdhint"><kbd>⌥⌘E</kbd> capture from anywhere</span>
          </div>
        ) : (
          <div className="lib-list">
            {rows.map((r, i) => (
              <div key={i} className={"lrow" + (r.current ? " lrow--sel" : "")} onClick={() => { onClose && onClose(); e.gotoChapter(0); }}>
                <Icon name={TYPE_ICON[r.type]} size={16} />
                <span className="lrow-t">{r.title}</span>
                {full && <span className={"badge badge--" + (r.state === "saved" ? "saved" : "active")}>{r.state}</span>}
                <span className="lrow-dur">{r.dur}</span>
                {full && (
                  <span className="lrow-actions">
                    <IBtn icon="play" size={13} label="Play" /><IBtn icon="link" size={13} label="Copy link" />
                    <IBtn icon="bookmark" size={13} label="Save" /><IBtn icon="trash" size={13} label="Delete" />
                  </span>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    );
  }

  // =========================================================================
  //  COMPOSE  → flips to PROGRESS  (Create + Progress, one surface)
  // =========================================================================
  const detect = (t) => /-->|graph |sequencediagram/i.test(t) ? "Mermaid" : /(youtu\.be|youtube\.com)/i.test(t) ? "YouTube" : "Text";
  function ComposeBody() {
    const e = useEngine();
    const [src, setSrc] = React.useState("https://youtu.be/agent-memory-deep-dive");
    const [speed, setSpeed] = React.useState(1);  // 0 Fast · 1 Normal · 2 Smart
    const [level, setLevel] = React.useState(1);  // 0 Easy · 1 Normal · 2 Technical
    const [adv, setAdv] = React.useState(false);
    const SPEED = ["Fast", "Normal", "Smart"];
    const LEVEL = ["Easy", "Normal", "Technical"];
    const SPEED_D = ["Quick draft, lowest cost", "Balanced quality", "Deepest reasoning"];
    const LEVEL_D = ["Plain language", "General audience", "Full depth & jargon"];
    const [dd, setDd] = React.useState(null);   // open field dropdown: "speed" | "level" | null
    const [phase, setPhase] = React.useState("source");   // source | progress
    const [done, setDone] = React.useState(0);
    const [pct, setPct] = React.useState(0);
    const type = detect(src);

    React.useEffect(() => {
      if (phase !== "progress") return;
      let step = 0, p = 0;
      const id = setInterval(() => {
        p += 4 + Math.random() * 6; setPct(Math.min(100, Math.round(p)));
        const ns = Math.min(D.genSteps.length, Math.floor((p / 100) * D.genSteps.length) + 1);
        step = ns; setDone(ns);
        if (p >= 100) { clearInterval(id); setTimeout(() => { e.closeOverlay(); e.flash("Walkthrough ready"); e.gotoChapter(0); }, 700); }
      }, 520);
      return () => clearInterval(id);
    }, [phase]);

    return (
      <Scrim onClose={e.closeOverlay} blur center>
        <div className="modal modal--compose" onPointerDown={(ev) => ev.stopPropagation()}>
          <ModalHead title={phase === "source" ? "New walkthrough" : "Generating…"} sub={phase === "source" ? "Paste a source — Nutshell narrates it" : `${pct}% · ~${Math.max(0, 18 - Math.round(pct / 6))}s left`} onClose={e.closeOverlay} icon="plus" />
          {phase === "source" ? (
            <React.Fragment>
              <div className="src-area">
                <textarea value={src} onChange={(ev) => setSrc(ev.target.value)} placeholder="Paste a Mermaid diagram, a YouTube link, or notes…" />
                <span className="detect-badge">Detected: {type}</span>
              </div>
              <div className="compose-fields">
                <div className={"ddfield" + (dd === "speed" ? " open" : "")}>
                  <button type="button" className="popbtn ddfield-trig" onClick={() => setDd(dd === "speed" ? null : "speed")}>
                    <span>Intelligence</span><b>{SPEED[speed]}</b><Icon name="chevronDown" size={12} />
                  </button>
                  {dd === "speed" && (
                    <div className="ddmenu">
                      {SPEED.map((t, i) => (
                        <button key={t} type="button" className={"ddmenu-item" + (i === speed ? " on" : "")} onClick={() => { setSpeed(i); setDd(null); }}>
                          <b>{t}</b><span>{SPEED_D[i]}</span><i className="ddtick" />
                        </button>
                      ))}
                    </div>
                  )}
                </div>
                <div className={"ddfield" + (dd === "level" ? " open" : "")}>
                  <button type="button" className="popbtn ddfield-trig" onClick={() => setDd(dd === "level" ? null : "level")}>
                    <span>Difficulty</span><b>{LEVEL[level]}</b><Icon name="chevronDown" size={12} />
                  </button>
                  {dd === "level" && (
                    <div className="ddmenu">
                      {LEVEL.map((t, i) => (
                        <button key={t} type="button" className={"ddmenu-item" + (i === level ? " on" : "")} onClick={() => { setLevel(i); setDd(null); }}>
                          <b>{t}</b><span>{LEVEL_D[i]}</span><i className="ddtick" />
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
              <button className={"adv-toggle" + (adv ? " adv-toggle--open" : "")} onClick={() => setAdv((a) => !a)} aria-expanded={adv}>
                <Icon name="chevronRight" size={13} /><span>Advanced</span>
              </button>
              {adv && (
                <div className="compose-grid">
                  {[["Voice", "Ardbeg"], ["Accent", "Neutral"], ["Model", "Sonnet"], ["Effort", "High"]].map(([k, v]) => (
                    <button key={k} className="popbtn"><span>{k}</span><b>{v}</b><Icon name="chevronDown" size={12} /></button>
                  ))}
                  <button className="popbtn"><span>Pace</span><b>0.9</b><Icon name="chevronDown" size={12} /></button>
                  <button className="popbtn"><span>Chapters</span><b>Auto</b><Icon name="chevronDown" size={12} /></button>
                </div>
              )}
              <div className="modal-foot"><span className="modal-status" /><Pill variant="sec" icon="wave" onClick={() => setPhase("progress")}>Audio narration</Pill><Pill variant="pri" icon="activity" onClick={() => setPhase("progress")}>Visual narration</Pill></div>
            </React.Fragment>
          ) : (
            <div className="prog">
              <div className="prog-hero"><div className="prog-pct">{pct}%</div><div className="ptrack"><i style={{ width: pct + "%" }} /></div></div>
              {D.genSteps.map((s, i) => {
                const st = i < done - 1 || pct >= 100 ? "done" : i === done - 1 ? "act" : "wait";
                return (
                  <div key={s.key} className={"pstep pstep--" + st}>
                    <span className="pdot">{st === "done" ? <Icon name="check" size={11} /> : st === "act" ? <Icon name="dot" size={9} /> : i + 1}</span>
                    <div className="pstep-txt"><b>{s.label}</b><span>{s.note}</span></div>
                    <span className="pstep-stat">{st === "done" ? "Done" : st === "act" ? "Working" : "Waiting"}</span>
                  </div>
                );
              })}
              <div className="modal-foot"><Pill icon="x" onClick={e.closeOverlay}>Cancel</Pill></div>
            </div>
          )}
        </div>
      </Scrim>
    );
  }

  // =========================================================================
  //  YOUTUBE IMPORT  (premium plugin) — standalone browser → generation
  // =========================================================================
  function ProgSteps({ pct, done }) {
    return (
      <React.Fragment>
        <div className="prog-hero"><div className="prog-pct">{pct}%</div><div className="ptrack"><i style={{ width: pct + "%" }} /></div></div>
        {D.genSteps.map((s, i) => {
          const st = i < done - 1 || pct >= 100 ? "done" : i === done - 1 ? "act" : "wait";
          return (
            <div key={s.key} className={"pstep pstep--" + st}>
              <span className="pdot">{st === "done" ? <Icon name="check" size={11} /> : st === "act" ? <Icon name="dot" size={9} /> : i + 1}</span>
              <div className="pstep-txt"><b>{s.label}</b><span>{s.note}</span></div>
              <span className="pstep-stat">{st === "done" ? "Done" : st === "act" ? "Working" : "Waiting"}</span>
            </div>
          );
        })}
      </React.Fragment>
    );
  }

  const avStyle = (c) => ({ background: `radial-gradient(circle at 34% 30%, color-mix(in oklab, ${c}, #fff 30%), ${c})` });

  function YouTubeImportModal() {
    const e = useEngine();
    const Y = D.youtube;
    const [phase, setPhase] = React.useState("browse");      // browse | switch | progress
    const [plOpen, setPlOpen] = React.useState(false);
    const [acctMenu, setAcctMenu] = React.useState(false);
    const [playlistId, setPlaylistId] = React.useState(Y.playlists[0].id);
    const [showAll, setShowAll] = React.useState(false);
    const [picked, setPicked] = React.useState(null);
    const [pct, setPct] = React.useState(0);
    const [done, setDone] = React.useState(0);

    const profile = Y.profiles.find((p) => p.id === e.ytProfile) || Y.profiles[0];
    const playlist = Y.playlists.find((p) => p.id === playlistId) || Y.playlists[0];
    const vids = Y.videos.slice(0, showAll ? 10 : 5);

    React.useEffect(() => {
      if (phase !== "progress") return;
      let p = 0;
      const id = setInterval(() => {
        p += 4 + Math.random() * 6; setPct(Math.min(100, Math.round(p)));
        setDone(Math.min(D.genSteps.length, Math.floor((p / 100) * D.genSteps.length) + 1));
        if (p >= 100) { clearInterval(id); setTimeout(() => { e.closeOverlay(); e.flash("Walkthrough ready"); e.gotoChapter(0); }, 700); }
      }, 520);
      return () => clearInterval(id);
    }, [phase]);

    const ytHead = (
      <div className="mhead">
        <span className="mhead-ic mhead-ic--yt"><Icon name="youtube" size={18} /></span>
        <div>
          <div className="mhead-t">Import from YouTube <span className="pro pro--sm">Pro</span></div>
          <div className="mhead-s">{phase === "switch" ? "Choose a channel" : phase === "progress" ? "Generating your walkthrough…" : "Pick a video to turn into a narrated walkthrough"}</div>
        </div>
        <button className="ib mhead-x" onClick={e.closeOverlay} aria-label="Close"><Icon name="x" size={16} /></button>
      </div>
    );

    return (
      <Scrim onClose={e.closeOverlay} blur center>
        <div className="modal modal--yt" onPointerDown={(ev) => { ev.stopPropagation(); setPlOpen(false); setAcctMenu(false); }}>
          {ytHead}

          {!e.ytConnected ? (
            <div className="yt-connect">
              <span className="yt-connect-ic"><Icon name="youtube" size={26} /></span>
              <b>Connect YouTube</b>
              <span>Sign in to browse your playlists. Read-only access — Nutshell never posts or edits.</span>
              <button className="yt-connect-btn" onClick={() => e.setYtConnected(true)}><Icon name="youtube" size={15} />Connect YouTube</button>
            </div>
          ) : phase === "progress" ? (
            <div className="prog">
              <div className="yt-genfrom">
                <span className="yt-thumb yt-thumb--row"><i className="yt-dur">{picked.dur}</i></span>
                <div className="yt-genfrom-tx"><b>{picked.title}</b><span>{picked.channel} · pulling captions</span></div>
              </div>
              <ProgSteps pct={pct} done={done} />
              <div className="modal-foot"><Pill icon="x" onClick={e.closeOverlay}>Cancel</Pill></div>
            </div>
          ) : phase === "switch" ? (
            <div className="yt-switch">
              {Y.profiles.map((p) => (
                <button key={p.id} className={"yt-prow" + (p.id === e.ytProfile ? " on" : "")} onClick={() => { e.setYtProfile(p.id); setPhase("browse"); }}>
                  <span className="yt-av" style={avStyle(p.color)}>{p.initials}</span>
                  <div className="yt-prow-meta"><b>{p.name}</b><span>{p.playlists} playlists</span></div>
                  {p.id === e.ytProfile && <Icon name="check" size={16} />}
                </button>
              ))}
              <button className="yt-switch-other" onClick={() => { e.setYtConnected(false); setPhase("browse"); }}>
                <Icon name="plus" size={14} />Use a different account
              </button>
            </div>
          ) : (
            <React.Fragment>
              <div className="yt-acct">
                <span className="yt-av" style={avStyle(profile.color)}>{profile.initials}</span>
                <div className="yt-id"><b><i className="yt-ok" />{profile.name}</b><span>Connected · read-only access</span></div>
                <div className="yt-acct-act">
                  <div className={"ddfield" + (plOpen ? " open" : "")} onPointerDown={(ev) => ev.stopPropagation()}>
                    <button type="button" className="popbtn ddfield-trig" onClick={() => { setPlOpen((o) => !o); setAcctMenu(false); }}>
                      <span>Playlist</span><b>{playlist.name}</b><Icon name="chevronDown" size={12} />
                    </button>
                    {plOpen && (
                      <div className="ddmenu">
                        {Y.playlists.map((p) => (
                          <button key={p.id} type="button" className={"ddmenu-item" + (p.id === playlistId ? " on" : "")} onClick={() => { setPlaylistId(p.id); setPlOpen(false); }}>
                            <b>{p.name}</b><span>{p.count} videos</span><i className="ddtick" />
                          </button>
                        ))}
                      </div>
                    )}
                  </div>
                  <button className="ib" title="Refresh" onClick={() => e.flash("Refreshed playlists")}><Icon name="refresh" size={15} /></button>
                  <div className="yt-acctmenu-wrap" onPointerDown={(ev) => ev.stopPropagation()}>
                    <button className={"ib" + (acctMenu ? " ib--on" : "")} title="YouTube account" onClick={() => { setAcctMenu((o) => !o); setPlOpen(false); }}><Icon name="settings" size={15} /></button>
                    {acctMenu && (
                      <div className="yt-acctmenu">
                        <button className="yt-mrow" onClick={() => { setAcctMenu(false); e.flash("Refreshed"); }}><Icon name="refresh" size={14} />Refresh</button>
                        <button className="yt-mrow" onClick={() => { setAcctMenu(false); setPhase("switch"); }}><Icon name="collection" size={14} />Switch profile…</button>
                        <button className="yt-mrow" onClick={() => { setAcctMenu(false); e.setSettingsTab("plugins"); e.openOverlay("settings"); }}><Icon name="settings" size={14} />YouTube settings</button>
                        <div className="yt-msep" />
                        <button className="yt-mrow yt-mrow--danger" onClick={() => { setAcctMenu(false); e.setYtConnected(false); }}><Icon name="eject" size={14} />Disconnect</button>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              <div className="yt-grid">
                {vids.map((v, i) => (
                  <button key={i} className="yt-card" onClick={() => { setPicked(v); setPhase("progress"); }}>
                    <span className="yt-thumb"><i className="yt-dur">{v.dur}</i></span>
                    <span className="yt-card-go"><Icon name="activity" size={12} />Generate</span>
                    <span className="yt-card-t">{v.title}</span>
                    <span className="yt-card-s">{v.channel} · {v.date}</span>
                  </button>
                ))}
              </div>

              <div className="yt-pager">
                <span className="yt-pager-info">{showAll ? "Showing all 10" : "Showing 5 of 10"} · newest first</span>
                <div className="yt-pager-pg">
                  <button className="yt-pg" disabled><Icon name="chevronLeft" size={14} /></button>
                  <button className="yt-pg"><Icon name="chevronRight" size={14} /></button>
                </div>
                <button className="yt-showmore" onClick={() => setShowAll((s) => !s)}>{showAll ? "Show fewer" : "Show 10 videos"}</button>
              </div>
              <div className="yt-foot"><span className="yt-foot-dot" />Clicking a video starts generation immediately — output lands in your Library.</div>
            </React.Fragment>
          )}
        </div>
      </Scrim>
    );
  }

  // =========================================================================
  //  PLUGIN PAYWALL  (unlock sheet for the YouTube Import plugin)
  // =========================================================================
  function PluginPaywall() {
    const e = useEngine();
    return (
      <Scrim onClose={e.closeOverlay} blur center>
        <div className="modal modal--paywall" onPointerDown={(ev) => ev.stopPropagation()}>
          <button className="ib mhead-x paywall-x" onClick={e.closeOverlay} aria-label="Close"><Icon name="x" size={16} /></button>
          <div className="paywall-crest"><Icon name="youtube" size={26} /><span className="paywall-lock"><Icon name="lock" size={12} /></span></div>
          <h3 className="paywall-t">Import from YouTube</h3>
          <p className="paywall-lede">A premium plugin that turns videos from your playlists into narrated diagrams.</p>
          <ul className="paywall-feat">
            <li><span className="paywall-tick"><Icon name="check" size={11} /></span>Browse playlists from your connected channel</li>
            <li><span className="paywall-tick"><Icon name="check" size={11} /></span>One click → captions pulled, diagram &amp; narration generated</li>
            <li><span className="paywall-tick"><Icon name="check" size={11} /></span>Private &amp; deleted videos filtered, newest first</li>
          </ul>
          <button className="paywall-buy" onClick={() => { e.unlockYouTube(); e.closeOverlay(); e.flash("YouTube Import enabled — find it in your Library"); }}>
            <Icon name="lock" size={13} />Unlock for {D.youtube.price} — one time
          </button>
          <p className="paywall-fine">One-time purchase · manage in Settings › Plugins</p>
          <button className="paywall-restore" onClick={() => e.flash("No purchases to restore")}>Restore purchase</button>
        </div>
      </Scrim>
    );
  }

  // =========================================================================
  //  SETTINGS
  // =========================================================================
  function SettingsBody() {
    const e = useEngine();
    const [tab, setTab] = React.useState(e.settingsTab || "general");
    const [openPlug, setOpenPlug] = React.useState(e.settingsTab === "plugins" ? "youtube" : null);
    const [mermaidOn, setMermaidOn] = React.useState(true);
    React.useEffect(() => () => e.setSettingsTab("general"), []); // reset deep-link when closed

    const statusEl = (p) => {
      if (p.id === "youtube") return e.ytOwned
        ? <span className="plug-status">{e.ytEnabled ? <React.Fragment><i className="plug-on" />On</React.Fragment> : "Off"}</span>
        : <span className="pro pro--sm">Pro</span>;
      if (p.state === "included") return <span className="plug-status">{mermaidOn ? <React.Fragment><i className="plug-on" />On</React.Fragment> : "Off"}</span>;
      return <span className="plug-status plug-status--soon">Soon</span>;
    };
    const actionEl = (p) => {
      if (p.id === "youtube") return e.ytOwned
        ? <button className={"switch" + (e.ytEnabled ? " switch--on" : "")} onClick={() => e.setYtEnabled((v) => !v)} aria-label="Toggle YouTube Import"><i /></button>
        : <React.Fragment><button className="unlock-btn" onClick={() => e.openOverlay("paywall")}><Icon name="lock" size={12} />Unlock · {D.youtube.price}</button><span className="plug-note">One-time purchase</span></React.Fragment>;
      if (p.state === "included") return <React.Fragment><button className={"switch" + (mermaidOn ? " switch--on" : "")} onClick={() => setMermaidOn((v) => !v)} aria-label="Toggle Mermaid Live"><i /></button><span className="plug-note">Included with Nutshell</span></React.Fragment>;
      return <button className="plug-notify" onClick={() => e.flash("We’ll let you know when " + p.name + " ships")}>Notify me</button>;
    };

    return (
      <Scrim onClose={e.closeOverlay} blur center>
        <div className="modal modal--set" onPointerDown={(ev) => ev.stopPropagation()}>
          <ModalHead title="Settings" onClose={e.closeOverlay} icon="settings" />
          <div className="set-tabs">
            <button className={tab === "general" ? "on" : ""} onClick={() => setTab("general")}>General</button>
            <button className={tab === "plugins" ? "on" : ""} onClick={() => setTab("plugins")}>Plugins</button>
          </div>

          <div className="set-content">
            {tab === "general" ? (
              <React.Fragment>
                <div className="set-group">
                  <div className="set-row"><div><b>Engine</b><span>mac-mini.local:8080</span></div>
                    <div className="set-health"><i className={"dot " + (e.engineOnline ? "dot--ok" : "dot--off")} />{e.engineOnline ? "Online" : "Offline"}
                      <button className={"switch" + (e.engineOnline ? " switch--on" : "")} onClick={() => e.setEngineOnline((o) => !o)} aria-label="Toggle engine"><i /></button></div>
                  </div>
                </div>
                <div className="set-group">
                  {[["Default audience", e.audience], ["Voice", "Ardbeg"], ["Max chapters", "Auto"], ["Renderer", "Mermaid"]].map(([k, v]) => (
                    <button key={k} className="set-row set-row--btn"><div><b>{k}</b></div><span className="set-val">{v}<Icon name="chevronDown" size={12} /></span></button>
                  ))}
                </div>
                <div className="set-group set-group--appear">
                  <span>Appearance</span>
                  <div className="seg">{["light", "dark"].map((t) => <button key={t} className={e.theme === t ? "on" : ""} onClick={() => e.setTheme(t)}>{t[0].toUpperCase() + t.slice(1)}</button>)}</div>
                </div>
              </React.Fragment>
            ) : (
              <div className="plug-list">
                {D.plugins.map((p) => {
                  const open = openPlug === p.id;
                  const tint = `color-mix(in oklab, ${p.tone}, transparent 88%)`;
                  return (
                    <div key={p.id} className={"plug-item" + (open ? " open" : "") + (p.state === "soon" ? " plug-item--soon" : "")}>
                      <button className="plug-row" onClick={() => setOpenPlug(open ? null : p.id)} aria-expanded={open}>
                        <span className="plug-ic" style={{ background: tint, color: p.tone }}><Icon name={p.icon} size={16} /></span>
                        <span className="plug-name">{p.name}</span>
                        {statusEl(p)}
                        <Icon name="chevronDown" size={14} className="plug-chev" />
                      </button>
                      {open && (
                        <div className="plug-detail">
                          <p>{p.desc}</p>
                          <div className="plug-actions">{actionEl(p)}</div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          <div className="set-ver">Nutshell 1.0 (build 142) · macOS 26 Tahoe</div>
        </div>
      </Scrim>
    );
  }

  // =========================================================================
  //  COMMAND PALETTE (concept 3)
  // =========================================================================
  function CommandPalette() {
    const e = useEngine();
    const [q, setQ] = React.useState("");
    const cmds = [
      { ic: "plus", label: "New walkthrough", kbd: "⌘N", go: () => e.openOverlay("compose") },
      { ic: "chat", label: "Ask about this run", go: () => { e.closeOverlay(); e.setChatOpen(true); } },
      { ic: "sparkles", label: "Gold nuggets", go: () => e.openOverlay("nuggets") },
      { ic: "wand", label: "Change audience…", go: () => e.openOverlay("audience") },
      { ic: "library", label: "Open Library", kbd: "⌘L", go: () => e.openOverlay("library") },
      { ic: "youtube", label: "View original source", go: () => e.openOverlay("source") },
      { ic: "share", label: "Share walkthrough", go: () => e.flash("Link copied") },
      { ic: "settings", label: "Settings…", kbd: "⌘,", go: () => e.openOverlay("settings") },
    ].filter((c) => c.label.toLowerCase().includes(q.toLowerCase()));
    return (
      <Scrim onClose={e.closeOverlay} blur>
        <div className="palette glassT" onPointerDown={(ev) => ev.stopPropagation()}>
          <div className="pal-field"><Icon name="sparkles" size={16} /><input autoFocus placeholder="Type a command or search…" value={q} onChange={(ev) => setQ(ev.target.value)} /></div>
          <div className="pal-list">
            {cmds.map((c, i) => (
              <button key={i} className={"pal-row" + (i === 0 ? " pal-row--sel" : "")} onClick={c.go}>
                <Icon name={c.ic} size={15} /><span>{c.label}</span>{c.kbd && <kbd>{c.kbd}</kbd>}
              </button>
            ))}
          </div>
        </div>
      </Scrim>
    );
  }

  // ---- dispatcher for modal-style overlays --------------------------------
  function OverlayHost() {
    const e = useEngine();
    switch (e.overlay) {
      case "audience": return <AudienceModal />;
      case "compose": return <ComposeBody />;
      case "youtube": return <YouTubeImportModal />;
      case "paywall": return <PluginPaywall />;
      case "settings": return <SettingsBody />;
      case "sourceFull": return <SourceFull />;
      case "palette": return <CommandPalette />;
      default: return null;
    }
  }

  window.SHELL_OVERLAYS = { Scrim, ModalHead, ChatBody, NuggetsBody, SourceBody, LibraryBody, OverlayHost, CommandPalette, YouTubeImportModal, PluginPaywall };
})();
