/* Skyhearth Codex — the in-app view (load after wheel.jsx)
 * Wraps the Leak Wheel (primary) + grid (alternate), a rank selector
 * (Nascent / Lesser / Adult), and the omniscient design-mode toggle.
 * Driven by a discovery accessor `sv(id) -> {seen, tk}` passed from the game
 * (or the sample save). True Primal (R3) is intentionally absent — its very
 * existence is a secret until reached. */
/* global FORMS, plabel */
const { WheelBestiary } = window.CodexWheel;
const { GridOverview } = window.CodexCollection;

function CodexTab({ active, onClick, children, sub }) {
  return (
    <button onClick={onClick} className="btn" style={{
      padding:'7px 16px 6px', background: active ? 'var(--ink)' : 'rgba(244,236,214,0.55)',
      color: active ? 'var(--paper-light)' : 'var(--ink)', borderColor:'var(--ink)',
      display:'flex', flexDirection:'column', alignItems:'center', gap:1, lineHeight:1.1 }}>
      <span style={{ fontSize:15 }}>{children}</span>
      {sub != null && <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize:9, opacity:0.7 }}>{sub}</span>}
    </button>
  );
}

function CodexView({ sv, w = 1240, onClose }) {
  const [rank, setRank] = React.useState(2);
  const [view, setView] = React.useState('wheel');
  const [omni, setOmni] = React.useState(false);
  const baseSv = sv || window.CodexCollection.sv;
  const effSv = omni ? (() => ({ seen:1, tk:1 })) : baseSv;

  const countFor = (rk) => {
    const fs = FORMS.filter(f => f.rank === rk);
    return `${fs.filter(f => baseSv(f.id).seen || baseSv(f.id).tk).length}/${fs.length}`;
  };
  const rankWord = rank===0 ? 'Nascent' : rank===1 ? 'Lesser' : 'Adult';
  const forms = FORMS.filter(f => f.rank === rank);

  return (
    <div className="frayed-card" style={{ width:w, display:'flex', flexDirection:'column' }}>
      {/* command bar */}
      <div className="row" style={{ justifyContent:'space-between', alignItems:'center',
        padding:'13px 20px', borderBottom:'1.5px solid var(--ink)', background:'rgba(244,236,214,0.5)' }}>
        <div className="col" style={{ gap:1 }}>
          <span className="label" style={{ letterSpacing:'0.2em' }}>SKYHEARTH · HEARTH CODEX</span>
          <span className="fell" style={{ fontSize:22, lineHeight:1 }}>The Bestiary of Veins</span>
        </div>
        <div className="row" style={{ gap:8 }}>
          <CodexTab active={rank===0} onClick={()=>setRank(0)} sub={countFor(0)}>Nascent</CodexTab>
          <CodexTab active={rank===1} onClick={()=>setRank(1)} sub={countFor(1)}>Lesser</CodexTab>
          <CodexTab active={rank===2} onClick={()=>setRank(2)} sub={countFor(2)}>Adult</CodexTab>
        </div>
        <div className="row" style={{ gap:8, alignItems:'center' }}>
          <div className="row" style={{ border:'1.5px solid var(--ink)' }}>
            {['wheel','grid'].map(v => (
              <button key={v} onClick={()=>setView(v)} className="elite" style={{
                border:'none', cursor:'pointer', padding:'8px 12px', fontSize:11, letterSpacing:'0.08em',
                background: view===v ? 'var(--ink)' : 'transparent', color: view===v ? 'var(--paper-light)' : 'var(--ink-faded)' }}>
                {v==='wheel' ? '◎ Wheel' : '▦ Grid'}</button>
            ))}
          </div>
          <button onClick={()=>setOmni(o=>!o)} className="elite" style={{
            cursor:'pointer', padding:'8px 12px', fontSize:10.5, letterSpacing:'0.06em',
            border:`1.5px solid ${omni?'var(--stamp-red)':'var(--ink-ghost)'}`,
            background: omni ? 'rgba(161,43,34,0.08)' : 'transparent',
            color: omni ? 'var(--stamp-red)' : 'var(--ink-faded)' }}>
            {omni ? '● DESIGN MODE' : '○ design mode'}</button>
          {onClose && <button onClick={onClose} className="btn" style={{ padding:'8px 13px', fontSize:13, borderColor:'var(--ink)' }}>✕ Close</button>}
        </div>
      </div>

      {/* body */}
      <div style={{ padding:'8px 14px 12px', display:'flex', justifyContent:'center', background:'rgba(236,225,199,0.35)' }}>
        {view==='wheel'
          ? <WheelBestiary rank={rank} sv={effSv} w={w-36} />
          : <GridOverview forms={forms} svFn={effSv} title={`${rankWord} Forms`} w={w-36} />}
      </div>

      {omni && <div className="row" style={{ justifyContent:'center', gap:8, padding:'8px 0 12px', background:'rgba(236,225,199,0.35)' }}>
        <span className="elite" style={{ fontSize:10.5, color:'var(--stamp-red)' }}>
          DESIGN MODE — every entry forced to Trigger-Known; this is the §7.3 omniscient viz, not the player view.</span>
      </div>}
    </div>
  );
}

window.CodexApp = { CodexView, CodexOverlay };

// Overlay shell — floats on top of the current screen (matches InventoryOverlay:
// light dim, same z-band, contained panel, click-backdrop / Esc to close).
function CodexOverlay({ onClose, sv }) {
  React.useEffect(() => {
    const k = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', k); return () => window.removeEventListener('keydown', k);
  }, []);
  return (
    <div onClick={onClose} style={{
      position:'absolute', inset:0, zIndex:300,
      background:'rgba(20, 16, 10, 0.55)',
      display:'flex', alignItems:'center', justifyContent:'center' }}>
      <div onClick={(e)=>e.stopPropagation()} style={{ position:'relative', maxHeight:'90%', maxWidth:'94%', overflow:'auto' }}>
        <CodexView sv={sv} onClose={onClose} />
      </div>
    </div>
  );
}
