// ss-sheet.jsx: the one popup frame for the whole site (2026-11-24).
// Spec: docs/popup-review/SPEC-ONE-SHEET.md. Look: public/ss-sheet.css.
// No build step. Plain Babel script, same pattern as card-popup.jsx.
//
// LOAD (after React, ReactDOM and Babel; before the page script):
//   <link rel="stylesheet" href="/ss-sheet.css?v=1" />          (after styles.css)
//   <script type="text/babel" src="/ss-sheet.jsx?v=1"></script>
//   <script type="text/babel" src="/your-page.jsx"></script>
//
// EXPOSES window.ssSheet = { Sheet, Actions, Ask, useAsk, CardSheet, lockScroll }
//   const { Sheet, Actions, Ask, useAsk, CardSheet, lockScroll } = window.ssSheet;
//
// Sheet: bottom sheet under 700px, centred dialog at 700px+. Renders into
// document.body (a portal). It does not close itself: onClose is the request,
// the parent stops rendering it. Escape, backdrop, the close button and Done
// all call onClose. Focus goes in on open, stays inside, and returns on close.
// The page behind is locked (counted, so stacked sheets unlock once).
//   {open && (
//     <Sheet title="Move card" onClose={() => setOpen(false)}
//       foot={<Actions primary={{ label: "Move it here", onClick: move, busy }} done="Cancel" />}>
//       <label className="ss-field"><span className="ss-label">To</span>
//         <select className="ss-select">...</select></label>
//     </Sheet>
//   )}
//   Props: title (no title = no head and no close button; Done closes),
//   onClose, size 'default' | 'wide' (640px) | 'card', foot (pinned node),
//   children, labelledBy, label (aria-label when there is no title),
//   className, onKey(e) (return true to take a key before Escape handling).
//
// Actions: the vertical stack in the fixed order. Every item is
//   { label, onClick, href?, target?, rel?, disabled?, busy?, danger?, id?, ariaLabel?, title?, key? }.
//   <Actions primary={{ label: "Buy at Card Kingdom $4.99", href: url, target: "_blank" }}
//            secondary={[{ label: "Own this", onClick: own }, { label: "Want it", onClick: want }]}
//            minor={[{ label: "Remove from this version", onClick: rm, danger: true }]}
//            done />
//   primary = the ONE filled pill; secondary = outline pills; minor = plain
//   text (danger = red text); done = outline pill last. done: true -> "Done",
//   a string -> that label, an item -> as given; with no onClick it closes the
//   sheet it sits in. Falsy entries in the arrays are skipped. Nothing at all
//   -> renders null. primary with danger:true renders as an outline pill in red.
//
// useAsk: a drop-in for confirm(). Inside an open sheet the question takes the
// foot of the top sheet; with no sheet open it comes up as its own small sheet.
//   const ask = useAsk();
//   if (!(await ask({ question: "Remove Sol Ring?", yes: "Remove", no: "Keep", danger: true }))) return;
//   ask("Add another copy?") works too. alert() replacement: ask({ question, yes: "OK", no: null }).
//   Escape, backdrop and the close button answer false. Safe answer is first and focused.
// Ask: the same question block, for drawing one yourself:
//   <Ask question="Remove it?" yes="Remove" no="Keep" danger onAnswer={(yes) => ...} />
//
// CardSheet: the one card layout. index is 0-based ("3 of 12" shows when total > 1).
//   <CardSheet card={{ name: "Sol Ring" }} image={url} status="In Atraxa deck"
//     onPrev={i > 0 ? () => setI(i - 1) : null} onNext={...} index={i} total={list.length}
//     clip={{ on: clipped, onToggle: toggleClip }}
//     actions={{ primary: {...}, secondary: [...], minor: [...] }}   (Done is added in the foot; done:false hides it)
//     sections={[{ title: "Where your copies live", content: <List/> }]}  (closed unless open:true)
//     onClose={close}>
//     {optional extras between the status line and the buttons, such as a stepper}
//   </CardSheet>
//   status: a string or node, one line, quiet grey. Wrap in
//   <span className="ss-sheet-card-status--accent"> for the orange tone. image: URL or node.
//   Arrow keys and a sideways swipe on the image walk previous / next.
//
// lockScroll(): const unlock = lockScroll(); ... unlock();  counted with every sheet
// (React and vanilla share one counter), the page scrolls again only at zero.
(() => {
const { useState, useEffect, useRef, useCallback, useContext } = React;

// ── Shared core (identical copy in ss-sheet-vanilla.js; whichever loads first wins).
function ssSheetCore() {
  if (window.__ssSheetCore) return window.__ssSheetCore;
  var stack = [];
  var locks = 0;
  var saved = null;
  function lock() {
    if (locks === 0) {
      var de = document.documentElement, b = document.body;
      var sbw = Math.max(0, window.innerWidth - de.clientWidth);
      saved = { h: de.style.overflow, b: b.style.overflow, pr: b.style.paddingRight };
      if (sbw > 0) b.style.paddingRight = ((parseFloat(getComputedStyle(b).paddingRight) || 0) + sbw) + "px";
      de.style.overflow = "hidden";
      b.style.overflow = "hidden";
    }
    locks += 1;
    var done = false;
    return function unlock() {
      if (done) return;
      done = true;
      locks = Math.max(0, locks - 1);
      if (locks === 0 && saved) {
        document.documentElement.style.overflow = saved.h;
        document.body.style.overflow = saved.b;
        document.body.style.paddingRight = saved.pr;
        saved = null;
      }
    };
  }
  function push(entry) { stack.push(entry); return stack.length - 1; }
  function remove(entry) { var i = stack.indexOf(entry); if (i >= 0) stack.splice(i, 1); }
  function top() { return stack.length ? stack[stack.length - 1] : null; }
  var SEL = 'a[href],button:not([disabled]),input:not([disabled]):not([type="hidden"]),select:not([disabled]),textarea:not([disabled]),summary,[tabindex]:not([tabindex="-1"])';
  function focusables(root) {
    return Array.prototype.filter.call(root.querySelectorAll(SEL), function (el) {
      if (el.closest && el.closest("[inert]")) return false;
      var r = el.getClientRects();
      return r && r.length > 0;
    });
  }
  window.addEventListener("keydown", function (e) {
    var t = top();
    if (!t || !t.el) return;
    if (e.key === "Tab") {
      var els = focusables(t.el);
      var a = document.activeElement;
      if (!els.length) { e.preventDefault(); try { t.el.focus(); } catch (x) { /* ignore */ } return; }
      var first = els[0], last = els[els.length - 1];
      if (!t.el.contains(a)) { e.preventDefault(); (e.shiftKey ? last : first).focus(); return; }
      if (e.shiftKey && (a === first || a === t.el)) { e.preventDefault(); last.focus(); }
      else if (!e.shiftKey && a === last) { e.preventDefault(); first.focus(); }
      return;
    }
    if (e.defaultPrevented) return;
    if (t.onKey) t.onKey(e);
  });
  // The page behind never scrolls: a drag outside a sheet body does nothing.
  document.addEventListener("touchmove", function (e) {
    if (!stack.length) return;
    var tg = e.target;
    if (tg && tg.closest && tg.closest(".ss-sheet-body, .ss-sheet-scroll")) return;
    if (e.cancelable) e.preventDefault();
  }, { passive: false });
  window.__ssSheetCore = { lock: lock, push: push, remove: remove, top: top, stack: stack, focusables: focusables, version: 1 };
  return window.__ssSheetCore;
}
const core = ssSheetCore();

let uid = 0;
const nextId = (p) => "ss-sheet-" + p + "-" + (++uid);
const isTyping = (e) => {
  const t = e.target;
  if (!t) return false;
  const tg = t.tagName;
  return tg === "INPUT" || tg === "TEXTAREA" || tg === "SELECT" || !!t.isContentEditable;
};
const focusQuiet = (el) => { try { if (el && el.focus) el.focus({ preventScroll: true }); } catch (e) { /* ignore */ } };
const normAsk = (o) => (typeof o === "string" ? { question: o } : Object.assign({}, o || {}));

const SheetCtx = React.createContext(null);

function XIcon() {
  return (
    <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
      <path d="M3.5 3.5l9 9M12.5 3.5l-9 9" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" fill="none" />
    </svg>
  );
}
function ClipSvg() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" />
    </svg>
  );
}

// ── Sheet
function Sheet({ title, onClose, size, foot, children, labelledBy, label, className, onKey }) {
  const panelRef = useRef(null);
  const bodyRef = useRef(null);
  const cb = useRef({});
  cb.current = { onClose, onKey };
  const [askQ, setAskQ] = useState(null);
  const askRef = useRef(null);
  const [depth] = useState(() => core.stack.length);
  const titleId = useRef(null);
  if (!titleId.current) titleId.current = nextId("t");
  const downOnBack = useRef(false);
  // What had focus when the sheet first rendered (before any child took it).
  const [opener] = useState(() => document.activeElement);
  // If the opener sat inside another sheet that closes first (a menu row that opens
  // this sheet), focus goes back to what opened that sheet instead of the page body.
  const [fallback] = useState(() => {
    const t = core.top();
    const a = document.activeElement;
    return t && t.el && a && t.el.contains(a) ? (t.opener || t.fallback || null) : null;
  });
  const entryRef = useRef(null);

  const close = useCallback(() => {
    // Marked closing for this tick: a question asked right after a close request
    // opens as its own sheet instead of attaching to this one on its way out.
    const en = entryRef.current;
    if (en) { en.closing = true; setTimeout(() => { en.closing = false; }, 0); }
    if (cb.current.onClose) cb.current.onClose();
  }, []);
  const requestClose = useCallback(() => {
    if (askRef.current) { askRef.current.answer(false); return; }
    close();
  }, [close]);

  useEffect(() => {
    const unlock = core.lock();
    const entry = {
      el: panelRef.current,
      opener: opener && opener !== document.body ? opener : null,
      fallback,
      onKey: (e) => {
        if (askRef.current) {
          if (e.key === "Escape") { e.preventDefault(); askRef.current.answer(false); }
          return;
        }
        if (cb.current.onKey && cb.current.onKey(e)) return;
        if (e.key === "Escape") { e.preventDefault(); close(); }
      },
      close,
      ask: (opts) => new Promise((resolve) => {
        if (askRef.current) askRef.current.answer(false);
        const before = document.activeElement;
        const q = { opts: normAsk(opts), done: false };
        q.answer = (v) => {
          if (q.done) return;
          q.done = true;
          if (askRef.current === q) { askRef.current = null; setAskQ(null); }
          resolve(!!v);
          requestAnimationFrame(() => {
            const p = panelRef.current;
            if (!p || !document.contains(p)) return;
            if (before && document.contains(before) && p.contains(before)) focusQuiet(before);
            else focusQuiet(p);
          });
        };
        askRef.current = q;
        setAskQ(q);
      }),
    };
    entryRef.current = entry;
    core.push(entry);
    // Focus moves in, unless a child (a question's safe answer) already took it.
    if (!panelRef.current.contains(document.activeElement)) focusQuiet(panelRef.current);
    return () => {
      core.remove(entry);
      unlock();
      if (askRef.current) askRef.current.answer(false);
      const a = document.activeElement;
      if (!a || a === document.body || !document.contains(a)) {
        if (opener && opener !== document.body && document.contains(opener)) focusQuiet(opener);
        else if (fallback && document.contains(fallback)) focusQuiet(fallback);
      }
    };
  }, []);

  useEffect(() => { if (bodyRef.current) bodyRef.current.inert = !!askQ; }, [askQ]);

  const hasTitle = title != null && title !== false && title !== "";
  const sz = size === "wide" || size === "card" ? " ss-sheet--" + size : "";
  const ctx = useRef(null);
  if (!ctx.current) ctx.current = { close: () => close() };

  const node = (
    <div className="ss-sheet-back" style={{ zIndex: "calc(var(--ss-sheet-z, 100) + " + depth * 2 + ")" }}
      onPointerDown={(e) => { downOnBack.current = e.target === e.currentTarget; }}
      onClick={(e) => { if (e.target === e.currentTarget && downOnBack.current) requestClose(); downOnBack.current = false; }}>
      <div ref={panelRef} className={"ss-sheet" + sz + (className ? " " + className : "")} role="dialog" aria-modal="true" tabIndex={-1}
        aria-labelledby={labelledBy || (hasTitle ? titleId.current : undefined)}
        aria-label={!labelledBy && !hasTitle ? (label || "Dialog") : undefined}>
        <SheetCtx.Provider value={ctx.current}>
          {hasTitle && (
            <div className="ss-sheet-head">
              <h2 className="ss-sheet-title" id={titleId.current}>{title}</h2>
              <button type="button" className="ss-sheet-x" aria-label="Close" onClick={requestClose}><XIcon /></button>
            </div>
          )}
          <div ref={bodyRef} className={"ss-sheet-body" + (askQ ? " is-asking" : "")}>{children}</div>
          {askQ ? (
            <div className="ss-sheet-foot ss-sheet-foot--ask"><Ask {...askQ.opts} onAnswer={askQ.answer} /></div>
          ) : foot ? (
            <div className="ss-sheet-foot">{foot}</div>
          ) : null}
        </SheetCtx.Provider>
      </div>
    </div>
  );
  return ReactDOM.createPortal(node, document.body);
}

// ── Actions
function ActBtn({ item, cls }) {
  const dis = !!(item.disabled || item.busy);
  const c = "ss-sheet-btn " + cls + (item.busy ? " is-busy" : "") + (item.className ? " " + item.className : "");
  if (item.href) {
    return (
      <a className={c} href={dis ? undefined : item.href} target={item.target} id={item.id} title={item.title}
        rel={item.rel || (item.target === "_blank" ? "noopener" : undefined)}
        aria-disabled={dis || undefined} aria-busy={item.busy || undefined} aria-label={item.ariaLabel}
        onClick={dis ? (e) => e.preventDefault() : item.onClick}>{item.label}</a>
    );
  }
  return (
    <button type="button" className={c} disabled={dis} id={item.id} title={item.title}
      aria-busy={item.busy || undefined} aria-label={item.ariaLabel} onClick={item.onClick}>{item.label}</button>
  );
}

function Actions({ primary, secondary, minor, done, className }) {
  const ctx = useContext(SheetCtx);
  const sec = (secondary || []).filter(Boolean);
  const min = (minor || []).filter(Boolean);
  let d = null;
  if (done) {
    d = (typeof done === "object") ? Object.assign({}, done) : { label: typeof done === "string" ? done : "Done" };
    if (!d.label) d.label = "Done";
    if (!d.onClick && !d.href) d.onClick = () => { if (ctx) ctx.close(); };
  }
  if (!primary && !sec.length && !min.length && !d) return null;
  return (
    <div className={"ss-sheet-acts" + (className ? " " + className : "")}>
      {primary && <ActBtn item={primary} cls={primary.danger ? "ss-sheet-btn--ghost ss-sheet-btn--danger" : "ss-sheet-btn--primary"} />}
      {sec.map((it, i) => <ActBtn key={it.key || "s" + i} item={it} cls={"ss-sheet-btn--ghost" + (it.danger ? " ss-sheet-btn--danger" : "")} />)}
      {min.map((it, i) => <ActBtn key={it.key || "m" + i} item={it} cls={"ss-sheet-btn--quiet" + (it.danger ? " ss-sheet-btn--danger" : "")} />)}
      {d && <ActBtn item={d} cls="ss-sheet-btn--ghost ss-sheet-btn--done" />}
    </div>
  );
}

// ── Ask
function Ask({ question, detail, yes, no, danger, onAnswer }) {
  const firstRef = useRef(null);
  const qid = useRef(null);
  if (!qid.current) qid.current = nextId("q");
  useEffect(() => { focusQuiet(firstRef.current); }, [question]);
  const yesLabel = yes == null ? "Yes" : yes;
  const noLabel = no === undefined ? "Cancel" : no;
  const answer = (v) => { if (onAnswer) onAnswer(v); };
  return (
    <div className="ss-sheet-ask" role="group" aria-labelledby={qid.current}>
      <p className="ss-sheet-ask-q" id={qid.current}>{question}</p>
      {detail ? <p className="ss-sheet-ask-detail">{detail}</p> : null}
      <div className="ss-sheet-acts">
        {noLabel !== null && noLabel !== false ? (
          <React.Fragment>
            <button ref={firstRef} type="button" className="ss-sheet-btn ss-sheet-btn--ghost" data-ss-answer="no" onClick={() => answer(false)}>{noLabel}</button>
            <button type="button" className={"ss-sheet-btn " + (danger ? "ss-sheet-btn--quiet ss-sheet-btn--danger" : "ss-sheet-btn--primary")}
              data-ss-answer="yes" onClick={() => answer(true)}>{yesLabel}</button>
          </React.Fragment>
        ) : (
          <button ref={firstRef} type="button" className="ss-sheet-btn ss-sheet-btn--ghost" data-ss-answer="yes" onClick={() => answer(true)}>{yesLabel}</button>
        )}
      </div>
    </div>
  );
}

function StandaloneAsk({ opts, onAnswer }) {
  return (
    <Sheet label={typeof opts.question === "string" ? opts.question : "Question"} onClose={() => onAnswer(false)}>
      <Ask {...opts} onAnswer={onAnswer} />
    </Sheet>
  );
}
function standaloneAsk(opts) {
  return new Promise((resolve) => {
    const host = document.createElement("div");
    host.setAttribute("data-ss-sheet-host", "ask");
    document.body.appendChild(host);
    const root = ReactDOM.createRoot(host);
    let done = false;
    const finish = (v) => {
      if (done) return;
      done = true;
      resolve(!!v);
      setTimeout(() => { root.unmount(); host.remove(); }, 0);
    };
    root.render(<StandaloneAsk opts={opts} onAnswer={finish} />);
  });
}
function ask(opts) {
  const o = normAsk(opts);
  const t = core.top();
  if (t && t.ask && !t.closing) return t.ask(o);
  return standaloneAsk(o);
}
function useAsk() { return ask; }

// ── CardSheet
function CardSheet({ card, status, image, onPrev, onNext, index, total, clip, actions, sections, onClose, children, label }) {
  const c = card || {};
  const name = c.name || "Unknown card";
  const swipe = useRef(null);
  const stageRef = useRef(null);
  const nav = useRef({});
  nav.current = { onPrev, onNext };
  const img = image !== undefined ? image : (c.image_normal || c.image_small || null);
  const onKey = (e) => {
    if (isTyping(e)) return false;
    if (e.key === "ArrowLeft" && nav.current.onPrev) { e.preventDefault(); nav.current.onPrev(); return true; }
    if (e.key === "ArrowRight" && nav.current.onNext) { e.preventDefault(); nav.current.onNext(); return true; }
    return false;
  };
  const onTouchStart = (e) => { if (e.touches && e.touches.length === 1) swipe.current = { x: e.touches[0].clientX, y: e.touches[0].clientY }; };
  const onTouchEnd = (e) => {
    const s0 = swipe.current;
    swipe.current = null;
    if (!s0 || !e.changedTouches || !e.changedTouches.length) return;
    const dx = e.changedTouches[0].clientX - s0.x;
    const dy = e.changedTouches[0].clientY - s0.y;
    if (Math.abs(dx) < 48 || Math.abs(dx) < Math.abs(dy) * 1.5) return;
    const go = dx < 0 ? nav.current.onNext : nav.current.onPrev;
    if (go) go();
  };
  // Walking to the first or last card disables the arrow that had focus; keep focus in the sheet.
  useEffect(() => {
    const a = document.activeElement;
    if (stageRef.current && (!a || a === document.body)) {
      const p = stageRef.current.closest(".ss-sheet");
      if (p) focusQuiet(p);
    }
  }, [name, index]);
  const isNode = React.isValidElement(actions);
  const a = (!isNode && actions) || {};
  const done = isNode ? true : (a.done === undefined ? true : a.done);
  const secs = (sections || []).filter(Boolean);
  const showCount = typeof index === "number" && typeof total === "number" && total > 1;
  return (
    <Sheet size="card" label={label || name} onClose={onClose} onKey={onKey}
      foot={done ? <Actions done={done} /> : null}>
      <div className="ss-sheet-card-stage" ref={stageRef} onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
        <button type="button" className="ss-sheet-card-arrow" disabled={!onPrev} onClick={() => onPrev && onPrev()} aria-label="Previous card">‹</button>
        <div className="ss-sheet-card-frame">
          <div className="ss-sheet-card-art">
            {typeof img === "string" && img ? <img src={img} alt={name} />
              : (img && React.isValidElement(img)) ? img
              : <span className="ss-sheet-card-ph">{name}</span>}
          </div>
          {clip && (
            <button type="button" className={"ss-sheet-card-clip" + (clip.on ? " is-on" : "")} aria-pressed={!!clip.on}
              aria-label={(clip.on ? "Unclip " : "Clip ") + name} title={clip.on ? "Clipped" : "Clip this card"}
              onClick={() => clip.onToggle && clip.onToggle()}><ClipSvg /></button>
          )}
        </div>
        <button type="button" className="ss-sheet-card-arrow" disabled={!onNext} onClick={() => onNext && onNext()} aria-label="Next card">›</button>
      </div>
      <div className="ss-sheet-card-head">
        {showCount && <p className="ss-sheet-card-count">{(index + 1) + " of " + total}</p>}
        <h2 className="ss-sheet-card-name">{name}</h2>
        <p className="ss-sheet-card-status">{status || " "}</p>
      </div>
      {children ? <div className="ss-sheet-card-extra">{children}</div> : null}
      {isNode ? actions : <Actions primary={a.primary} secondary={a.secondary} minor={a.minor} />}
      {secs.length > 0 && (
        <div className="ss-sheet-card-secs">
          {secs.map((s, i) => (
            <details key={name + ":" + (s.key || s.title || i)} className="ss-sheet-details" open={!!s.open}>
              <summary>{s.title}</summary>
              <div className="ss-sheet-details-body">{s.content}</div>
            </details>
          ))}
        </div>
      )}
    </Sheet>
  );
}

window.ssSheet = { Sheet, Actions, Ask, useAsk, CardSheet, lockScroll: core.lock };
})();
