/* ─── Dual-career line chart: 이정후 KBO → MLB ────────────────────────── */
/* Uses Chart.js (loaded in index.html). One canvas, two datasets that share x-axis. */

function CareerChart() {
  const ref = React.useRef(null);
  const chartRef = React.useRef(null);
  const [metric, setMetric] = React.useState("ops");

  React.useEffect(() => {
    if (!ref.current) return;
    if (chartRef.current) { chartRef.current.destroy(); }

    const seasons = window.KB_DATA.career.seasons;
    const labels = seasons.map(s => s.y);

    // Build dual datasets: KBO points where lg==='kbo', MLB points where lg==='mlb'
    const kboData = seasons.map(s => s.lg === "kbo" ? s[metric] : null);
    const mlbData = seasons.map(s => s.lg === "mlb" ? s[metric] : null);

    const ctx = ref.current.getContext("2d");

    // Gradient fills
    const kboGrad = ctx.createLinearGradient(0, 0, 0, 280);
    kboGrad.addColorStop(0, "rgba(75,156,255,0.32)");
    kboGrad.addColorStop(1, "rgba(75,156,255,0)");
    const mlbGrad = ctx.createLinearGradient(0, 0, 0, 280);
    mlbGrad.addColorStop(0, "rgba(255,75,75,0.32)");
    mlbGrad.addColorStop(1, "rgba(255,75,75,0)");

    chartRef.current = new Chart(ctx, {
      type: "line",
      data: {
        labels,
        datasets: [
          {
            label: "KBO (키움)",
            data: kboData,
            borderColor: "#4B9CFF",
            backgroundColor: kboGrad,
            borderWidth: 2.5,
            pointRadius: 5,
            pointHoverRadius: 7,
            pointBackgroundColor: "#4B9CFF",
            pointBorderColor: "#0B0E14",
            pointBorderWidth: 2,
            tension: 0.32,
            fill: true,
            spanGaps: false,
          },
          {
            label: "MLB (SF)",
            data: mlbData,
            borderColor: "#FF4B4B",
            backgroundColor: mlbGrad,
            borderWidth: 2.5,
            pointRadius: 5,
            pointHoverRadius: 7,
            pointBackgroundColor: "#FF4B4B",
            pointBorderColor: "#0B0E14",
            pointBorderWidth: 2,
            tension: 0.32,
            fill: true,
            spanGaps: false,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: { mode: "index", intersect: false },
        plugins: {
          legend: { display: false },
          tooltip: {
            backgroundColor: "#161B22",
            borderColor: "rgba(255,255,255,0.14)",
            borderWidth: 1,
            padding: 12,
            titleColor: "#E6EDF3",
            bodyColor: "#8B949E",
            titleFont: { family: "Inter", weight: "600", size: 12 },
            bodyFont: { family: "Inter", size: 12 },
            displayColors: true,
            boxPadding: 4,
            callbacks: {
              label: (ctx) => {
                if (ctx.parsed.y === null) return null;
                const k = metric === "ops" ? "OPS" : metric === "war" ? "WAR" : "HR";
                const v = metric === "ops" ? ctx.parsed.y.toFixed(3).replace(/^0/,"") : ctx.parsed.y.toFixed(1);
                return `${ctx.dataset.label}  ${k} ${v}`;
              }
            }
          }
        },
        scales: {
          x: {
            grid: { color: "rgba(255,255,255,0.04)", drawTicks: false },
            ticks: { color: "#6E7681", font: { family: "Inter", size: 11 } },
            border: { color: "rgba(255,255,255,0.08)" }
          },
          y: {
            grid: { color: "rgba(255,255,255,0.04)" },
            ticks: {
              color: "#6E7681",
              font: { family: "Inter", size: 11 },
              callback: (v) => metric === "ops" ? Number(v).toFixed(2).replace(/^0/,"") : v
            },
            border: { display: false }
          }
        }
      }
    });

    return () => { if (chartRef.current) chartRef.current.destroy(); };
  }, [metric]);

  const c = window.KB_DATA.career;
  const last = c.seasons[c.seasons.length - 1];
  const peakKbo = c.seasons.filter(s => s.lg === "kbo").reduce((a,b) => b.ops > a.ops ? b : a);

  return (
    <section className="section">
      <div className="section-head">
        <div>
          <div className="eyebrow" style={{marginBottom:6}}>이중 커리어</div>
          <h2>이정후 KBO → MLB 여정</h2>
        </div>
        <div className="tabs">
          {[["ops","OPS"],["war","WAR"],["hr","HR"]].map(([k,l])=>(
            <button key={k} className={metric===k?"on":""} onClick={()=>setMetric(k)}>{l}</button>
          ))}
        </div>
      </div>

      <div className="card" style={{padding:24}}>
        {/* Header strip — legend + key milestones */}
        <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:16,marginBottom:18}}>
          <div style={{display:"flex",gap:18,alignItems:"center",flexWrap:"wrap"}}>
            <div style={{display:"flex",alignItems:"center",gap:8}}>
              <span style={{width:10,height:10,borderRadius:"50%",background:"var(--kbo)"}}/>
              <span style={{fontSize:13,fontWeight:600}}>KBO</span>
              <span className="num" style={{fontSize:12,color:"var(--text-3)"}}>2017–2022 · 키움 히어로즈</span>
            </div>
            <div style={{display:"flex",alignItems:"center",gap:8}}>
              <span style={{width:10,height:10,borderRadius:"50%",background:"var(--mlb)"}}/>
              <span style={{fontSize:13,fontWeight:600}}>MLB</span>
              <span className="num" style={{fontSize:12,color:"var(--text-3)"}}>2024– · 샌프란시스코</span>
            </div>
          </div>
          <div style={{display:"flex",gap:14}}>
            <div style={{textAlign:"right"}}>
              <div style={{fontSize:11,color:"var(--text-3)",letterSpacing:"0.04em"}}>KBO 정점</div>
              <div className="num" style={{fontSize:18,fontWeight:700}}>{peakKbo.ops.toFixed(3).replace(/^0/,"")} <span style={{fontSize:11,color:"var(--text-3)",fontWeight:500}}>{peakKbo.y.split(" ")[0]}</span></div>
            </div>
            <div style={{textAlign:"right"}}>
              <div style={{fontSize:11,color:"var(--text-3)",letterSpacing:"0.04em"}}>현재 MLB</div>
              <div className="num" style={{fontSize:18,fontWeight:700,color:"var(--mlb)"}}>{last.ops.toFixed(3).replace(/^0/,"")} <span style={{fontSize:11,color:"var(--text-3)",fontWeight:500}}>2026</span></div>
            </div>
          </div>
        </div>

        <div style={{height:300,position:"relative"}}>
          <canvas ref={ref}/>
        </div>

        <div style={{display:"flex",justifyContent:"space-between",marginTop:14,paddingTop:14,borderTop:"1px solid var(--hairline)",fontSize:12,color:"var(--text-3)",flexWrap:"wrap",gap:8}}>
          <span>※ 2023년은 부상으로 시즌 데이터 없음 (점선 구간)</span>
          <span>출처 · KBO 공식 · MLB Stats API</span>
        </div>
      </div>
    </section>
  );
}

window.CareerChart = CareerChart;
