/* ═══════════════════════════════════════════════════════════
   CircleThrice · Card-object interaction study.
   One screen of transits, four ways the detail card appears:
     A · Bottom sheet   B · Right tray   C · Anchored popover   D · Split view
   Reuses ork tokens + styles (orrery-takes), buildCard / CIcon /
   useSaves / toggleSave / useWheelScroll (orrery-cards).
═══════════════════════════════════════════════════════════ */
const { DesignCanvas, DCSection, DCArtboard } = window;
const CO = window.ORRERY;
const LEVEL = CO.byId['now'];           // the "Now · Hour of Saturn" horizon — 4 rich readings

/* ── one-time styles for the lab ──────────────────────── */
if (!document.getElementById('cix-styles')) {
  const s = document.createElement('style');
  s.id = 'cix-styles';
  s.textContent = `
  .cix-host{ width:100%; height:100%; }
  .cix-top{ flex:0 0 auto; display:flex; align-items:center; gap:12px; padding:15px 18px; border-bottom:1px solid var(--rule); background:var(--white); }
  .cix-mini{ width:30px; height:30px; flex:0 0 auto; }
  .cix-brand{ font-family:var(--disp); font-weight:600; letter-spacing:-0.012em; font-size:17px; color:var(--ink); }
  .cix-brand b{ color:var(--blue); font-weight:600; }
  .cix-chip{ margin-left:auto; font-family:var(--sc); text-transform:uppercase; letter-spacing:.12em; font-size:10px; font-weight:500;
    color:var(--blue); border:1px solid var(--vpale); border-radius:20px; padding:6px 12px; background:var(--paper); white-space:nowrap; }

  /* reading list */
  .cix-list{ flex:1 1 auto; min-height:0; overflow:auto; padding:14px 16px; display:flex; flex-direction:column; gap:9px; }
  .cix-listhead{ font-family:var(--sc); text-transform:uppercase; letter-spacing:.14em; font-size:10px; font-weight:500; color:var(--muted); padding:1px 2px 3px; }
  .cix-row{ display:flex; gap:11px; align-items:flex-start; padding:12px 13px; background:var(--white); cursor:pointer; text-align:left; font:inherit;
    border:1px solid var(--vpale); border-left:3px solid var(--rule); border-radius:3px; transition:border-color .15s, box-shadow .15s, background .15s, opacity .2s; width:100%; }
  .cix-row.lens-auspice{ border-left-color:var(--blue); } .cix-row.lens-transit{ border-left-color:var(--l-blue); } .cix-row.lens-planning{ border-left-color:#9aa9bb; }
  .cix-row:hover{ border-color:var(--l-blue); box-shadow:0 2px 12px rgba(43,50,64,.07); }
  .cix-row.on{ border-color:var(--blue); background:rgba(63,109,150,.06); box-shadow:0 2px 14px rgba(43,50,64,.08); }
  .cix-r-icn{ color:var(--blue); margin-top:1px; flex:0 0 auto; display:flex; } .cix-r-icn svg{ width:15px; height:15px; display:block; overflow:visible; }
  .cix-r-body{ flex:1; min-width:0; display:flex; flex-direction:column; }
  .cix-r-top{ display:flex; justify-content:space-between; gap:10px; align-items:baseline; }
  .cix-r-label{ font-family:var(--disp); font-weight:600; letter-spacing:-0.014em; font-size:15.5px; color:var(--ink); line-height:1.16; }
  .cix-r-time{ font-family:var(--sc); text-transform:uppercase; letter-spacing:.06em; font-size:10px; font-weight:500; color:var(--blue); white-space:nowrap; flex:0 0 auto; }
  .cix-r-text{ font-size:13px; font-weight:500; color:var(--muted); line-height:1.42; margin-top:3px; }
  .cix-r-chev{ align-self:center; flex:0 0 auto; width:7px; height:7px; border-right:1.5px solid var(--icon); border-bottom:1.5px solid var(--icon); transform:rotate(-45deg); }
  .cix-row:hover .cix-r-chev, .cix-row.on .cix-r-chev{ border-color:var(--blue); }

  /* shared detail content */
  .cix-d{ flex:1 1 auto; min-height:0; height:100%; display:flex; flex-direction:column; }
  .cix-d-scroll{ flex:1 1 auto; min-height:0; overflow:auto; padding:22px 24px; }
  .cix-d-titlewrap{ display:flex; align-items:center; gap:13px; }
  .cix-d-icn{ color:var(--blue); flex:0 0 auto; display:flex; } .cix-d-icn svg{ width:26px; height:26px; overflow:visible; }
  .cix-d-title{ font-family:var(--disp); font-weight:600; letter-spacing:-0.015em; font-size:27px; line-height:1.04; color:var(--ink); margin:0; }
  .cix-d-time{ font-family:var(--sc); text-transform:uppercase; letter-spacing:.1em; font-size:11.5px; font-weight:500; color:var(--blue); margin-top:9px; }
  .cix-d-pills{ display:flex; flex-wrap:wrap; gap:7px; margin:15px 0 2px; }
  .cix-d-p{ font-family:var(--body); font-size:16px; font-weight:500; line-height:1.55; color:var(--ink); margin:13px 0 0; }
  .cix-d-foot{ flex:0 0 auto; border-top:1px solid var(--rule); padding:13px 18px; background:var(--white); display:flex; align-items:center; justify-content:space-between; gap:12px; }
  .cix-dismiss{ font-family:var(--sc); text-transform:uppercase; letter-spacing:.1em; font-size:10.5px; font-weight:500; color:var(--icon); background:none; border:none; cursor:pointer; padding:4px 0; transition:color .15s; }
  .cix-dismiss:hover{ color:var(--blue); }

  /* a shared top bar for sheet / tray with handle + back pill */
  .cix-ovtop{ flex:0 0 auto; display:flex; align-items:center; justify-content:space-between; gap:12px; padding:13px 16px; border-bottom:1px solid var(--rule); background:var(--white); position:relative; }
  .cix-back{ display:inline-flex; align-items:center; gap:7px; cursor:pointer; border:1px solid var(--rule); background:var(--white); color:var(--blue);
    border-radius:20px; padding:7px 14px 7px 11px; transition:all .15s; font-family:var(--sc); text-transform:uppercase; letter-spacing:.1em; font-size:11px; font-weight:500; }
  .cix-back svg{ width:13px; height:13px; }
  .cix-back:hover{ color:var(--ink); border-color:var(--l-blue); background:rgba(63,109,150,.06); }
  .cix-kick{ font-family:var(--sc); text-transform:uppercase; letter-spacing:.16em; font-size:11px; font-weight:500; color:var(--blue); text-align:right; }

  /* scrim */
  .cix-scrim{ position:absolute; inset:0; z-index:20; background:rgba(43,50,64,.34); cursor:pointer; animation:cixfade .2s ease; }
  .cix-scrim.soft{ background:rgba(43,50,64,.14); }
  @keyframes cixfade{ from{ opacity:0; } to{ opacity:1; } }

  /* A · bottom sheet */
  .cix-sheet{ position:absolute; left:0; right:0; bottom:0; height:75%; z-index:21; background:var(--paper);
    border-top:1px solid var(--rule); border-radius:15px 15px 0 0; box-shadow:0 -16px 44px rgba(43,50,64,.26);
    display:flex; flex-direction:column; overflow:hidden; animation:cixsheet .3s cubic-bezier(.4,0,.2,1); }
  .cix-sheet .cix-ovtop{ border-radius:15px 15px 0 0; }
  .cix-sheet .cix-ovtop::before{ content:''; position:absolute; top:7px; left:50%; transform:translateX(-50%); width:38px; height:4px; border-radius:3px; background:var(--vpale); }
  @keyframes cixsheet{ from{ transform:translateY(100%); } to{ transform:none; } }

  /* B · right tray */
  .cix-tray{ position:absolute; top:0; right:0; bottom:0; width:54%; z-index:21; background:var(--paper);
    border-left:1px solid var(--rule); box-shadow:-18px 0 46px rgba(43,50,64,.22);
    display:flex; flex-direction:column; overflow:hidden; animation:cixtray .32s cubic-bezier(.4,0,.2,1); }
  @keyframes cixtray{ from{ transform:translateX(100%); } to{ transform:none; } }

  /* C · focus card — selected transit + detail rise, the rest recedes */
  .cix-sidebody{ flex:1 1 auto; min-height:0; display:flex; }
  .cix-sidelist{ flex:0 0 330px; min-height:0; display:flex; flex-direction:column; }
  .cix-sidedetail{ flex:1; min-width:0; min-height:0; display:flex; align-items:center; justify-content:center; padding:18px 26px 36px; }
  .cix-sidehint{ font-family:var(--sc); text-transform:uppercase; letter-spacing:.14em; font-size:11px; font-weight:500;
    color:var(--muted); text-align:center; max-width:190px; line-height:1.7; opacity:.6; }
  .cix-sidecard{ width:100%; max-width:352px; max-height:100%; background:var(--paper); border:1px solid var(--rule); border-radius:11px;
    box-shadow:0 18px 50px rgba(43,50,64,.22); display:flex; flex-direction:column; overflow:hidden; animation:cixpop .24s cubic-bezier(.4,0,.2,1); }
  @keyframes cixpop{ from{ opacity:0; transform:scale(.97) translateY(8px); } to{ opacity:1; transform:none; } }

  /* focus state: keep selected row + detail card lit, push everything else back */
  .cix-host.has-sel .cix-top{ opacity:.55; transition:opacity .2s; }
  .cix-host.has-sel .cix-listhead{ opacity:.5; }
  .cix-host.has-sel .cix-row:not(.on){ opacity:.38; }

  .cix-pop-top{ flex:0 0 auto; display:flex; align-items:center; justify-content:space-between; gap:10px; padding:11px 9px 11px 15px; border-bottom:1px solid var(--rule); background:var(--white); }
  .cix-pop-kick{ font-family:var(--sc); text-transform:uppercase; letter-spacing:.14em; font-size:10px; font-weight:500; color:var(--blue); }
  .cix-pop-x{ width:26px; height:26px; flex:0 0 auto; border-radius:50%; border:1px solid var(--rule); background:var(--white); cursor:pointer;
    font-size:15px; line-height:1; color:var(--muted); display:flex; align-items:center; justify-content:center; transition:all .15s; }
  .cix-pop-x:hover{ color:var(--ink); border-color:var(--l-blue); }
  .cix-pop-body{ flex:1 1 auto; min-height:0; overflow:auto; padding:16px 18px 18px; }
  .cix-sidecard .cix-d-title{ font-size:21px; }
  .cix-sidecard .cix-d-icn svg{ width:20px; height:20px; }
  .cix-sidecard .cix-d-p{ font-size:14.5px; margin-top:10px; }
  .cix-pop-save{ margin-top:15px; }

  /* D · split view */
  .cix-split{ flex:1 1 auto; min-height:0; display:flex; }
  .cix-split-rail{ flex:0 0 318px; min-height:0; border-right:1px solid var(--rule); display:flex; flex-direction:column; background:var(--paper); }
  .cix-split-detail{ flex:1; min-width:0; min-height:0; display:flex; }
  .cix-split-detail .cix-d{ width:100%; }

  /* generic save button reuses .ork-save; compact variant */
  .cix-save{ display:inline-flex; align-items:center; gap:9px; font-family:var(--sc); text-transform:uppercase; letter-spacing:.1em;
    font-size:11.5px; font-weight:500; cursor:pointer; padding:10px 16px; border-radius:3px; border:1px solid var(--blue); background:var(--white); color:var(--blue); transition:all .15s; }
  .cix-save svg{ width:14px; height:14px; }
  .cix-save:hover{ background:rgba(63,109,150,.06); }
  .cix-save.on{ background:var(--blue); color:#fff; }
  `;
  document.head.appendChild(s);
}

/* ── small bits ───────────────────────────────────────── */
const CIXArrow = () => (
  <svg viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M8.5 2.5 4 7l4.5 4.5" /></svg>
);
const Bookmark = ({ on }) => (
  <svg viewBox="0 0 14 14" fill={on ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.4"><path d="M3 1.6h8v10.8L7 9.4l-4 3z" strokeLinejoin="round" /></svg>
);
function MiniRings() {
  return (
    <svg viewBox="0 0 30 30" className="cix-mini" aria-hidden="true">
      {[3.4, 6.2, 9, 11.8].map((r, i) => (
        <circle key={i} cx="15" cy="15" r={r} fill="none" stroke={i === 0 ? 'var(--blue)' : 'var(--rule)'} strokeWidth={i === 0 ? 1.5 : 0.8} opacity={i === 0 ? 1 : 0.6} />
      ))}
      <circle cx="15" cy="15" r="1.5" fill="var(--blue)" />
    </svg>
  );
}

function SaveBtn({ card }) {
  const saves = useSaves();
  const saved = saves.some((c) => c.id === card.id);
  return (
    <button className={'cix-save' + (saved ? ' on' : '')} onClick={() => toggleSave(card)}>
      <Bookmark on={saved} />{saved ? 'Saved to favorites' : 'Save to favorites'}
    </button>
  );
}

/* ── shared host pieces ───────────────────────────────── */
function HostTop() {
  return (
    <div className="cix-top">
      <MiniRings />
      <span className="cix-brand">Circle<b>Thrice</b></span>
      <span className="cix-chip">{LEVEL.scale}</span>
    </div>
  );
}

function ReadingList({ activeId, onPick, headLabel }) {
  return (
    <div className="cix-list">
      {headLabel && <div className="cix-listhead">{headLabel}</div>}
      {LEVEL.rows.map((r, i) => {
        const card = buildCard(LEVEL, r, i);
        const on = activeId === card.id;
        return (
          <button key={i} className={'cix-row lens-' + r.lens + (on ? ' on' : '')} onClick={(e) => onPick(card, e)}>
            <span className="cix-r-icn"><CIcon id={r.icon} /></span>
            <span className="cix-r-body">
              <span className="cix-r-top">
                <span className="cix-r-label">{r.label}</span>
                {r.time && r.time !== '—' && <span className="cix-r-time">{r.time}</span>}
              </span>
              <span className="cix-r-text">{r.text}</span>
            </span>
            <span className="cix-r-chev"></span>
          </button>
        );
      })}
    </div>
  );
}

function DetailMeta({ card }) {
  return (
    <React.Fragment>
      <div className="cix-d-titlewrap">
        <span className="cix-d-icn"><CIcon id={card.icon} /></span>
        <h3 className="cix-d-title">{card.title}</h3>
      </div>
      {card.time && card.time !== '—' && <div className="cix-d-time">{card.time}</div>}
      {card.topics.length > 0 && <div className="cix-d-pills">{card.topics.map((t) => <span key={t} className="ork-pill">{t}</span>)}</div>}
      {card.body.map((p, i) => <p key={i} className="cix-d-p">{p}</p>)}
    </React.Fragment>
  );
}

/* full detail = scroll body + footer (save + optional close) */
function FullDetail({ card, onClose }) {
  const ref = useWheelScroll(false);
  return (
    <div className="cix-d ork-swap" key={card.id}>
      <div className="cix-d-scroll" ref={ref}><DetailMeta card={card} /></div>
      <div className="cix-d-foot">
        <SaveBtn card={card} />
        {onClose && <button className="cix-dismiss" onClick={onClose}>Back to transits</button>}
      </div>
    </div>
  );
}

/* ── A · bottom sheet ─────────────────────────────────── */
function PatternBottomSheet() {
  const [card, setCard] = React.useState(null);
  return (
    <div className="ork cix-host">
      <HostTop />
      <ReadingList activeId={card && card.id} onPick={(c) => setCard(c)} headLabel="Now · tap a transit" />
      {card && (
        <React.Fragment>
          <div className="cix-scrim" onClick={() => setCard(null)}></div>
          <div className="cix-sheet">
            <div className="cix-ovtop">
              <button className="cix-back" onClick={() => setCard(null)}><CIXArrow /> Back</button>
              <span className="cix-kick">{card.horizon}</span>
            </div>
            <FullDetail card={card} onClose={() => setCard(null)} />
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

/* ── B · right tray ───────────────────────────────────── */
function PatternRightTray() {
  const [card, setCard] = React.useState(null);
  return (
    <div className="ork cix-host">
      <HostTop />
      <ReadingList activeId={card && card.id} onPick={(c) => setCard(c)} headLabel="Now · tap a transit" />
      {card && (
        <React.Fragment>
          <div className="cix-scrim" onClick={() => setCard(null)}></div>
          <div className="cix-tray">
            <div className="cix-ovtop">
              <button className="cix-back" onClick={() => setCard(null)}><CIXArrow /> Back</button>
              <span className="cix-kick">{card.horizon}</span>
            </div>
            <FullDetail card={card} onClose={() => setCard(null)} />
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

/* ── C · focus card (selected row + detail rise, rest recedes) ── */
function PatternPopover() {
  const [card, setCard] = React.useState(null);
  return (
    <div className={'ork cix-host' + (card ? ' has-sel' : '')}>
      <HostTop />
      <div className="cix-sidebody">
        <div className="cix-sidelist">
          <ReadingList activeId={card && card.id} onPick={(c) => setCard(c)} headLabel="Now · tap a transit" />
        </div>
        <div className="cix-sidedetail">
          {card ? (
            <div className="cix-sidecard" key={card.id}>
              <div className="cix-pop-top">
                <span className="cix-pop-kick">{card.horizon}</span>
                <button className="cix-pop-x" onClick={() => setCard(null)} aria-label="Close">{'\u00d7'}</button>
              </div>
              <div className="cix-pop-body">
                <DetailMeta card={card} />
                <div className="cix-pop-save"><SaveBtn card={card} /></div>
              </div>
            </div>
          ) : (
            <div className="cix-sidehint">Tap a transit to open it here</div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ── D · split view (persistent two-pane) ─────────────── */
function PatternSplit() {
  const cards = LEVEL.rows.map((r, i) => buildCard(LEVEL, r, i));
  const [id, setId] = React.useState(cards[0].id);
  const card = cards.find((c) => c.id === id) || cards[0];
  return (
    <div className="ork cix-host">
      <HostTop />
      <div className="cix-split">
        <div className="cix-split-rail"><ReadingList activeId={card.id} onPick={(c) => setId(c.id)} headLabel="Now" /></div>
        <div className="cix-split-detail"><FullDetail card={card} /></div>
      </div>
    </div>
  );
}

/* ── canvas ───────────────────────────────────────────── */
function CardLab() {
  return (
    <DesignCanvas>
      <DCSection
        id="cards"
        title="Transit card · interaction study"
        subtitle="One screen of transits, four ways the detail opens. Tap any transit to see the pattern in action. A & B you asked for; C & D are proposals that keep the main screen in view so getting back is never in question."
      >
        <DCArtboard id="sheet" label="A · Bottom sheet — slides up over the lower 75%, wheel dimmed above" width={440} height={720}>
          <PatternBottomSheet />
        </DCArtboard>
        <DCArtboard id="tray" label="B · Right tray — detail drawer slides in from the edge" width={900} height={560}>
          <PatternRightTray />
        </DCArtboard>
        <DCArtboard id="pop" label="C · Focus card — selected transit + detail rise, the rest recedes (proposed)" width={820} height={560}>
          <PatternPopover />
        </DCArtboard>
        <DCArtboard id="split" label="D · Split view — persistent two-pane, never leaves the screen (proposed)" width={900} height={560}>
          <PatternSplit />
        </DCArtboard>
      </DCSection>
    </DesignCanvas>
  );
}

Object.assign(window, { PatternBottomSheet, PatternRightTray, PatternPopover, PatternSplit, CardLab });
if (!window.__CARD_LIB_ONLY) ReactDOM.createRoot(document.getElementById('root')).render(<CardLab />);
