/* ─── 히트존 매핑 상세 화면 ────────────────────────────────────────────── */

/* 5×5 zone, 안쪽 3×3이 스트라이크 존. 각 셀에 더미 (avg, slg, n). */
const HZ_PLAYERS = {
  "lee-jh":  { ko:"이정후", team:"SF",  lg:"MLB", color:"#FD5A1E", role:"좌타자" },
  "kim-hys": { ko:"김혜성", team:"LAD", lg:"MLB", color:"#005A9C", role:"좌타자" },
  "kim-hs":  { ko:"김하성", team:"TB",  lg:"MLB", color:"#092C5C", role:"우타자" },
  "kim-dy":  { ko:"김도영", team:"KIA", lg:"KBO", color:"#EA0029", role:"좌타자" },
  "austin":  { ko:"오스틴", team:"LG",  lg:"KBO", color:"#C30452", role:"우타자" },
};

/* 5×5 matrix of {avg, slg, n}. Inner 3×3 are strike zone. */
function makeZone(seed=1) {
  // simple deterministic-ish dummy zone for each player+hand+season combo
  const rng = (a,b,k)=> {
    const x = Math.sin((a+1)*(b+2)*seed + k)*10000;
    return x - Math.floor(x);
  };
  const grid = [];
  for (let r=0; r<5; r++){
    const row = [];
    for (let c=0; c<5; c++){
      const strike = r>=1 && r<=3 && c>=1 && c<=3;
      const base = strike ? 0.25 : 0.18;
      const center = (r===2 && c===2) ? 0.12 : (r===2||c===2) && strike ? 0.07 : 0;
      const noise = rng(r,c,0)*0.10;
      const avg = Math.max(0.12, Math.min(0.52, base + center + noise));
      const slg = Math.max(0.18, Math.min(0.92, avg + 0.18 + rng(r,c,1)*0.22));
      const n   = strike ? 28 + Math.floor(rng(r,c,2)*42) : 8 + Math.floor(rng(r,c,2)*16);
      row.push({avg,slg,n,strike});
    }
    grid.push(row);
  }
  return grid;
}

const ZONE_NAMES = [
  ["하이 아웃","하이 인","하이 센터","하이 가까이","하이 몸쪽"],
  ["바깥 높음","아웃 하이","상단","인 하이","몸쪽 높음"],
  ["바깥","아웃","센터","인","몸쪽"],
  ["바깥 낮음","아웃 로우","하단","인 로우","몸쪽 낮음"],
  ["로우 아웃","로우 인","로우 센터","로우 가까이","로우 몸쪽"],
];

function ToolHeatzone({ onClose }) {
  const [pid, setPid] = React.useState("lee-jh");
  const [hand, setHand] = React.useState("R"); // 상대 투수 손
  const [season, setSeason] = React.useState("2026");
  const [hover, setHover] = React.useState(null);

  const player = HZ_PLAYERS[pid];
  const seedKey = pid.length + (hand==="R"?2:5) + season.charCodeAt(3);
  const zone = React.useMemo(() => makeZone(seedKey), [pid,hand,season]);

  const flat = [];
  zone.forEach((row,r)=>row.forEach((c,i)=>flat.push({r,c:i,...c,name:ZONE_NAMES[r][i]})));
  const strikes = flat.filter(c=>c.strike).sort((a,b)=>b.avg-a.avg);
  const top3    = strikes.slice(0,3);
  const bot3    = [...strikes].sort((a,b)=>a.avg-b.avg).slice(0,3);
  const maxAvg = Math.max(...flat.map(c=>c.avg));

  return (
    <div className="tool-overlay" onClick={onClose}>
      <div className="tool-overlay-inner" onClick={(e)=>e.stopPropagation()}>
        {/* banner */}
        <div style={{
          height:320,
          position:"relative",
          backgroundImage:`linear-gradient(180deg, rgba(11,14,20,0.30) 0%, rgba(11,14,20,0.90) 100%), url('images/sections/tool-heatzone.png')`,
          backgroundSize:"cover",
          backgroundPosition:"center",
        }}>
          <button className="tool-close" onClick={onClose} style={{position:"absolute",top:18,right:18,zIndex:2,background:"rgba(11,14,20,0.6)",backdropFilter:"blur(8px)"}}>✕</button>
          <div style={{position:"absolute",left:24,bottom:20,right:24}}>
            <div className="eb" style={{color:"var(--mlb)"}}>인터랙티브 도구</div>
            <h2 style={{margin:"4px 0 0",fontSize:28,fontWeight:800,letterSpacing:"-0.025em"}}>히트존 매핑 — 9구역 타율 시각화</h2>
          </div>
        </div>

        <div className="hz-wrap">
          {/* LEFT: controls */}
          <div className="dt-panel" style={{display:"flex",flexDirection:"column",gap:14}}>
            <div>
              <div className="eyebrow" style={{marginBottom:8}}>선수 선택</div>
              <div style={{display:"flex",flexDirection:"column",gap:6}}>
                {Object.entries(HZ_PLAYERS).map(([id,p])=>(
                  <div key={id} className={`pp-row${pid===id?" added":""}`} onClick={()=>setPid(id)}>
                    <div className="pp-av" style={{background:p.color}}>{p.ko[0]}</div>
                    <div>
                      <div className="pp-name">{p.ko}</div>
                      <div className="pp-sub">{p.lg} · {p.team} · {p.role}</div>
                    </div>
                    <div className="pp-stat" style={{minWidth:0}}></div>
                    <button className="pp-add">{pid===id?"✓":""}</button>
                  </div>
                ))}
              </div>
            </div>

            <div>
              <div className="eyebrow" style={{marginBottom:8}}>상대 투수</div>
              <div className="chip-row">
                {[["R","우완"],["L","좌완"]].map(([k,l])=>(
                  <span key={k} className={`chip ${hand===k?"on":""}`} onClick={()=>setHand(k)}>{l}</span>
                ))}
              </div>
            </div>

            <div>
              <div className="eyebrow" style={{marginBottom:8}}>시즌</div>
              <div className="chip-row">
                {["2024","2025","2026"].map(s=>(
                  <span key={s} className={`chip ${season===s?"on kbo":""}`} onClick={()=>setSeason(s)}>{s}</span>
                ))}
              </div>
            </div>
          </div>

          {/* CENTER: zone */}
          <div className="hz-stage">
            <div style={{textAlign:"center"}}>
              <div style={{fontSize:18,fontWeight:700,letterSpacing:"-0.02em"}}>{player.ko}<span style={{fontSize:13,color:"var(--text-3)",fontWeight:500,marginLeft:8}}>{season} · {hand==="R"?"우완":"좌완"} 상대</span></div>
              <div className="num" style={{fontSize:11,color:"var(--text-3)",marginTop:2}}>표본 {flat.reduce((s,c)=>s+c.n,0)}타석</div>
            </div>

            <div className="hz-zone">
              {zone.flatMap((row,r)=>row.map((cell,c)=>{
                const heat = (cell.avg / maxAvg);
                const bg = `color-mix(in oklab, var(--mlb) ${Math.round(heat*92)}%, transparent)`;
                const isHov = hover && hover.r===r && hover.c===c;
                return (
                  <div key={`${r}-${c}`} className={`hz-cell${cell.strike?" strike":""}`}
                       style={{background:bg, opacity: cell.strike?1:0.55}}
                       onMouseEnter={()=>setHover({r,c,...cell})}
                       onMouseLeave={()=>setHover(null)}>
                    {isHov && (
                      <div className="hz-cell-tip">
                        <div style={{fontSize:10,color:"var(--text-3)",letterSpacing:"0.04em"}}>{ZONE_NAMES[r][c]}</div>
                        <div className="tipnum">.{Math.round(cell.avg*1000).toString().padStart(3,"0")}</div>
                        <div style={{display:"flex",gap:10,marginTop:2}}>
                          <span>SLG <span className="num" style={{color:"var(--text)",fontWeight:600}}>.{Math.round(cell.slg*1000).toString().padStart(3,"0")}</span></span>
                          <span>n <span className="num" style={{color:"var(--text)",fontWeight:600}}>{cell.n}</span></span>
                        </div>
                      </div>
                    )}
                  </div>
                );
              }))}
            </div>

            <div style={{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"var(--text-3)"}}>
              <span>차가움</span>
              <div style={{flex:1,height:6,borderRadius:3,background:"linear-gradient(90deg, color-mix(in oklab, var(--mlb) 8%, transparent), var(--mlb))",minWidth:160}}/>
              <span>뜨거움</span>
            </div>

            {/* opponent pitcher type bar */}
            <div style={{width:"100%"}}>
              <div className="eyebrow" style={{marginBottom:8}}>상대 투수 구종 분포</div>
              <div style={{display:"flex",flexDirection:"column",gap:8}}>
                {[
                  {k:"포심 패스트볼", p:42, c:"var(--mlb)"},
                  {k:"슬라이더",      p:24, c:"var(--kbo)"},
                  {k:"체인지업",      p:18, c:"var(--warn)"},
                  {k:"커브",           p:11, c:"var(--pos)"},
                  {k:"기타",           p: 5, c:"var(--text-3)"},
                ].map((r,i)=>(
                  <div key={i} style={{display:"grid",gridTemplateColumns:"100px 1fr 40px",alignItems:"center",gap:10,fontSize:12}}>
                    <span style={{color:"var(--text-2)"}}>{r.k}</span>
                    <div style={{height:6,background:"rgba(255,255,255,0.06)",borderRadius:3}}>
                      <div style={{width:`${r.p}%`,height:"100%",background:r.c,borderRadius:3}}/>
                    </div>
                    <span className="num" style={{color:"var(--text-3)",textAlign:"right"}}>{r.p}%</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* RIGHT: strengths / weaknesses */}
          <div style={{display:"flex",flexDirection:"column",gap:14}}>
            <div className="dt-panel">
              <div className="eyebrow" style={{marginBottom:10,color:"var(--mlb)"}}>강점 코스 TOP 3</div>
              <div className="hz-list">
                {top3.map((c,i)=>(
                  <div key={i} className="row">
                    <span className="rk">{i+1}</span>
                    <ZoneMini r={c.r} ci={c.c}/>
                    <div>
                      <div style={{fontSize:13,fontWeight:600}}>{c.name}</div>
                      <div className="desc num">SLG .{Math.round(c.slg*1000).toString().padStart(3,"0")} · n {c.n}</div>
                    </div>
                    <span className="v" style={{color:"var(--mlb)"}}>.{Math.round(c.avg*1000).toString().padStart(3,"0")}</span>
                  </div>
                ))}
              </div>
            </div>

            <div className="dt-panel">
              <div className="eyebrow" style={{marginBottom:10,color:"var(--kbo)"}}>약점 코스 TOP 3</div>
              <div className="hz-list">
                {bot3.map((c,i)=>(
                  <div key={i} className="row">
                    <span className="rk">{i+1}</span>
                    <ZoneMini r={c.r} ci={c.c} cold/>
                    <div>
                      <div style={{fontSize:13,fontWeight:600}}>{c.name}</div>
                      <div className="desc num">SLG .{Math.round(c.slg*1000).toString().padStart(3,"0")} · n {c.n}</div>
                    </div>
                    <span className="v" style={{color:"var(--kbo)"}}>.{Math.round(c.avg*1000).toString().padStart(3,"0")}</span>
                  </div>
                ))}
              </div>
            </div>

            <button className="btn btn-primary" style={{justifySelf:"stretch"}} onClick={()=>console.log("share heatzone")}>공유 카드 만들기</button>
            <div style={{fontSize:11,color:"var(--text-3)",textAlign:"center"}}>
              ※ 표본 30타석 이하 코스는 참고용 데이터 분석 자료로만 활용하세요.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* 3×3 mini zone with one cell highlighted */
function ZoneMini({ r, ci, cold }) {
  // map 5×5 strike cells (r in [1..3], ci in [1..3]) to 3×3 inner cells
  const rr = r-1, cc = ci-1;
  return (
    <div className="mini">
      {Array.from({length:9}).map((_,k)=>{
        const x = k%3, y = Math.floor(k/3);
        const on = (x===cc && y===rr);
        return <i key={k} style={{background: on ? (cold?"var(--kbo)":"var(--mlb)") : "rgba(255,255,255,0.06)"}}/>;
      })}
    </div>
  );
}

window.ToolHeatzone = ToolHeatzone;
