// chart-sheet.jsx — 지수/환율 드릴다운 실시간 차트 시트
// 기간 선택(1D/1W/1M/3M/1Y), 크로스헤어, 실시간 틱 시뮬레이션, 통계 카드

function formatPx(v, unit) {
  if (unit === 'yield') return v.toFixed(2) + '%';
  if (unit === 'fx')    return v.toLocaleString('en-US', {maximumFractionDigits:2});
  if (unit === 'bbl')   return '$' + v.toFixed(2);
  if (unit === 'crypto')return '$' + v.toLocaleString('en-US', {maximumFractionDigits:0});
  return v.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2});
}

const PERIODS = [
  { k:'1D', labelKo:'1일',  labelEn:'1D' },
  { k:'1W', labelKo:'1주',  labelEn:'1W' },
  { k:'1M', labelKo:'1개월',labelEn:'1M' },
  { k:'3M', labelKo:'3개월',labelEn:'3M' },
  { k:'1Y', labelKo:'1년',  labelEn:'1Y' },
];

function IndexChartSheet({ sym, onClose }) {
  const { dark, lang } = useTheme();
  const p = palette(dark);

  const [mounted, setMounted] = React.useState(false);
  const [period, setPeriod] = React.useState('1D');
  const [hover, setHover] = React.useState(null);         // {idx, x, y}
  const [livePx, setLivePx] = React.useState(null);
  const svgRef = React.useRef(null);

  React.useEffect(() => {
    if (sym) { requestAnimationFrame(()=>setMounted(true)); }
    else { setMounted(false); setHover(null); setLivePx(null); }
  }, [sym]);

  // 실시간 가격 — INDICES 배열을 data.jsx 로더가 60s 주기로 갱신하므로
  // base.px 를 그대로 반영한다. 난수 시뮬레이션은 사용하지 않는다.
  React.useEffect(() => {
    if (!sym) return;
    const sync = () => {
      const base = INDICES.find(i=>i.sym===sym);
      if (base && typeof base.px === 'number') setLivePx(base.px);
    };
    sync();
    window.addEventListener('indices-updated', sync);
    return () => window.removeEventListener('indices-updated', sync);
  }, [sym]);

  if (!sym) return null;
  const base = INDICES.find(i=>i.sym===sym);
  const series0 = (HISTORY[sym] && HISTORY[sym][period]) || [];
  // 1D: 실제 Yahoo 인트라데이 종가만 사용. 난수 시뮬레이션 없음.
  const series = series0.length ? series0 : [base?.px || 0];

  const up = (base.pct || 0) >= 0;
  const upRgb = dark ? '111,215,196' : '31,140,120';
  const dnRgb = dark ? '240,138,122' : '196,90,72';
  const rgb = up ? upRgb : dnRgb;
  const stroke = up ? p.inkUp : p.inkDown;

  // 차트 geometry
  const W = 370, H = 200, padX = 14, padY = 14;
  const n = series.length;
  const min = Math.min(...series), max = Math.max(...series);
  const rng = (max - min) || 1;
  const x = (i) => padX + (i/(n-1)) * (W - padX*2);
  const y = (v) => padY + (1 - (v-min)/rng) * (H - padY*2);
  const d = series.map((v,i)=> `${i?'L':'M'}${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ');

  // hover 처리
  const onMove = (ev) => {
    const rect = svgRef.current.getBoundingClientRect();
    const px = (ev.touches? ev.touches[0].clientX : ev.clientX) - rect.left;
    const scale = W / rect.width;
    const xPx = px * scale;
    const idx = Math.max(0, Math.min(n-1, Math.round(((xPx - padX)/(W - padX*2)) * (n-1))));
    setHover({ idx, x: x(idx), y: y(series[idx]), v: series[idx] });
  };
  const onLeave = () => setHover(null);

  // Use authoritative live numbers for header (not series-derived — series
  // is a visual sampling and doesn't anchor the true prev close).
  const truePct = (typeof base.pct === 'number') ? base.pct : 0;
  const trueChg = (typeof base.chg === 'number') ? base.chg : 0;
  const truePx  = livePx ?? base.px ?? series[series.length-1];
  const trueOpen = (typeof base.prev === 'number') ? base.prev : series0[0];
  const high = Math.max(...series);
  const low = Math.min(...series);
  const close = truePx;
  const displayPx  = hover ? hover.v : close;
  const displayChg = hover ? (hover.v - trueOpen) : trueChg;
  const displayPct = hover ? ((hover.v - trueOpen) / trueOpen * 100) : truePct;

  // x축 라벨
  const xLabels = (() => {
    if (period === '1D') return ['09:00', '11:00', '13:00', '15:30'];
    if (period === '1W') return ['Mon', 'Wed', 'Fri'];
    if (period === '1M') return ['4주 전', '2주 전', '지금'];
    if (period === '3M') return ['Feb', 'Mar', 'Apr'];
    return ['1Y ago', '6M', 'now'];
  })();

  // y축 눈금 (3개)
  const yTicks = [max, (max+min)/2, min];

  return (
    <div style={{ position:'absolute', inset:0, zIndex:110, pointerEvents:'auto' }}>
      <div
        onClick={onClose}
        style={{
          position:'absolute', inset:0,
          background:'rgba(0,0,0,0.42)',
          backdropFilter:'blur(3px)', WebkitBackdropFilter:'blur(3px)',
          opacity: mounted ? 1 : 0,
          transition:'opacity 220ms ease',
        }}
      />
      <div style={{
        position:'absolute', left:0, right:0, bottom:0,
        background: p.bg,
        borderTopLeftRadius: 28, borderTopRightRadius: 28,
        height: '88%',
        display:'flex', flexDirection:'column',
        transform: mounted ? 'translateY(0)' : 'translateY(100%)',
        transition:'transform 340ms cubic-bezier(0.25, 1, 0.32, 1)',
        boxShadow:'0 -20px 48px rgba(0,0,0,0.28)',
        overflow:'hidden',
      }}>
        {/* grabber */}
        <div style={{ display:'flex', justifyContent:'center', padding:'10px 0 2px' }}>
          <div style={{ width:36, height:5, borderRadius:3, background:p.line2 }}/>
        </div>

        {/* header */}
        <div style={{ padding:'10px 22px 14px', display:'flex', alignItems:'flex-start', gap:12 }}>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{
              display:'flex', alignItems:'center', gap:8,
              fontSize:10, letterSpacing:'0.16em', color:p.faint,
              fontFamily:'"JetBrains Mono", monospace', marginBottom:5,
            }}>
              <span>{base.unit.toUpperCase()}</span>
              <span style={{
                display:'inline-flex', alignItems:'center', gap:5,
                color: stroke, letterSpacing:'0.14em',
              }}>
                <span style={{
                  width:6, height:6, borderRadius:'50%', background:stroke,
                  animation:'dmr-pulse 1.4s ease-in-out infinite',
                }}/>
                LIVE
              </span>
            </div>
            <div style={{
              fontSize:26, fontWeight:600, color:p.text,
              fontFamily:'"Inter Tight", system-ui', letterSpacing:-0.6,
              lineHeight:1.05,
            }}>{sym}</div>
          </div>
          <button onClick={onClose} aria-label="close" style={{
            width:34, height:34, borderRadius:'50%', border:'none', cursor:'pointer',
            background: p.surface2, color:p.muted,
            display:'flex', alignItems:'center', justifyContent:'center',
            flexShrink:0,
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14">
              <path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
            </svg>
          </button>
        </div>

        {/* big price + delta */}
        <div style={{ padding:'0 22px 14px' }}>
          <div style={{
            fontSize:40, fontWeight:600, letterSpacing:-1.2,
            color:p.text, fontFamily:'"Inter Tight", system-ui',
            fontVariantNumeric:'tabular-nums', lineHeight:1,
            transition:'color 300ms ease',
          }}>{formatPx(displayPx, base.unit)}</div>
          <div style={{ marginTop:7, display:'flex', alignItems:'center', gap:10 }}>
            <Delta pct={displayPct} chg={displayChg} size={13}/>
            <span style={{
              fontSize:10, color:p.faint, letterSpacing:'0.12em',
              fontFamily:'"JetBrains Mono", monospace',
            }}>
              {hover
                ? (lang==='ko'?'호버':'HOVER')
                : (period === '1D'
                    ? (lang==='ko'?'실시간':'REAL-TIME')
                    : (lang==='ko'?'기간 변동':'PERIOD CHG'))
              }
            </span>
          </div>
        </div>

        {/* chart area */}
        <div style={{ padding:'0 8px 0', position:'relative' }}>
          <svg
            ref={svgRef}
            viewBox={`0 0 ${W} ${H}`}
            width="100%" height={H}
            preserveAspectRatio="none"
            style={{ display:'block', touchAction:'none' }}
            onMouseMove={onMove} onMouseLeave={onLeave}
            onTouchStart={onMove} onTouchMove={onMove} onTouchEnd={onLeave}
          >
            {/* y 눈금선 */}
            {yTicks.map((v,i)=>(
              <g key={i}>
                <line x1={padX} x2={W-padX} y1={y(v)} y2={y(v)}
                  stroke={p.line} strokeWidth={0.5} strokeDasharray={i===1?'2 3':''}/>
                <text x={W-padX-2} y={y(v)-3} textAnchor="end"
                  style={{
                    fill: p.faint, fontSize:9,
                    fontFamily:'"JetBrains Mono", monospace',
                    fontVariantNumeric:'tabular-nums',
                  }}>{formatPx(v, base.unit)}</text>
              </g>
            ))}
            {/* line */}
            <path d={d} fill="none" stroke={stroke} strokeWidth={1.6}
              strokeLinejoin="round" strokeLinecap="round"/>
            {/* 끝점 + 펄스 (실시간) */}
            <circle cx={x(n-1)} cy={y(series[n-1])} r={3.5} fill={stroke}/>
            {period === '1D' && (
              <circle cx={x(n-1)} cy={y(series[n-1])} r={8} fill={stroke}
                opacity={0.35} style={{ animation:'dmr-radar 1.6s ease-out infinite' }}/>
            )}
            {/* hover crosshair */}
            {hover && (
              <g>
                <line x1={hover.x} x2={hover.x} y1={padY} y2={H-padY}
                  stroke={p.line2} strokeWidth={0.7} strokeDasharray="2 3"/>
                <line x1={padX} x2={W-padX} y1={hover.y} y2={hover.y}
                  stroke={p.line2} strokeWidth={0.7} strokeDasharray="2 3"/>
                <circle cx={hover.x} cy={hover.y} r={4.5} fill={p.bg} stroke={stroke} strokeWidth={1.6}/>
              </g>
            )}
          </svg>
          {/* x-axis labels */}
          <div style={{
            display:'flex', justifyContent:'space-between',
            padding:'6px 20px 0',
            fontFamily:'"JetBrains Mono", monospace', fontSize:9,
            color:p.faint, letterSpacing:'0.1em',
          }}>
            {xLabels.map((l,i)=>(<span key={i}>{l}</span>))}
          </div>
        </div>

        {/* period tabs */}
        <div style={{ padding:'16px 16px 12px' }}>
          <div style={{
            display:'grid', gridTemplateColumns:'repeat(5, 1fr)', gap:4,
            background: p.surface2, borderRadius:12, padding:4,
          }}>
            {PERIODS.map(per=>(
              <button key={per.k}
                onClick={()=>setPeriod(per.k)}
                style={{
                  appearance:'none', border:'none', cursor:'pointer',
                  padding:'9px 4px', borderRadius:9,
                  fontSize:12, fontWeight: period===per.k? 600:500,
                  color: period===per.k? p.text : p.muted,
                  background: period===per.k? p.surface : 'transparent',
                  boxShadow: period===per.k? (dark?'0 0 0 1px rgba(255,255,255,0.06)':'0 1px 2px rgba(0,0,0,0.06)') : 'none',
                  fontFamily:'"Inter Tight", system-ui',
                  transition:'all 180ms',
                }}>{lang==='ko'? per.labelKo : per.labelEn}</button>
            ))}
          </div>
        </div>

        {/* OHLC stats */}
        <div style={{
          padding:'6px 22px 20px',
          display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:4,
          borderTop:`0.5px solid ${p.line}`, marginTop:4,
        }}>
          {[
            {label: lang==='ko'?'전일종가':'PREV', v: trueOpen},
            {label: lang==='ko'?'고가':'HIGH', v: high},
            {label: lang==='ko'?'저가':'LOW',  v: low},
            {label: lang==='ko'?'현재가':'LAST',v: close},
          ].map((s,i)=>(
            <div key={i} style={{ paddingTop:12 }}>
              <div style={{
                fontSize:9, letterSpacing:'0.14em', color:p.faint,
                fontFamily:'"JetBrains Mono", monospace',
              }}>{s.label}</div>
              <div style={{
                fontSize:13, color:p.text, marginTop:4,
                fontFamily:'"JetBrains Mono", monospace',
                fontVariantNumeric:'tabular-nums', fontWeight:500,
              }}>{formatPx(s.v, base.unit)}</div>
            </div>
          ))}
        </div>

        {/* footnote */}
        <div style={{
          padding:'0 22px 22px',
          fontSize:10, color:p.faint, letterSpacing:'0.1em',
          fontFamily:'"JetBrains Mono", monospace',
        }}>
          {lang==='ko'? '* 시뮬레이션 데이터 · 0.7초 간격 업데이트' : '* Simulated data · 0.7s refresh'}
        </div>
      </div>

      <style>{`
        @keyframes dmr-pulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50% { opacity: 0.3; transform: scale(0.8); }
        }
        @keyframes dmr-radar {
          0% { r: 3.5; opacity: 0.55; }
          100% { r: 14; opacity: 0; }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { IndexChartSheet });
