/* ─── Sections: Hero, Analysis cards, Carousel, Leaderboard, Guide, CTA, Footer, MobileTabBar ─── */

const { useState, useMemo, useEffect, useRef } = React;
const D = window.KB_DATA;

/* ─── Tiny inline icons ─────────────────────────────────────────────── */
const I = {
  search: (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>,
  moon:   (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 12.5A8.5 8.5 0 1 1 11.5 3a7 7 0 0 0 9.5 9.5z"/></svg>,
  star:   (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 17.3 5.8 21l1.6-7-5.4-4.7 7-.6L12 2l3 6.7 7 .6-5.4 4.7L18.2 21z"/></svg>,
  bell:   (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M6 8a6 6 0 1 1 12 0c0 7 3 8 3 8H3s3-1 3-8"/><path d="M10 21a2 2 0 0 0 4 0"/></svg>,
  arrow:  (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  home:   (p) => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/></svg>,
  user:   (p) => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>,
  chart:  (p) => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 21V5"/><path d="M7 21V12"/><path d="M11 21V8"/><path d="M15 21v-6"/><path d="M19 21V3"/></svg>,
  pin:    (p) => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 17v5"/><path d="M9 10V4h6v6l3 4H6z"/></svg>,
  menu:   (p) => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M4 6h16M4 12h16M4 18h16"/></svg>,
  vs:     (p) => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="7" cy="12" r="3"/><circle cx="17" cy="12" r="3"/><path d="M10 12h4"/></svg>,
};

/* ─── Sparkline SVG ─────────────────────────────────────────────────── */
function Sparkline({ data, color = "var(--mlb)", h = 36 }) {
  const w = 220;
  const min = Math.min(...data), max = Math.max(...data);
  const span = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - 4 - ((v - min) / span) * (h - 8);
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  });
  const path = `M ${pts.join(" L ")}`;
  const fill = `M 0,${h} L ${pts.join(" L ")} L ${w},${h} Z`;
  const id = useMemo(() => "g" + Math.random().toString(36).slice(2, 7), []);
  return (
    <svg className="spark" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <defs>
        <linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor={color} stopOpacity=".35"/>
          <stop offset="1" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={fill} fill={`url(#${id})`}/>
      <path d={path} stroke={color} strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      <circle cx={w} cy={h - 4 - ((data[data.length-1] - min) / span) * (h - 8)} r="2.6" fill={color}/>
    </svg>
  );
}

/* ─── Strike-zone heatmap (decorative) ──────────────────────────────── */
function ZoneHeat({ accent = "var(--mlb)" }) {
  const cells = [
    [0.10, 0.18, 0.22, 0.18, 0.10],
    [0.18, 0.42, 0.68, 0.45, 0.20],
    [0.24, 0.72, 0.96, 0.74, 0.26],
    [0.20, 0.55, 0.78, 0.52, 0.22],
    [0.10, 0.20, 0.28, 0.20, 0.10],
  ];
  return (
    <div style={{display:"grid",gridTemplateColumns:"repeat(5,1fr)",gap:2,padding:8,background:"rgba(255,255,255,0.02)",border:"1px solid var(--hairline)",borderRadius:10,width:120,aspectRatio:"1/1"}}>
      {cells.flat().map((v,i)=>(
        <div key={i} style={{background:`color-mix(in oklab, ${accent} ${Math.round(v*100)}%, transparent)`,borderRadius:2}}/>
      ))}
    </div>
  );
}

/* ─── Header ────────────────────────────────────────────────────────── */
function Header() {
  const [active, setActive] = useState("home");
  const items = [
    { id: "home", label: "홈" },
    { id: "matchup", label: "매치업" },
    { id: "mlb",  label: "MLB" },
    { id: "kbo",  label: "KBO" },
    { id: "players", label: "선수" },
    { id: "rank", label: "랭킹" },
    { id: "guide", label: "가이드" },
  ];
  return (
    <header className="hdr">
      <div className="hdr-inner">
        <a className="logo" href="#">
          <span className="logo-mark"/>
          <span>Dualbat<small style={{display:"block",marginTop:2}}>MLB · KBO ANALYTICS</small></span>
        </a>
        <nav className="nav">
          {items.map(x => (
            <a key={x.id} href={`#${x.id}`} className={active===x.id?"active":""} onClick={(e)=>{setActive(x.id);}}>
              {x.label}
            </a>
          ))}
        </nav>
        <div className="hdr-actions">
          <div className="search-pill desktop-only">
            <I.search/> <span>선수, 팀, 지표 검색</span>
            <span className="kbd">⌘ K</span>
          </div>
          <button className="icon-btn" title="다크 모드"><I.moon/></button>
          <button className="icon-btn" title="내 픽"><I.star/></button>
        </div>
      </div>
    </header>
  );
}

/* ─── Hero / live matchup ───────────────────────────────────────────── */
function Hero() {
  const h = D.hero;
  const sp = h.spotlight;
  return (
    <section className="hero" style={{
      padding:"32px 36px",
      backgroundImage: `linear-gradient(rgba(11,14,20,0.55), rgba(11,14,20,0.88)), url('images/hero/stadium-night.png')`,
      backgroundSize: "cover",
      backgroundPosition: "center",
    }}>
      {/* top meta row */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:12,marginBottom:24}}>
        <div style={{display:"flex",alignItems:"center",gap:10}}>
          <span className="tag tag-live"><span className="live-dot"/>LIVE</span>
          <span className="tag tag-mlb">MLB</span>
          <span className="num" style={{fontSize:13,color:"var(--text-2)"}}>{h.status}</span>
        </div>
        <div className="num" style={{fontSize:12,color:"var(--text-3)"}}>{h.venue} · {h.date}</div>
      </div>

      <div className="grid-hero" style={{display:"grid",gridTemplateColumns:"1.2fr 1fr",gap:32,alignItems:"stretch"}}>
        {/* Left: scoreboard + spotlight */}
        <div>
          <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:24}}>
            <div className="team">
              <div className="team-mark lg" style={{background:window.KB_TEAM_LOGOS[h.away.code]?"#1F2630":h.away.fg,overflow:"hidden",padding:window.KB_TEAM_LOGOS[h.away.code]?8:0}}>
                {window.KB_TEAM_LOGOS[h.away.code] ? (
                  <img src={window.KB_TEAM_LOGOS[h.away.code]} alt={h.away.code} style={{width:"100%",height:"100%",objectFit:"contain"}}/>
                ) : h.away.code}
              </div>
              <div style={{fontSize:13,color:"var(--text-2)",marginTop:2}}>{h.away.short}</div>
            </div>
            <div style={{textAlign:"center"}}>
              <div className="num hero-score" style={{fontSize:54,fontWeight:800,letterSpacing:"-0.04em",lineHeight:1}}>
                <span style={{color:"var(--text)"}}>{h.away.score}</span>
                <span style={{color:"var(--text-3)",margin:"0 14px",fontSize:34,verticalAlign:"middle"}}>:</span>
                <span style={{color:"var(--text-2)"}}>{h.home.score}</span>
              </div>
              <div className="num" style={{fontSize:11,color:"var(--text-3)",marginTop:8,letterSpacing:"0.18em"}}>SCORE · 6회초</div>
            </div>
            <div className="team">
              <div className="team-mark lg" style={{background:window.KB_TEAM_LOGOS[h.home.code]?"#1F2630":h.home.fg,overflow:"hidden",padding:window.KB_TEAM_LOGOS[h.home.code]?8:0}}>
                {window.KB_TEAM_LOGOS[h.home.code] ? (
                  <img src={window.KB_TEAM_LOGOS[h.home.code]} alt={h.home.code} style={{width:"100%",height:"100%",objectFit:"contain"}}/>
                ) : h.home.code}
              </div>
              <div style={{fontSize:13,color:"var(--text-2)",marginTop:2}}>{h.home.short}</div>
            </div>
          </div>

          {/* spotlight player block */}
          <div style={{background:"rgba(255,255,255,0.025)",border:"1px solid var(--hairline)",borderRadius:16,padding:20}}>
            <div style={{display:"flex",alignItems:"center",gap:14}}>
              <div className="player-avatar" style={{width:54,height:54,fontSize:18,background:sp.avatarBg,marginBottom:0}}>
                LJH
              </div>
              <div style={{flex:1,minWidth:0}}>
                <div style={{display:"flex",alignItems:"center",gap:8}}>
                  <div style={{fontSize:18,fontWeight:700,letterSpacing:"-0.02em"}}>{sp.player}</div>
                  <span className="tag tag-pos">진행 중</span>
                </div>
                <div style={{fontSize:12,color:"var(--text-3)",marginTop:2}}>
                  <span className="num">{sp.en}</span> · {sp.role}
                </div>
              </div>
              <div style={{textAlign:"right",fontSize:12,color:"var(--text-2)"}}>{sp.vsLine}</div>
            </div>

            <div className="hero-stats" style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:12,marginTop:16}}>
              {sp.stats.map((s, i) => (
                <div key={i} style={{padding:"10px 12px",background:"rgba(255,255,255,0.02)",border:"1px solid var(--hairline)",borderRadius:10}}>
                  <div style={{fontSize:11,color:"var(--text-3)",letterSpacing:"0.04em"}}>{s.k}</div>
                  <div className="num" style={{fontSize:22,fontWeight:700,marginTop:2,letterSpacing:"-0.03em"}}>{s.v}</div>
                  <div style={{fontSize:11,color:"var(--text-3)",marginTop:2}} className="num">{s.d}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Right: at-bat tracker + sidecar */}
        <div style={{display:"flex",flexDirection:"column",gap:16}}>
          <div style={{background:"rgba(255,255,255,0.025)",border:"1px solid var(--hairline)",borderRadius:16,padding:18}}>
            <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:14}}>
              <div className="eyebrow">오늘의 타석</div>
              <div className="num" style={{fontSize:11,color:"var(--text-3)"}}>4 PA</div>
            </div>
            <div style={{display:"flex",gap:14,alignItems:"center"}}>
              <ZoneHeat accent="var(--mlb)"/>
              <div style={{flex:1,display:"flex",flexDirection:"column",gap:6}}>
                {sp.pitches.map((p, i) => (
                  <div key={i} style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 10px",borderRadius:8,background: p.big ? "rgba(255,75,75,0.10)" : "rgba(255,255,255,0.02)",border:"1px solid var(--hairline)"}}>
                    <span style={{fontSize:13,fontWeight: p.big ? 700 : 500,color: p.big ? "var(--mlb)" : "var(--text)"}}>{p.type}</span>
                    <span className="num" style={{fontSize:11,color:"var(--text-3)"}}>{p.h ? `H ${p.h}` : "·"}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div style={{background:"rgba(255,255,255,0.025)",border:"1px solid var(--hairline)",borderRadius:16,padding:18}}>
            <div className="eyebrow" style={{marginBottom:12}}>다른 한국인 선수</div>
            <div style={{display:"flex",flexDirection:"column",gap:10}}>
              {D.hero.sidecar.map((s, i) => (
                <div key={i} style={{display:"flex",alignItems:"center",gap:10}}>
                  <div className="team-mark sm" style={{background:i===0?"#005A9C":i===1?"#092C5C":"#FA4616",fontSize:10}}>{s.team}</div>
                  <div style={{flex:1,fontSize:14,fontWeight:600}}>{s.player}</div>
                  <div style={{fontSize:12,color:"var(--text-2)"}} className="num">{s.line}</div>
                  <span className={`tag tag-${s.tag==="kbo"?"kbo":"mut"}`} style={{fontSize:10}}>{s.tag==="kbo"?"KBO":"휴식"}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── Today's matchups grid ─────────────────────────────────────────── */
function MatchupCard({ m }) {
  const total = m.away.win + m.home.win;
  const aPct = (m.away.win / total) * 100;
  const favorAway = m.away.win >= m.home.win;
  return (
    <article className="card" style={{padding:20,display:"flex",flexDirection:"column",gap:16,cursor:"pointer",transition:"border-color .15s, transform .15s"}}
      onMouseEnter={(e)=>{e.currentTarget.style.borderColor="var(--hairline-strong)"; e.currentTarget.style.transform="translateY(-2px)";}}
      onMouseLeave={(e)=>{e.currentTarget.style.borderColor="var(--hairline)"; e.currentTarget.style.transform="";}}>
      {/* meta */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
        <span className="tag tag-kbo" style={{fontSize:10}}>KBO</span>
        <div className="num" style={{fontSize:11,color:"var(--text-3)",letterSpacing:"0.04em"}}>{m.time} · {m.venue}</div>
      </div>

      {/* matchup row */}
      <div style={{display:"grid",gridTemplateColumns:"1fr auto 1fr",alignItems:"center",gap:12}}>
        <div style={{display:"flex",alignItems:"center",gap:10,minWidth:0}}>
          <div className="team-mark sm" style={{background:window.KB_TEAM_LOGOS[m.away.code]?"#1F2630":m.away.color,fontSize:11,width:40,height:40,overflow:"hidden",padding:window.KB_TEAM_LOGOS[m.away.code]?4:0}}>
            {window.KB_TEAM_LOGOS[m.away.code] ? (
              <img src={window.KB_TEAM_LOGOS[m.away.code]} alt={m.away.code} style={{width:"100%",height:"100%",objectFit:"contain"}}/>
            ) : m.away.code}
          </div>
          <div style={{minWidth:0}}>
            <div style={{fontSize:14,fontWeight:700,letterSpacing:"-0.01em"}}>{m.away.code}</div>
            <div className="num" style={{fontSize:11,color:"var(--text-3)"}}>{m.away.short}</div>
          </div>
        </div>
        <div className="num" style={{fontSize:11,color:"var(--text-3)",fontWeight:600,letterSpacing:"0.1em"}}>VS</div>
        <div style={{display:"flex",alignItems:"center",gap:10,minWidth:0,justifyContent:"flex-end"}}>
          <div style={{minWidth:0,textAlign:"right"}}>
            <div style={{fontSize:14,fontWeight:700,letterSpacing:"-0.01em"}}>{m.home.code}</div>
            <div className="num" style={{fontSize:11,color:"var(--text-3)"}}>{m.home.short}</div>
          </div>
          <div className="team-mark sm" style={{background:window.KB_TEAM_LOGOS[m.home.code]?"#1F2630":m.home.color,fontSize:11,width:40,height:40,overflow:"hidden",padding:window.KB_TEAM_LOGOS[m.home.code]?4:0}}>
            {window.KB_TEAM_LOGOS[m.home.code] ? (
              <img src={window.KB_TEAM_LOGOS[m.home.code]} alt={m.home.code} style={{width:"100%",height:"100%",objectFit:"contain"}}/>
            ) : m.home.code}
          </div>
        </div>
      </div>

      {/* starting pitchers */}
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,padding:"10px 12px",background:"rgba(255,255,255,0.02)",border:"1px solid var(--hairline)",borderRadius:10}}>
        <div>
          <div style={{fontSize:10,color:"var(--text-3)",letterSpacing:"0.06em"}}>선발 (어웨이)</div>
          <div style={{fontSize:13,fontWeight:600,marginTop:2}}>{m.away.sp}</div>
          <div className="num" style={{fontSize:10.5,color:"var(--text-3)",marginTop:1}}>{m.away.spLine}</div>
        </div>
        <div style={{textAlign:"right"}}>
          <div style={{fontSize:10,color:"var(--text-3)",letterSpacing:"0.06em"}}>선발 (홈)</div>
          <div style={{fontSize:13,fontWeight:600,marginTop:2}}>{m.home.sp}</div>
          <div className="num" style={{fontSize:10.5,color:"var(--text-3)",marginTop:1}}>{m.home.spLine}</div>
        </div>
      </div>

      {/* predicted win % bar — data analysis tone */}
      <div>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:6}}>
          <span style={{fontSize:11,color:"var(--text-3)",letterSpacing:"0.04em"}}>모델 예측 승률</span>
          <span className="num" style={{fontSize:10.5,color:"var(--text-3)"}}>데이터 분석 · {m.tag}</span>
        </div>
        <div style={{display:"flex",height:8,borderRadius:6,overflow:"hidden",background:"rgba(255,255,255,0.05)"}}>
          <div style={{width:`${aPct}%`,background:"var(--mlb)",opacity: favorAway?1:0.5,transition:"width .3s"}}/>
          <div style={{width:`${100-aPct}%`,background:"var(--kbo)",opacity: favorAway?0.5:1,transition:"width .3s"}}/>
        </div>
        <div style={{display:"flex",justifyContent:"space-between",marginTop:6}}>
          <span className="num" style={{fontSize:13,fontWeight:700,color:favorAway?"var(--mlb)":"var(--text-2)"}}>{m.away.win}<span style={{fontSize:10,color:"var(--text-3)",fontWeight:500,marginLeft:2}}>%</span></span>
          <span className="num" style={{fontSize:13,fontWeight:700,color:favorAway?"var(--text-2)":"var(--kbo)"}}>{m.home.win}<span style={{fontSize:10,color:"var(--text-3)",fontWeight:500,marginLeft:2}}>%</span></span>
        </div>
      </div>
    </article>
  );
}

function MatchupGrid() {
  return (
    <section className="section" id="matchup" style={{
      backgroundImage: `linear-gradient(rgba(11,14,20,0.78), rgba(11,14,20,0.92)), url('images/sections/matchup-stadium.png')`,
      backgroundSize: "cover",
      backgroundPosition: "center",
      backgroundAttachment: "fixed",
    }}>
      <div className="section-head">
        <div>
          <div className="eyebrow" style={{marginBottom:6}}>오늘의 매치업 분석</div>
          <h2>KBO 5경기 · 데이터 기반 예측</h2>
        </div>
        <a className="more" href="#">전체 일정 <I.arrow/></a>
      </div>
      <div className="grid-3" style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:18}}>
        {D.matchups.map((m,i)=> <MatchupCard key={i} m={m}/>)}
      </div>
      <div style={{marginTop:14,fontSize:11,color:"var(--text-3)",textAlign:"right"}}>
        ※ 예측 승률은 최근 10경기 성적·선발 매치업·구장 효과 기반의 통계 모델 결과입니다. 참고용 데이터 분석 자료입니다.
      </div>
    </section>
  );
}

/* ─── Analysis card ─────────────────────────────────────────────────── */
function AnalysisCard({ a }) {
  return (
    <article className="card" style={{display:"flex",flexDirection:"column",gap:12,cursor:"pointer",transition:"border-color .15s, transform .15s"}}
      onMouseEnter={(e)=>{e.currentTarget.style.borderColor="var(--hairline-strong)"; e.currentTarget.style.transform="translateY(-2px)";}}
      onMouseLeave={(e)=>{e.currentTarget.style.borderColor="var(--hairline)"; e.currentTarget.style.transform="";}}>
      {a.image && (
        <div style={{
          margin:"-22px -22px 4px",
          height:160,
          backgroundImage:`linear-gradient(180deg, rgba(11,14,20,0.10) 0%, rgba(11,14,20,0.55) 100%), url('${a.image}')`,
          backgroundSize:"cover",
          backgroundPosition:"center",
          borderRadius:"var(--r-xl) var(--r-xl) 0 0",
        }}/>
      )}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
        <span className="eyebrow" style={{color:a.color}}>{a.ribbon} · {a.tag}</span>
        <span className="num" style={{fontSize:11,color:"var(--text-3)"}}>{a.read}</span>
      </div>

      {/* visual — varies per kind */}
      <div style={{minHeight: a.kind === "zone" ? 0 : 44}}>
        {a.kind === "spark-up" && <Sparkline data={a.data} color={a.color}/>}
        {a.kind === "bars" && (
          <div className={`bars ${a.color === "var(--mlb)" ? "red" : ""}`}>
            {[0.55,0.72,0.41,0.86,0.62,0.93,0.48,0.78,0.34,0.66,0.55,0.81].map((h,i)=>(
              <i key={i} style={{height:`${h*100}%`}}/>
            ))}
          </div>
        )}
        {a.kind === "zone" && (
          <div style={{display:"flex",gap:14,alignItems:"center"}}>
            <ZoneHeat accent={a.color}/>
            <div style={{flex:1}}>
              <div className="num" style={{fontSize:32,fontWeight:800,letterSpacing:"-0.04em",lineHeight:1}}>102.1<span style={{fontSize:14,color:"var(--text-3)",fontWeight:500,marginLeft:4}}>mph</span></div>
              <div style={{fontSize:12,color:"var(--text-3)",marginTop:4}}>발사각 <span className="num" style={{color:"var(--text-2)"}}>26°</span> · 비거리 <span className="num" style={{color:"var(--text-2)"}}>134m</span></div>
            </div>
          </div>
        )}
        {a.kind === "compare" && (
          <div style={{display:"flex",gap:8,alignItems:"flex-end",height:44}}>
            {[
              {l:"2017 한화", c:"var(--text-3)", h:.62},
              {l:"2026 한화", c:a.color, h:.86},
            ].map((b,i)=>(
              <div key={i} style={{flex:1,textAlign:"center"}}>
                <div style={{height:b.h*44,background:b.c,opacity:0.85,borderRadius:"3px 3px 0 0",marginBottom:6}}/>
                <div style={{fontSize:10,color:"var(--text-3)"}}>{b.l}</div>
              </div>
            ))}
          </div>
        )}
      </div>

      <h3 style={{margin:0,fontSize:17,fontWeight:700,letterSpacing:"-0.02em",lineHeight:1.35,textWrap:"pretty"}}>{a.title}</h3>
      <p style={{margin:0,fontSize:13.5,color:"var(--text-2)",lineHeight:1.55,textWrap:"pretty"}}>{a.excerpt}</p>

      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:"auto",paddingTop:8,borderTop:"1px solid var(--hairline)"}}>
        <div style={{fontSize:12,color:"var(--text-3)"}}>{a.author} · {a.time}</div>
        <I.arrow style={{color:"var(--text-3)"}}/>
      </div>
    </article>
  );
}

function AnalysisGrid() {
  return (
    <section className="section" id="mlb">
      <div className="section-head">
        <div>
          <div className="eyebrow" style={{marginBottom:6}}>오늘의 분석</div>
          <h2>한국 야구를 보는 6가지 시선</h2>
        </div>
        <a className="more" href="#">전체 보기 <I.arrow/></a>
      </div>
      <div className="grid-3" style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:18}}>
        {D.analysis.map((a,i)=> <AnalysisCard key={i} a={a}/>)}
      </div>
    </section>
  );
}

/* ─── Player carousel ───────────────────────────────────────────────── */
function PlayerCarousel() {
  return (
    <section className="section-tight" id="players">
      <div className="section-head">
        <div>
          <div className="eyebrow" style={{marginBottom:6}}>인기 선수</div>
          <h2>지금 이 선수들</h2>
        </div>
        <a className="more" href="#">선수 전체 <I.arrow/></a>
      </div>
      <div className="carousel">
        {D.players.map((p,i)=>(
          <div key={i} className="player-chip">
            <div className="player-avatar" style={{background:p.color, fontSize: p.team.length >= 3 ? 14 : 18, overflow:"hidden"}}>
              {window.KB_TEAM_LOGOS[p.team] ? (
                <img src={window.KB_TEAM_LOGOS[p.team]} alt={p.team} style={{width:"70%",height:"70%",objectFit:"contain",filter:"drop-shadow(0 1px 2px rgba(0,0,0,0.4))"}}/>
              ) : p.team}
              {p.live && <span style={{position:"absolute",top:-2,right:-2,width:14,height:14,borderRadius:"50%",background:"var(--mlb)",border:"2px solid var(--bg)",zIndex:2}}/>}
            </div>
            <div className="name">{p.ko}</div>
            <div className="team-line num">{p.team} · {p.pos}</div>
            <div style={{marginTop:8}}>
              <span className={`tag ${p.league==="MLB"?"tag-mlb":"tag-kbo"}`} style={{fontSize:10,padding:"2px 7px"}}>{p.league}</span>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ─── Leaderboard ───────────────────────────────────────────────────── */
function Leaderboard() {
  const [tab, setTab] = useState("kbo");
  const lb = D.leaderboards[tab];
  const max = Math.max(...lb.rows.map(r=>r.ops));
  return (
    <section className="section" id="rank">
      <div className="section-head">
        <div>
          <div className="eyebrow" style={{marginBottom:6}}>2026 시즌 리더보드</div>
          <h2>OPS 기준 탑 플레이어</h2>
        </div>
        <div className="tabs">
          <button className={tab==="kbo"?"on":""} onClick={()=>setTab("kbo")}>
            <span className="league-dot" style={{background:"var(--kbo)"}}/>
            KBO TOP 10
          </button>
          <button className={tab==="mlb"?"on":""} onClick={()=>setTab("mlb")}>
            <span className="league-dot" style={{background:"var(--mlb)"}}/>
            한국인 MLB TOP 5
          </button>
        </div>
      </div>

      <div className="lb">
        <table>
          <thead>
            <tr>
              <th style={{width:48}}>#</th>
              <th>선수</th>
              <th style={{width:200}}>OPS</th>
              <th className="num" style={{width:80}}>HR</th>
              <th className="num" style={{width:80}}>AVG</th>
              <th className="num" style={{width:80}}>WAR</th>
            </tr>
          </thead>
          <tbody>
            {lb.rows.map((r,i)=>(
              <tr key={i}>
                <td><span className="rank">{i+1}</span></td>
                <td>
                  <div className="player-cell">
                    <div className="team-mark sm" style={{background:"#1F2630",fontSize:9,color:"var(--text-2)",overflow:"hidden",padding:window.KB_TEAM_LOGOS[r.team]?4:0}}>
                      {window.KB_TEAM_LOGOS[r.team] ? (
                        <img src={window.KB_TEAM_LOGOS[r.team]} alt={r.team} style={{width:"100%",height:"100%",objectFit:"contain"}}/>
                      ) : r.team}
                    </div>
                    <div>
                      <div className="name">{r.name}</div>
                      <div className="sub">{r.sub}</div>
                    </div>
                  </div>
                </td>
                <td>
                  <div className={`bar-cell ${tab==="mlb"?"red":""}`}>
                    <span className="num" style={{minWidth:48,fontWeight:600}}>{r.ops.toFixed(3).replace(/^0/,"")}</span>
                    <div className="track"><div className="fill" style={{width:`${(r.ops/max)*100}%`}}/></div>
                  </div>
                </td>
                <td className="num">{r.hr}</td>
                <td className="num">{r.avg.toFixed(3).replace(/^0/,"")}</td>
                <td className="num" style={{fontWeight:600}}>{r.war.toFixed(1)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}

/* ─── Guide boxes ───────────────────────────────────────────────────── */
function Guides() {
  return (
    <section className="section" id="guide">
      <div className="section-head">
        <div>
          <div className="eyebrow" style={{marginBottom:6}}>입문자 가이드</div>
          <h2>처음 보는 야구 데이터, 5분이면 이해</h2>
        </div>
        <a className="more" href="#">가이드 전체 <I.arrow/></a>
      </div>
      <div className="grid-3" style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:18}}>
        {D.guides.map((g,i)=>(
          <div key={i} className="guide-box">
            {g.image && (
              <div style={{
                margin:"-22px -22px 14px",
                height:120,
                backgroundImage:`linear-gradient(180deg, rgba(11,14,20,0.20) 0%, rgba(11,14,20,0.70) 100%), url('${g.image}')`,
                backgroundSize:"cover",
                backgroundPosition:"center",
                borderRadius:"var(--r-xl) var(--r-xl) 0 0",
              }}/>
            )}
            <div className="num-badge num" style={{zIndex:2}}>{g.n}</div>
            <div className="eyebrow" style={{color:i===0?"var(--mlb)":i===1?"var(--kbo)":"var(--warn)",marginBottom:10}}>{g.eyebrow}</div>
            <h3>{g.title}</h3>
            <p>{g.body}</p>
            <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:14}}>
              <span className="read">읽으러 가기 <I.arrow/></span>
              <span className="num" style={{fontSize:11,color:"var(--text-3)"}}>{g.time}</span>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ─── Notify CTA ────────────────────────────────────────────────────── */
function NotifyCTA() {
  const [val, setVal] = useState("");
  const [done, setDone] = useState(false);
  return (
    <section className="section">
      <div className="cta" style={{
        position:"relative",
        overflow:"hidden",
        backgroundImage:`linear-gradient(135deg, rgba(11,14,20,0.85) 0%, rgba(11,14,20,0.55) 50%, rgba(11,14,20,0.85) 100%), url('images/sections/cta-bell.png')`,
        backgroundSize:"cover",
        backgroundPosition:"center right",
      }}>
        <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:8}}>
          <I.bell style={{color:"var(--mlb)"}}/>
          <span className="eyebrow" style={{color:"var(--mlb)"}}>푸시 알림</span>
        </div>
        <h2>내 픽 선수가 홈런을 치면 즉시 알림</h2>
        <p>이정후·김혜성·김하성·류현진 — 한 번의 등록으로 4명 모두 추적합니다. 광고는 보내지 않습니다.</p>
        <form className="cta-form" onSubmit={(e)=>{e.preventDefault(); setDone(true);}}>
          <input value={val} onChange={(e)=>setVal(e.target.value)} placeholder="이메일 또는 휴대폰 번호" type="text"/>
          <button type="submit" className="btn btn-primary">{done?"등록 완료 ✓":"알림 받기"}</button>
        </form>
      </div>
    </section>
  );
}

/* ─── Footer ────────────────────────────────────────────────────────── */
function Footer() {
  return (
    <footer>
      <div className="wrap">
        <div className="grid">
          <div>
            <a className="logo" href="#" style={{marginBottom:14}}>
              <span className="logo-mark"/>
              <span>Dualbat</span>
            </a>
            <p style={{margin:"12px 0 0",maxWidth:360,lineHeight:1.6}}>
              한국 팬을 위한 MLB·KBO 동시 분석 사이트. 한국인 메이저리거의 매 타석을 한국어로 풀어냅니다.
            </p>
            <div className="sources">
              <span className="source-chip">MLB Stats API</span>
              <span className="source-chip">KBO 공식</span>
              <span className="source-chip">Lahman DB</span>
              <span className="source-chip">Retrosheet</span>
              <span className="source-chip">Statcast</span>
            </div>
          </div>
          <div>
            <h4>리그</h4>
            <ul><li><a href="#">MLB 분석</a></li><li><a href="#">KBO 분석</a></li><li><a href="#">한국인 MLB</a></li><li><a href="#">마이너 리그</a></li></ul>
          </div>
          <div>
            <h4>도구</h4>
            <ul><li><a href="#">선수 비교</a></li><li><a href="#">시즌 리더보드</a></li><li><a href="#">예측 모델</a></li><li><a href="#">내 픽 관리</a></li></ul>
          </div>
          <div>
            <h4>회사</h4>
            <ul><li><a href="#">소개</a></li><li><a href="#">데이터 출처</a></li><li><a href="#">이용 약관</a></li><li><a href="#">문의</a></li></ul>
          </div>
        </div>
        <div style={{display:"flex",justifyContent:"space-between",marginTop:32,paddingTop:20,borderTop:"1px solid var(--hairline)",fontSize:12,color:"var(--text-3)",flexWrap:"wrap",gap:12}}>
          <span className="num">© 2026 KOREA BASEBALL HUB · 비공식 분석 사이트</span>
          <span>이 사이트는 MLB / KBO와 직접 연관되어 있지 않습니다.</span>
        </div>
      </div>
    </footer>
  );
}

/* ─── Mobile bottom tab bar ─────────────────────────────────────────── */
function MobileTabBar() {
  const [act, setAct] = useState("home");
  const tabs = [
    { id:"home",   label:"홈",    icon: I.home },
    { id:"matchup",label:"매치업", icon: I.vs },
    { id:"player", label:"선수",  icon: I.user },
    { id:"pin",    label:"내 픽",  icon: I.pin },
    { id:"menu",   label:"메뉴",  icon: I.menu },
  ];
  return (
    <nav className="tabbar">
      <div className="tabbar-inner">
        {tabs.map(t=>{
          const Icon = t.icon;
          return (
            <a key={t.id} href="#" className={act===t.id?"on":""} onClick={(e)=>{e.preventDefault();setAct(t.id);}}>
              <Icon className="tab-icon"/>
              <span>{t.label}</span>
            </a>
          );
        })}
      </div>
    </nav>
  );
}

/* expose to window */
Object.assign(window, { Header, Hero, MatchupGrid, AnalysisGrid, PlayerCarousel, Leaderboard, Guides, NotifyCTA, Footer, MobileTabBar, KBIcons: I });
