/* ─── 드림팀 빌더 상세 화면 ────────────────────────────────────────────── */

(function seedToolPlayers() {
  if (window.KB_DATA && window.KB_DATA.toolPlayers) return;
  window.KB_DATA = window.KB_DATA || {};
  window.KB_DATA.toolPlayers = [
    // 한국인 MLB 5
    { id:"lee-jh",   ko:"이정후", team:"SF",  lg:"MLB", pos:"OF", ops:.908, war:2.6, sal:11.3, color:"#FD5A1E" },
    { id:"kim-hs",   ko:"김하성", team:"TB",  lg:"MLB", pos:"SS", ops:.748, war:1.4, sal: 8.0, color:"#092C5C" },
    { id:"kim-hys",  ko:"김혜성", team:"LAD", lg:"MLB", pos:"2B", ops:.812, war:1.8, sal: 4.7, color:"#005A9C" },
    { id:"choi-jm",  ko:"최지만", team:"SD",  lg:"MLB", pos:"1B", ops:.721, war:0.9, sal: 5.5, color:"#2F241D" },
    { id:"go-ws",    ko:"고우석", team:"MIA", lg:"MLB", pos:"P",  ops:.000, war:1.1, sal: 4.5, color:"#00A3E0" },
    // KBO 스타 15
    { id:"austin",   ko:"오스틴", team:"LG",  lg:"KBO", pos:"1B", ops:1.082, war:4.1, sal: 1.5, color:"#C30452" },
    { id:"choi-j",   ko:"최정",   team:"SSG", lg:"KBO", pos:"3B", ops:1.041, war:3.9, sal: 2.4, color:"#CE0E2D" },
    { id:"kim-dy",   ko:"김도영", team:"KIA", lg:"KBO", pos:"3B", ops:1.018, war:4.2, sal: 0.9, color:"#EA0029" },
    { id:"koo-jw",   ko:"구자욱", team:"삼성", lg:"KBO", pos:"OF", ops: .988, war:3.4, sal: 2.0, color:"#074CA1" },
    { id:"song-sm",  ko:"송성문", team:"키움", lg:"KBO", pos:"3B", ops: .961, war:3.1, sal: 0.6, color:"#570514" },
    { id:"noh-sh",   ko:"노시환", team:"한화", lg:"KBO", pos:"3B", ops: .947, war:2.8, sal: 1.1, color:"#FA4616" },
    { id:"yang-uj",  ko:"양의지", team:"두산", lg:"KBO", pos:"C",  ops: .934, war:2.7, sal: 5.0, color:"#131230" },
    { id:"park-bh",  ko:"박병호", team:"KT",  lg:"KBO", pos:"1B", ops: .921, war:2.5, sal: 1.5, color:"#000000" },
    { id:"han-ys",   ko:"한유섬", team:"SSG", lg:"KBO", pos:"OF", ops: .909, war:2.2, sal: 1.2, color:"#CE0E2D" },
    { id:"lee-jy",   ko:"이재현", team:"삼성", lg:"KBO", pos:"SS", ops: .855, war:1.9, sal: 0.4, color:"#074CA1" },
    { id:"park-ch",  ko:"박찬호", team:"KIA", lg:"KBO", pos:"SS", ops: .808, war:2.6, sal: 0.5, color:"#EA0029" },
    { id:"kim-yh",   ko:"김영웅", team:"삼성", lg:"KBO", pos:"3B", ops: .824, war:1.7, sal: 0.3, color:"#074CA1" },
    { id:"kim-ks",   ko:"김광현", team:"SSG", lg:"KBO", pos:"P",  ops: .000, war:3.2, sal: 7.0, color:"#CE0E2D" },
    { id:"yang-hj",  ko:"양현종", team:"KIA", lg:"KBO", pos:"P",  ops: .000, war:2.8, sal: 5.0, color:"#EA0029" },
    { id:"ryu-hj",   ko:"류현진", team:"한화", lg:"KBO", pos:"P",  ops: .000, war:3.5, sal:17.0, color:"#FA4616" },
    { id:"an-wj",    ko:"안우진", team:"키움", lg:"KBO", pos:"P",  ops: .000, war:2.4, sal: 1.5, color:"#570514" },
    { id:"moon-dj",  ko:"문동주", team:"한화", lg:"KBO", pos:"P",  ops: .000, war:1.9, sal: 0.6, color:"#FA4616" },
  ];
})();

function ToolDreamteam({ onClose }) {
  const POS_ORDER = ["전체","C","1B","2B","3B","SS","OF"];
  const [tab, setTab] = React.useState("ALL"); // KBO / MLB / ALL
  const [pos, setPos] = React.useState("전체");
  const [q, setQ] = React.useState("");
  const [lineup, setLineup] = React.useState(Array(9).fill(null));
  const [rotation, setRotation] = React.useState(Array(5).fill(null));
  const [share, setShare] = React.useState(false);

  const pool = window.KB_DATA.toolPlayers;
  const usedIds = new Set([...lineup,...rotation].filter(Boolean).map(p=>p.id));

  const batters = pool.filter(p => p.pos !== "P");
  const pitchers = pool.filter(p => p.pos === "P");

  const filteredBatters = batters.filter(p =>
    (tab==="ALL" || p.lg === tab) &&
    (pos==="전체" || p.pos === pos) &&
    (q==="" || p.ko.includes(q) || p.team.includes(q))
  ).sort((a,b)=> b.ops - a.ops);

  const filteredPitchers = pitchers.filter(p =>
    (tab==="ALL" || p.lg === tab) &&
    (q==="" || p.ko.includes(q) || p.team.includes(q))
  ).sort((a,b)=> b.war - a.war);

  const addToLineup = (p) => {
    if (usedIds.has(p.id)) return;
    if (p.pos === "P") {
      const idx = rotation.indexOf(null);
      if (idx < 0) return;
      const next = [...rotation]; next[idx] = p; setRotation(next);
    } else {
      const idx = lineup.indexOf(null);
      if (idx < 0) return;
      const next = [...lineup]; next[idx] = p; setLineup(next);
    }
  };
  const removeBatter = (i) => { const n=[...lineup]; n[i]=null; setLineup(n); };
  const removePitcher = (i) => { const n=[...rotation]; n[i]=null; setRotation(n); };

  // summary
  const filledBat = lineup.filter(Boolean);
  const filledPit = rotation.filter(Boolean);
  const teamValue = [...filledBat,...filledPit].reduce((s,p)=>s+p.sal,0);
  const avgOps = filledBat.length ? (filledBat.reduce((s,p)=>s+p.ops,0)/filledBat.length) : 0;
  const avgSal = (filledBat.length+filledPit.length) ? (teamValue/(filledBat.length+filledPit.length)) : 0;

  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-dreamteam.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명 + 선발 5명</h2>
          </div>
        </div>

        {/* body */}
        <div className="dt-wrap">
          {/* LEFT: lineup */}
          <div style={{display:"flex",flexDirection:"column",gap:14}}>
            <div className="dt-panel">
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:10}}>
                <div className="eyebrow">타순 1~9</div>
                <span className="num" style={{fontSize:11,color:"var(--text-3)"}}>{filledBat.length}/9</span>
              </div>
              <div style={{display:"flex",flexDirection:"column",gap:6}}>
                {lineup.map((p,i)=>(
                  <div key={i} className={`dt-slot${p?" filled":""}`}>
                    <span className="order">{i+1}</span>
                    {p ? (
                      <div style={{display:"flex",alignItems:"center",gap:10,minWidth:0}}>
                        <div className="pp-av" style={{background:p.color,width:32,height:32,fontSize:11}}>{p.ko[0]}</div>
                        <div style={{minWidth:0}}>
                          <div className="pp-name">{p.ko}</div>
                          <div className="pp-sub">{p.lg} · {p.team} · {p.pos} · OPS {p.ops.toFixed(3).replace(/^0/,"")}</div>
                        </div>
                      </div>
                    ) : <span className="empty">선수를 추가하세요</span>}
                    {p && <button className="remove" onClick={()=>removeBatter(i)}>✕</button>}
                  </div>
                ))}
              </div>
            </div>
            <div className="dt-panel">
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:10}}>
                <div className="eyebrow">선발 로테이션 (5)</div>
                <span className="num" style={{fontSize:11,color:"var(--text-3)"}}>{filledPit.length}/5</span>
              </div>
              <div style={{display:"flex",flexDirection:"column",gap:6}}>
                {rotation.map((p,i)=>(
                  <div key={i} className={`dt-slot${p?" filled":""}`}>
                    <span className="order">SP{i+1}</span>
                    {p ? (
                      <div style={{display:"flex",alignItems:"center",gap:10,minWidth:0}}>
                        <div className="pp-av" style={{background:p.color,width:32,height:32,fontSize:11}}>{p.ko[0]}</div>
                        <div style={{minWidth:0}}>
                          <div className="pp-name">{p.ko}</div>
                          <div className="pp-sub">{p.lg} · {p.team} · WAR {p.war.toFixed(1)}</div>
                        </div>
                      </div>
                    ) : <span className="empty">투수를 추가하세요</span>}
                    {p && <button className="remove" onClick={()=>removePitcher(i)}>✕</button>}
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* RIGHT: player pool */}
          <div className="dt-panel" style={{display:"flex",flexDirection:"column",gap:12}}>
            <div className="dt-search">
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{color:"var(--text-3)"}}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
              <input value={q} onChange={(e)=>setQ(e.target.value)} placeholder="선수 이름 또는 팀 검색"/>
            </div>
            <div className="chip-row">
              {["ALL","KBO","MLB"].map(t=>(
                <span key={t} className={`chip ${tab===t?(t==="KBO"?"on kbo":"on"):""}`} onClick={()=>setTab(t)}>{t==="ALL"?"전체 리그":t}</span>
              ))}
            </div>
            <div className="chip-row">
              {POS_ORDER.map(p=>(
                <span key={p} className={`chip ${pos===p?"on":""}`} onClick={()=>setPos(p)}>{p}</span>
              ))}
            </div>

            <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginTop:6}}>
              <div className="eyebrow">야수 풀</div>
              <span className="num" style={{fontSize:11,color:"var(--text-3)"}}>{filteredBatters.length}명</span>
            </div>
            <div className="pp-list">
              {filteredBatters.map(p => {
                const added = usedIds.has(p.id);
                return (
                  <div key={p.id} className={`pp-row${added?" added":""}`} onClick={()=>!added && addToLineup(p)}>
                    <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.pos}</div>
                    </div>
                    <div className="pp-stat">OPS {p.ops.toFixed(3).replace(/^0/,"")}</div>
                    <button className="pp-add">{added?"✓":"+"}</button>
                  </div>
                );
              })}
              {filteredBatters.length === 0 && <div style={{textAlign:"center",padding:14,color:"var(--text-3)",fontSize:12}}>조건에 맞는 선수가 없습니다</div>}
            </div>

            <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginTop:6}}>
              <div className="eyebrow">투수 풀</div>
              <span className="num" style={{fontSize:11,color:"var(--text-3)"}}>{filteredPitchers.length}명</span>
            </div>
            <div className="pp-list" style={{maxHeight:180}}>
              {filteredPitchers.map(p => {
                const added = usedIds.has(p.id);
                return (
                  <div key={p.id} className={`pp-row${added?" added":""}`} onClick={()=>!added && addToLineup(p)}>
                    <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</div>
                    </div>
                    <div className="pp-stat">WAR {p.war.toFixed(1)}</div>
                    <button className="pp-add">{added?"✓":"+"}</button>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* footer summary */}
        <div className="dt-summary">
          <div><div className="k">라인업 가치</div><div className="v">{teamValue.toFixed(1)}<span style={{fontSize:11,color:"var(--text-3)",fontWeight:500,marginLeft:3}}>M USD</span></div></div>
          <div><div className="k">예상 OPS</div><div className="v">{avgOps>0?avgOps.toFixed(3).replace(/^0/,""):"—"}</div></div>
          <div><div className="k">평균 연봉</div><div className="v">{avgSal.toFixed(1)}<span style={{fontSize:11,color:"var(--text-3)",fontWeight:500,marginLeft:3}}>M</span></div></div>
          <div style={{display:"flex",alignItems:"center",justifyContent:"flex-end"}}>
            <button className="btn btn-primary" onClick={()=>setShare(true)} disabled={filledBat.length<3}>공유 카드 만들기</button>
          </div>
        </div>

        {/* footnote */}
        <div style={{padding:"10px 24px 16px",fontSize:11,color:"var(--text-3)"}}>
          ※ 라인업 평가는 시즌 기록 기반 참고용 데이터 분석 자료입니다.
        </div>
      </div>

      {share && (
        <ShareModal lineup={filledBat} rotation={filledPit} avgOps={avgOps} value={teamValue}
                    onClose={()=>setShare(false)}/>
      )}
    </div>
  );
}

function ShareModal({ lineup, rotation, avgOps, value, onClose }) {
  return (
    <div className="lock-modal" style={{zIndex:95}} onClick={onClose}>
      <div className="lock-modal-inner" style={{maxWidth:420}} onClick={(e)=>e.stopPropagation()}>
        <div className="eyebrow" style={{color:"var(--mlb)",marginBottom:8}}>공유 카드 미리보기</div>
        <h3 style={{margin:"0 0 14px",fontSize:18,fontWeight:700}}>나만의 드림팀 · 1080×1350</h3>

        <div className="share-stage">
          <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
            <div style={{fontSize:11,fontWeight:700,letterSpacing:"0.16em",color:"var(--mlb)"}}>나의 드림팀</div>
            <div className="num" style={{fontSize:10,color:"var(--text-3)"}}>2026</div>
          </div>
          <div className="stage-grid">
            {Array.from({length:9}).map((_,i)=>{
              const p = lineup[i];
              return (
                <div key={i} className="sg-cell">
                  <span className="o">{i+1}번</span>
                  {p ? (
                    <>
                      <div className="pp-av" style={{background:p.color}}>{p.ko[0]}</div>
                      <div className="n">{p.ko}</div>
                      <div className="num" style={{fontSize:9.5,color:"var(--text-3)"}}>{p.team}</div>
                    </>
                  ) : (
                    <div style={{color:"var(--text-3)",fontSize:10,marginTop:6}}>—</div>
                  )}
                </div>
              );
            })}
          </div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:6,fontSize:10}}>
            <div><div style={{color:"var(--text-3)"}}>OPS</div><div className="num" style={{fontWeight:700,fontSize:13}}>{avgOps>0?avgOps.toFixed(3).replace(/^0/,""):"—"}</div></div>
            <div><div style={{color:"var(--text-3)"}}>가치</div><div className="num" style={{fontWeight:700,fontSize:13}}>${value.toFixed(1)}M</div></div>
            <div><div style={{color:"var(--text-3)"}}>선발</div><div className="num" style={{fontWeight:700,fontSize:13}}>{rotation.length}/5</div></div>
          </div>
          <div className="stage-foot">
            <span>Dualbat</span>
            <span>참고용 데이터 분석</span>
          </div>
        </div>

        <div style={{display:"flex",gap:8,marginTop:16}}>
          <button className="btn btn-ghost" style={{flex:1}} onClick={onClose}>닫기</button>
          <button className="btn btn-primary" style={{flex:1}} onClick={()=>{console.log("share"); onClose();}}>이미지로 저장</button>
        </div>
      </div>
    </div>
  );
}

window.ToolDreamteam = ToolDreamteam;
