// stock-sheet.jsx — 개별 종목 클릭 시 열리는 실시간 차트 시트
// 차트 데이터는 /api/stock-chart 에서 실제 Yahoo Finance 인트라데이/히스토리 종가를 받아옴.

function StockChartSheet({ stock, 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);
  const [chart, setChart] = React.useState(null); // {sym, period, px, prev, pct, chg, high, low, closes}
  const [loading, setLoading] = React.useState(false);
  const svgRef = React.useRef(null);

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

  // 실제 차트 데이터 fetch (종목 or 기간 변경 시)
  React.useEffect(() => {
    if (!stock || !stock.sym) return;
    let aborted = false;
    setLoading(true);
    fetch(`/api/stock-chart?sym=${encodeURIComponent(stock.sym)}&period=${period}`, { cache: 'no-store' })
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (aborted) return;
        if (data && Array.isArray(data.closes) && data.closes.length > 0) {
          setChart(data);
        } else {
          setChart(null);
        }
      })
      .catch(() => { if (!aborted) setChart(null); })
      .finally(() => { if (!aborted) setLoading(false); });
    return () => { aborted = true; };
  }, [stock, period]);

  const PERIODS_LOCAL = [
    { 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' },
  ];

  if (!stock) return null;

  // Authoritative live values: chart response preferred, fall back to stock row.
  const livePx  = (chart && typeof chart.px === 'number') ? chart.px : stock.px;
  const livePct = (chart && typeof chart.pct === 'number') ? chart.pct : stock.pct;
  const liveChg = (chart && typeof chart.chg === 'number') ? chart.chg
                : (typeof stock.chg === 'number' ? stock.chg : null);
  const livePrev = (chart && typeof chart.prev === 'number') ? chart.prev
                 : (livePx != null && livePct != null ? livePx / (1 + livePct/100) : null);

  const series = (chart && chart.closes) ? chart.closes : [];
  const hasData = series.length >= 2;

  const up = (livePct || 0) >= 0;
  const stroke = up ? p.inkUp : p.inkDown;

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

  const onMove = (ev) => {
    if (!hasData) return;
    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);

  const high = (chart && typeof chart.high === 'number') ? chart.high : (hasData ? Math.max(...series) : null);
  const low  = (chart && typeof chart.low  === 'number') ? chart.low  : (hasData ? Math.min(...series) : null);
  const close = livePx;
  const displayPx  = hover ? hover.v : close;
  const displayChg = hover && livePrev != null ? (hover.v - livePrev) : liveChg;
  const displayPct = hover && livePrev != null ? ((hover.v - livePrev)/livePrev * 100) : livePct;

  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 [lang==='ko'?'4주 전':'4w',lang==='ko'?'2주 전':'2w',lang==='ko'?'지금':'now'];
    if (period === '3M') return ['3M','2M','1M',lang==='ko'?'지금':'now'];
    return ['1Y',lang==='ko'?'6개월':'6M',lang==='ko'?'지금':'now'];
  })();
  const yTicks = hasData ? [max, (max+min)/2, min] : [];

  const fmtPx = (v) => {
    if (typeof v !== 'number') return '—';
    return v >= 1000
      ? v.toLocaleString('en-US', {maximumFractionDigits:0})
      : v.toFixed(2);
  };

  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',
      }}>
        <div style={{ display:'flex', justifyContent:'center', padding:'10px 0 2px' }}>
          <div style={{ width:36, height:5, borderRadius:3, background:p.line2 }}/>
        </div>

        <div style={{ padding:'10px 22px 12px', 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>{stock.sym}</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:24, fontWeight:600, color:p.text,
              fontFamily:'"Inter Tight", system-ui', letterSpacing:-0.5,
              lineHeight:1.1,
            }}>{stock.name}</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>

        <div style={{ padding:'0 22px 10px' }}>
          <div style={{
            fontSize:38, fontWeight:600, letterSpacing:-1.1,
            color:p.text, fontFamily:'"Inter Tight", system-ui',
            fontVariantNumeric:'tabular-nums', lineHeight:1,
          }}>{fmtPx(displayPx)}</div>
          <div style={{ marginTop:6, display:'flex', alignItems:'center', gap:10 }}>
            <Delta pct={displayPct} chg={displayChg} size={13}/>
            {hover && (
              <span style={{
                fontFamily:'"JetBrains Mono", monospace', fontSize:10,
                color:p.faint, letterSpacing:'0.12em',
              }}>@ {xLabels[Math.round(hover.idx / (n-1) * (xLabels.length-1))] || ''}</span>
            )}
          </div>
        </div>

        <div style={{ padding:'0 18px 10px' }}>
          <div style={{
            display:'grid', gridTemplateColumns:'repeat(5, 1fr)', gap:3,
            background: p.surface2, borderRadius:11, padding:3,
          }}>
            {PERIODS_LOCAL.map(pd=>(
              <button key={pd.k} onClick={()=>setPeriod(pd.k)} style={{
                appearance:'none', border:'none', cursor:'pointer',
                padding:'7px', borderRadius:8,
                fontSize:11, fontWeight: period===pd.k?600:500,
                color: period===pd.k? p.text : p.muted,
                background: period===pd.k? p.surface : 'transparent',
                boxShadow: period===pd.k? (dark?'0 0 0 1px rgba(255,255,255,0.05)':'0 1px 2px rgba(0,0,0,0.05)') : 'none',
                fontFamily:'"Inter Tight", system-ui',
              }}>{lang==='ko'?pd.labelKo:pd.labelEn}</button>
            ))}
          </div>
        </div>

        {/* chart */}
        <div style={{ padding:'4px 14px 6px', position:'relative', minHeight: H+8 }}>
          {hasData ? (
            <svg
              ref={svgRef} viewBox={`0 0 ${W} ${H}`}
              width="100%" style={{ display:'block', touchAction:'none' }}
              onMouseMove={onMove} onMouseLeave={onLeave}
              onTouchMove={onMove} onTouchEnd={onLeave}
            >
              {yTicks.map((v,i)=>(
                <g key={i}>
                  <line x1={padX} x2={W-padX} y1={y(v)} y2={y(v)}
                    stroke={p.line} strokeDasharray="2 3" strokeWidth="0.5"/>
                  <text x={W-padX} y={y(v)-3} textAnchor="end"
                    fontFamily="JetBrains Mono, monospace" fontSize="9"
                    fill={p.faint}>{fmtPx(v)}</text>
                </g>
              ))}
              <path d={d} fill="none" stroke={stroke} strokeWidth="1.8"
                strokeLinejoin="round" strokeLinecap="round"/>
              {hover && (
                <g>
                  <line x1={hover.x} x2={hover.x} y1={padY} y2={H-padY}
                    stroke={p.muted} strokeDasharray="2 2" strokeWidth="0.5"/>
                  <circle cx={hover.x} cy={hover.y} r="4" fill={p.bg}
                    stroke={stroke} strokeWidth="1.8"/>
                </g>
              )}
              {xLabels.map((l,i)=>{
                const lx = padX + (i/(xLabels.length-1)) * (W - padX*2);
                return <text key={i} x={lx} y={H-2} textAnchor="middle"
                  fontFamily="JetBrains Mono, monospace" fontSize="9"
                  fill={p.faint}>{l}</text>;
              })}
            </svg>
          ) : (
            <div style={{
              height: H, display:'flex', alignItems:'center', justifyContent:'center',
              color: p.faint, fontSize: 12, letterSpacing:'0.1em',
              fontFamily:'"JetBrains Mono", monospace',
            }}>
              {loading
                ? (lang==='ko' ? '실시간 차트 로딩 중…' : 'LOADING LIVE CHART…')
                : (lang==='ko' ? '차트 데이터 없음' : 'NO CHART DATA')}
            </div>
          )}
        </div>

        {/* stats */}
        <div style={{
          padding:'10px 18px 8px', display:'grid',
          gridTemplateColumns:'repeat(4, 1fr)', gap:8,
        }}>
          {[
            [lang==='ko'?'전일종가':'PREV',  fmtPx(livePrev)],
            [lang==='ko'?'고가':'HIGH',      fmtPx(high)],
            [lang==='ko'?'저가':'LOW',       fmtPx(low)],
            [lang==='ko'?'현재가':'LAST',    fmtPx(close)],
          ].map(([k,v])=>(
            <div key={k} style={{
              background: p.surface, borderRadius:11, padding:'9px 10px',
            }}>
              <div style={{
                fontSize:9, letterSpacing:'0.14em', color:p.faint,
                fontFamily:'"JetBrains Mono", monospace', marginBottom:3,
              }}>{k}</div>
              <div style={{
                fontSize:12, fontWeight:600, color:p.text,
                fontFamily:'"JetBrains Mono", monospace',
                fontVariantNumeric:'tabular-nums',
              }}>{v}</div>
            </div>
          ))}
        </div>

        {/* CCI 시그널 — stock.cci 없으면 series 기반으로 근사치 계산 */}
        {(() => {
          let cciVal = stock.cci;
          if (cciVal == null && hasData && series.length >= 10) {
            const recent = series.slice(-Math.min(20, series.length));
            const mean = recent.reduce((a,b)=>a+b,0)/recent.length;
            const mad = recent.reduce((a,b)=>a+Math.abs(b-mean),0)/recent.length || 1;
            const raw = (close - mean) / (0.015 * mad);
            cciVal = Math.max(-200, Math.min(200, Math.round(raw)));
          }
          return cciVal != null ? (
            <div style={{ padding:'4px 18px 14px' }}>
              <CCIBadge cci={cciVal}/>
            </div>
          ) : null;
        })()}

        {/* footer */}
        <div style={{ marginTop:'auto', padding:'12px 22px 22px',
          borderTop:`0.5px solid ${p.line}`,
          fontSize:10, letterSpacing:'0.14em', color:p.faint,
          fontFamily:'"JetBrains Mono", monospace',
          display:'flex', justifyContent:'space-between',
        }}>
          <span>{lang==='ko'?'Yahoo Finance · 15분 지연될 수 있음':'Yahoo Finance · MAY BE 15M DELAYED'}</span>
          <span>{stock.sym}</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { StockChartSheet });
