// primitives.jsx — 공통 프리미티브 (스파크라인, 라인/캔들/바 차트, 뱃지, 구분선)
// 모든 수치는 흑백 + 회색. 상승/하락은 채움/외곽선 + ▲/▼로 구분.

// 공통 팔레트 헬퍼
function useTheme() {
  const ctx = React.useContext(ThemeCtx);
  return ctx;
}
const ThemeCtx = React.createContext({ dark:false, density:'cozy', chart:'line', type:'sans', lang:'ko' });

// 숫자 포맷
const fmt = (n, d=2) => (n==null?'—':Number(n).toLocaleString('en-US',{minimumFractionDigits:d, maximumFractionDigits:d}));
const sign = (n) => n>0?'+':(n<0?'−':'');
const arrow = (n) => n>0?'▲':(n<0?'▼':'•');

// 팔레트 — 웜 샌드 베이스 + 미드나잇 잉크 + 상승(teal) / 하락(coral) 악센트
function palette(dark){
  return dark ? {
    bg:'#141822', surface:'#1C2130', surface2:'#242A3B',
    line:'rgba(255,255,255,0.07)', line2:'rgba(255,255,255,0.14)',
    text:'#F3EEE4', muted:'rgba(243,238,228,0.62)', faint:'rgba(243,238,228,0.38)',
    inkUp:'#6FD7C4',  inkDown:'#F08A7A',
    accent:'#E8C88F', tint:'rgba(255,255,255,0.04)',
  } : {
    bg:'#F4EEE3', surface:'#FBF7EE', surface2:'#EFE8D8',
    line:'rgba(30,35,50,0.08)', line2:'rgba(30,35,50,0.14)',
    text:'#1E2332', muted:'rgba(30,35,50,0.60)', faint:'rgba(30,35,50,0.36)',
    inkUp:'#1F8C78',  inkDown:'#C45A48',
    accent:'#8B6F3A', tint:'rgba(30,35,50,0.035)',
  };
}

// 섹션 카드
function Card({ children, style={}, padded=true }) {
  const { dark } = useTheme();
  const p = palette(dark);
  return (
    <div style={{
      background:p.surface, borderRadius:22,
      margin:'0 14px', padding: padded ? 16 : 0,
      boxShadow: dark ? '0 0 0 1px rgba(255,255,255,0.05)' : '0 0 0 1px rgba(0,0,0,0.04)',
      ...style,
    }}>{children}</div>
  );
}

// 섹션 헤더 (카드 위 라벨)
function SectionLabel({ kicker, title, right }) {
  const { dark, type } = useTheme();
  const p = palette(dark);
  const serif = type==='serif';
  return (
    <div style={{ padding:'28px 26px 10px', display:'flex', alignItems:'flex-end', justifyContent:'space-between' }}>
      <div>
        <div style={{
          fontSize:11, letterSpacing:'0.14em', textTransform:'uppercase',
          color:p.faint, fontFamily:'"JetBrains Mono", ui-monospace, monospace',
        }}>{kicker}</div>
        <div style={{
          fontSize: serif? 26:24, fontWeight: serif?500:600,
          letterSpacing:-0.4, color:p.text, marginTop:4,
          fontFamily: serif? '"Fraunces", Georgia, serif' : '"Inter Tight", -apple-system, system-ui',
        }}>{title}</div>
      </div>
      {right && <div style={{ color:p.muted, fontSize:12, fontFamily:'"JetBrains Mono", monospace' }}>{right}</div>}
    </div>
  );
}

// 스파크라인 (라인/바/미니멀 대응)
function Spark({ data, w=88, h=28, up=true, variant }) {
  const { dark, chart } = useTheme();
  const p = palette(dark);
  variant = variant || chart;
  const max = Math.max(...data), min = Math.min(...data);
  const rng = (max-min) || 1;
  const n = data.length;
  const stroke = up ? p.inkUp : p.inkDown;

  if (variant === 'bar') {
    const bw = (w - (n-1)*1) / n;
    return (
      <svg width={w} height={h}>
        {data.map((v,i) => {
          const hh = ((v-min)/rng)*(h-2) + 2;
          return <rect key={i} x={i*(bw+1)} y={h-hh} width={bw} height={hh} fill={stroke} opacity={up?1:0.55}/>;
        })}
      </svg>
    );
  }
  if (variant === 'minimal') {
    // 시작/끝 점 + 가는 선
    const x = (i)=> (i/(n-1))*(w-2)+1;
    const y = (v)=> h - ((v-min)/rng)*(h-4) - 2;
    const d = data.map((v,i)=> `${i?'L':'M'}${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ');
    return (
      <svg width={w} height={h}>
        <path d={d} fill="none" stroke={stroke} strokeWidth={1} opacity={0.9}/>
        <circle cx={x(n-1)} cy={y(data[n-1])} r={2} fill={stroke}/>
      </svg>
    );
  }
  // line (default) — solid stroke only
  const x = (i)=> (i/(n-1))*(w-2)+1;
  const y = (v)=> h - ((v-min)/rng)*(h-4) - 2;
  const d = data.map((v,i)=> `${i?'L':'M'}${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ');
  return (
    <svg width={w} height={h}>
      <path d={d} fill="none" stroke={stroke} strokeWidth={1.5} strokeLinejoin="round" strokeLinecap="round"/>
    </svg>
  );
}

// 상/하락 델타 칩 (숫자)
function Delta({ pct, chg, size=12 }) {
  const { dark } = useTheme();
  const p = palette(dark);
  const up = pct>=0;
  const col = up ? p.inkUp : p.inkDown;
  return (
    <span style={{
      fontFamily:'"JetBrains Mono", ui-monospace, monospace',
      fontSize:size, fontVariantNumeric:'tabular-nums',
      color:col, letterSpacing:-0.2, whiteSpace:'nowrap',
    }}>
      <span style={{ marginRight:4, fontSize:size-2 }}>{arrow(pct)}</span>
      {sign(pct)}{Math.abs(pct).toFixed(2)}%
      {chg!=null && <span style={{ color:p.faint, marginLeft:6 }}>{sign(chg)}{fmt(Math.abs(chg),2)}</span>}
    </span>
  );
}

// 임포턴스 뱃지 (H/M/L)
function ImpBadge({ level }) {
  const { dark } = useTheme();
  const p = palette(dark);
  const filled = level==='H';
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', justifyContent:'center',
      width:20, height:20, borderRadius:6, fontSize:10, fontWeight:600,
      fontFamily:'"JetBrains Mono", monospace',
      background: filled ? p.text : 'transparent',
      color: filled ? p.bg : p.muted,
      border: filled ? 'none' : `1px solid ${p.line2}`,
    }}>{level}</span>
  );
}

Object.assign(window, { Card, SectionLabel, Spark, Delta, ImpBadge, palette, useTheme, ThemeCtx, fmt, sign, arrow });
