/* Skyhearth Codex — entry treatments B & C (load after cards.jsx) */
/* global CX_ELEM, VERDICT_META, AVAIL_META, restLabel, timeAwakePct, triggerLore,
   ElComposite, ElChip, LedgerBars, StatLines, TriggerSlip, tierOf, pad2 */

// =============================================================================
// B · SPECIMEN PLATE — naturalist pinned specimen + measurement callouts
// =============================================================================
function SpecimenCard({ f, num, seen, triggerKnown, w = 340 }) {
  const t = tierOf(seen, triggerKnown);
  const av = AVAIL_META[f.avail];
  const callout = (label, val) => (
    <div className="row" style={{ gap:6, alignItems:'baseline' }}>
      <span className="label" style={{ fontSize:9 }}>{label}</span>
      <span className="leader" style={{ margin:'0 4px' }} />
      <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize:11, color:'var(--ink)' }}>{val}</span>
    </div>
  );
  return (
    <div style={{ width:w, background:'var(--paper)', border:'1.5px solid var(--ink)', padding:'14px 16px 16px', position:'relative',
      boxShadow:'inset 0 0 60px rgba(110,80,40,0.12)' }}>
      {/* plate header */}
      <div className="row" style={{ justifyContent:'space-between', alignItems:'baseline', borderBottom:'1px solid var(--ink-faded)', paddingBottom:7 }}>
        <span className="label" style={{ letterSpacing:'0.2em' }}>PLATE №{pad2(num)}</span>
        <span className="label" style={{ color:av.color }}>{t>=1 ? window.plabel(f.profile).toUpperCase() : 'UNCATALOGUED'}</span>
      </div>

      {/* specimen well — centered, with pin */}
      <div style={{ position:'relative', height:148, margin:'6px 0 4px', display:'flex', alignItems:'center', justifyContent:'center' }}>
        {/* faint plate grid */}
        <div style={{ position:'absolute', inset:'8px 0', backgroundImage:
          'repeating-linear-gradient(0deg, var(--ink-trace) 0 1px, transparent 1px 22px), repeating-linear-gradient(90deg, var(--ink-trace) 0 1px, transparent 1px 22px)' }} />
        {t>=1
          ? <>
              <FormPortrait f={f} size={124} />
              {/* pin */}
              <span style={{ position:'absolute', top:8, left:'50%', width:9, height:9, borderRadius:'50%',
                background:'var(--stamp-red)', boxShadow:'0 2px 4px rgba(0,0,0,0.4)' }} />
            </>
          : <div style={{ position:'relative', width:104, height:104, border:'1.5px dashed var(--ink-faded)', borderRadius:6,
              display:'flex', alignItems:'center', justifyContent:'center' }}>
              <FormPortrait f={f} size={78} ghost />
              <span style={{ position:'absolute', fontFamily:'IM Fell English SC, serif', fontSize:46, color:'var(--ink-faded)' }}>?</span>
              {/* wax seal */}
              <span className="stamp" style={{ position:'absolute', bottom:-12, fontSize:8.5, transform:'rotate(-6deg)', background:'var(--paper)' }}>UNCATALOGUED</span>
            </div>}
      </div>

      {/* name */}
      <div className="fell" style={{ fontSize:22, textAlign:'center', marginTop:6 }}>
        {t>=1 ? f.slot : <span style={{ color:'var(--ink-faded)' }}>— specimen unnamed —</span>}
      </div>
      <div className="elite" style={{ fontSize:10, textAlign:'center', color:'var(--sepia)', marginTop:2 }}>
        {seen ? `${f.role} · niche ${f.d.niche.join(' / ') || 'none'}` : 'sighted in passing; not yet taken'}
      </div>

      <hr className="divider-h-dashed" style={{ margin:'11px 0 9px' }} />

      {/* measurements */}
      {seen
        ? <div className="col" style={{ gap:3 }}>
            {callout('SLEEP', restLabel(f.rest))}
            {callout('LIFESPAN', `${f.life} days`)}
            {callout('FOOD / BOND', `${f.food} · ${f.bond}`)}
            {callout('ASCEND BONUS', f.elements.length ? f.elements.map(e=>`${CX_ELEM[e].glyph}+${f.d.dist[e]}`).join('  ') : 'spread 4/4/4/4')}
            <div style={{ marginTop:8 }}><LedgerBars f={f} compact /></div>
          </div>
        : <div className="col" style={{ gap:7, padding:'2px 0 6px' }}>
            {['REST','LIFESPAN','FOOD / BOND','ASCEND BONUS'].map((l,i)=>(
              <div key={i} className="row" style={{ gap:6, alignItems:'baseline' }}>
                <span className="label" style={{ fontSize:9 }}>{l}</span>
                <span className="leader" style={{ margin:'0 4px' }} />
                <span style={{ fontFamily:'IM Fell English SC, serif', color:'var(--ink-faded)', fontSize:15 }}>?</span>
              </div>
            ))}
          </div>}

      {/* trait — what it does on ascend (seen only) */}
      {seen && <div style={{ marginTop:11 }}><TraitSlip f={f} compact /></div>}

      {/* margin annotation = trigger */}
      <div style={{ marginTop:11 }}><TriggerSlip f={f} known={t>=2} /></div>
    </div>
  );
}

// =============================================================================
// C · AETHER TRACE — element-vector dial (elements ARE the stats)
// =============================================================================
function VectorDial({ f, lit, size = 150 }) {
  const cx = size/2, cy = size/2, R = size/2 - 16;
  const els = f.elements.length ? f.elements : ['fire','water','earth','nature'];
  const n = els.length;
  const maxB = 24;
  const pts = els.map((e, i) => {
    const ang = -Math.PI/2 + i * (Math.PI*2/n);
    const v = lit ? Math.min(1, (f.d.dist[e]||0)/maxB) : 0.12;
    const r = R * (0.18 + 0.82*v);
    return { e, x: cx + Math.cos(ang)*r, y: cy + Math.sin(ang)*r,
      ax: cx + Math.cos(ang)*R, ay: cy + Math.sin(ang)*R, ang };
  });
  const poly = pts.map(p=>`${p.x},${p.y}`).join(' ');
  return (
    <svg viewBox={`0 0 ${size} ${size}`} style={{ width:size, height:size, display:'block' }}>
      {[0.33,0.66,1].map((g,i)=>(
        <circle key={i} cx={cx} cy={cy} r={R*g} fill="none" stroke="var(--ink-ghost)" strokeWidth="0.6" strokeDasharray={i===2?'none':'2 3'} />
      ))}
      {pts.map(p=>(
        <line key={'a'+p.e} x1={cx} y1={cy} x2={p.ax} y2={p.ay} stroke="var(--ink-ghost)" strokeWidth="0.6" />
      ))}
      {lit && <polygon points={poly} fill="rgba(184,99,42,0.16)" stroke="var(--stamp-amber)" strokeWidth="1.4" />}
      {pts.map(p=>(
        <g key={p.e}>
          {lit && <circle cx={p.x} cy={p.y} r="3" fill={CX_ELEM[p.e].color} />}
          <text x={p.ax + Math.cos(p.ang)*9} y={p.ay + Math.sin(p.ang)*9 + 4} textAnchor="middle"
            fontFamily="IM Fell English SC, serif" fontSize="13" fill={lit?CX_ELEM[p.e].color:'var(--ink-faded)'}>
            {f.elements.length ? CX_ELEM[p.e].glyph : '·'}</text>
        </g>
      ))}
      {!lit && <text x={cx} y={cy+9} textAnchor="middle" fontFamily="IM Fell English SC, serif" fontSize="26" fill="var(--ink-faded)">?</text>}
    </svg>
  );
}

function AetherCard({ f, num, seen, triggerKnown, w = 340 }) {
  const t = tierOf(seen, triggerKnown);
  const av = AVAIL_META[f.avail];
  return (
    <div style={{ width:w, background:'var(--ink)', color:'var(--paper-light)', padding:'14px 16px 16px', position:'relative',
      border:'1.5px solid var(--ink)', boxShadow:'0 6px 22px rgba(14,10,8,0.5)' }}>
      <div className="row" style={{ justifyContent:'space-between', alignItems:'baseline' }}>
        <span style={{ fontFamily:'Special Elite, monospace', fontSize:9.5, letterSpacing:'0.22em', color:'rgba(244,236,214,0.6)' }}>AETHER TRACE · №{pad2(num)}</span>
        <span style={{ fontFamily:'Special Elite, monospace', fontSize:9.5, letterSpacing:'0.12em', color:av.color }}>
          {t>=1 ? window.plabel(f.profile).toUpperCase() : 'NO SIGNAL'}</span>
      </div>

      <div className="row" style={{ gap:6, alignItems:'center', justifyContent:'center', marginTop:6 }}>
        <VectorDial f={f} lit={seen} size={150} />
      </div>

      <div className="fell" style={{ fontSize:21, textAlign:'center', color:'var(--paper-light)', marginTop:2 }}>
        {t>=1 ? f.slot : <span style={{ color:'rgba(244,236,214,0.4)' }}>trace unresolved</span>}
      </div>
      <div style={{ fontFamily:'Special Elite, monospace', fontSize:10, textAlign:'center', color:'rgba(244,236,214,0.55)', marginTop:2 }}>
        {seen ? `${f.role.toUpperCase()} · ${restLabel(f.rest)}` : 'raise one, or hear it told, to resolve the trace'}
      </div>

      {/* stat strip */}
      {seen && (
        <div className="row" style={{ justifyContent:'space-between', margin:'12px 0 4px', borderTop:'1px solid rgba(244,236,214,0.18)', borderBottom:'1px solid rgba(244,236,214,0.18)', padding:'8px 0' }}>
          {[['LIFE',`${f.life}d`],['SLEEP', f.rest.slots===0?'none':f.rest.tod.join('+')],['FOOD',f.food],['BOND',f.bond],['GATE', f.gate]].map(([k,v])=>(
            <div key={k} className="col" style={{ alignItems:'center', gap:2 }}>
              <span style={{ fontFamily:'Special Elite, monospace', fontSize:8, letterSpacing:'0.1em', color:'rgba(244,236,214,0.5)' }}>{k}</span>
              <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize:12, color:'var(--paper-light)' }}>{v}</span>
            </div>
          ))}
        </div>
      )}

      {/* ledger — recolored for dark */}
      {seen && (
        <div style={{ marginTop:8 }}>
          <div style={{ fontFamily:'Special Elite, monospace', fontSize:9, letterSpacing:'0.12em', color:'rgba(244,236,214,0.55)', marginBottom:5 }}>
            NET {f.d.net} · GATE {f.d.gate} · {VERDICT_META[f.d.verdict].label.toUpperCase()}</div>
          <div style={{ display:'flex', height:8, borderRadius:2, overflow:'hidden', background:'rgba(244,236,214,0.1)' }}>
            <div style={{ width:`${Math.min(100, f.d.net/46*100)}%`, background:VERDICT_META[f.d.verdict].color }} />
          </div>
          <div style={{ position:'relative', height:0 }}>
            <div style={{ position:'absolute', top:-9, left:`${Math.min(100, f.d.gate/46*100)}%`, width:2, height:12, background:'var(--paper-light)' }} />
          </div>
        </div>
      )}

      {/* trait — what it does on ascend (dark variant, seen only) */}
      {seen && f.trait && f.trait.kind !== 'none' && (
        <div style={{ marginTop:13, borderLeft:`2px solid ${f.trait.kind==='active'?'var(--stamp-amber)':'#7ee787'}`, paddingLeft:10 }}>
          <div style={{ fontFamily:'Special Elite, monospace', fontSize:9, letterSpacing:'0.12em', color:'rgba(244,236,214,0.6)' }}>
            TRAIT · {f.trait.kind.toUpperCase()}{f.trait.nyi ? ' · NYI' : ''}{f.trait.town ? ' · TOWN' : ''}</div>
          <div className="fell" style={{ fontSize:14.5, color:'var(--paper-light)', margin:'3px 0 2px' }}>{f.trait.name}</div>
          <div style={{ fontFamily:'Special Elite, monospace', fontSize:9.5, color:'rgba(244,236,214,0.72)', lineHeight:1.45 }}>{f.trait.text}</div>
        </div>
      )}

      {/* trigger — terminal print or sealed */}
      <div style={{ marginTop:14 }}>
        {t>=2
          ? (() => { const lore = triggerLore(f); return (
              <div style={{ borderLeft:'2px solid var(--stamp-amber)', paddingLeft:10 }}>
                <div style={{ fontFamily:'Special Elite, monospace', fontSize:9, letterSpacing:'0.12em', color:'var(--stamp-amber)' }}>TRIGGER · DECODED</div>
                <div className="fell" style={{ fontStyle:'italic', fontSize:14.5, lineHeight:1.4, color:'var(--paper-light)', margin:'5px 0 5px' }}>{lore.text}</div>
                <div style={{ fontFamily:'Special Elite, monospace', fontSize:9, color:'rgba(244,236,214,0.55)', textAlign:'right' }}>— {lore.who}</div>
              </div>); })()
          : <div style={{ border:'1px dashed rgba(244,236,214,0.3)', padding:'9px 11px' }}>
              <div style={{ fontFamily:'Special Elite, monospace', fontSize:9, letterSpacing:'0.12em', color:'rgba(244,236,214,0.45)' }}>TRIGGER · ENCRYPTED</div>
              <div style={{ fontFamily:'Special Elite, monospace', fontSize:10, color:'rgba(244,236,214,0.45)', marginTop:4, lineHeight:1.5 }}>
                ▓▓▓▓ ▓▓▓ ▓▓▓▓▓▓ ▓▓ — achieve once, or find who remembers.</div>
            </div>}
      </div>
    </div>
  );
}

window.CodexCards2 = { SpecimenCard, AetherCard, VectorDial };
