// =============================================================================
// HUB — DASHBOARD HOME
// =============================================================================
const { useState: hubUseState, useEffect: hubUseEffect } = React;
const useState = hubUseState, useEffect = hubUseEffect;
const { PROVIDERS:HP, RARITIES:HR, CARDS:HC, CHAMPIONS:HCH, COLLECTIONS:HCL } = window.GAME_DATA;

function Hub({ state, actions }) {
  const ownedSet = state.collection;
  const packsLeft = state.packsToday;
  const totalCards = HC.length;
  const ownedCount = Object.keys(ownedSet).filter(k => k.indexOf('myth-') !== 0 && HC.find(c=>c.id===k)).length;
  const mythicsOwned = Object.keys(ownedSet).filter(k => window.GAME_DATA.MYTHIC_CARDS[k]).length;

  const champsDefeated = state.defeatedChamps.length;

  // Collection completion %
  const collProgress = HCL.map(coll => {
    const total = coll.total;
    const have = HC.filter(c => c.provider === coll.provider && ownedSet[c.id]).length;
    return { ...coll, have, pct: total ? Math.round(100*have/total) : 0, complete: have === total };
  });

  return (
    <div className="page">
      {/* HERO ROW */}
      <div className="hub-grid">
        <div className="hero-panel">
          <PanelCorners color="var(--accent-cyan)" />
          <div className="hero-eyebrow">◈ SLOT LEGENDS / EDICIÓN ARQUETIPOS · v1.0</div>
          <div className="hero-title">
            COLECCIONA.<br/>
            <em>DESAFÍA.</em><br/>
            DOMINA.
          </div>
          <div className="hero-sub">
            50 cartas arquetípicas. 5 colecciones por estudio. 5 campeones.
            Abre sobres cada día, completa las series y derrota a los maestros
            para obtener cartas MÍTICAS que ningún sobre te dará.
          </div>
          <div style={{display:'flex', gap:'12px'}}>
            <button className="btn primary" disabled={packsLeft<=0} onClick={() => actions.go('packs')}>
              {packsLeft>0 ? `▸ ABRIR SOBRE (${packsLeft} disponibles)` : 'SIN SOBRES — VUELVE EN 24H'}
            </button>
            <button className="btn ghost" onClick={() => actions.go('champions')}>
              ◆ DESAFIAR CAMPEÓN
            </button>
          </div>
        </div>

        <div className="packs-panel">
          <PanelCorners color="var(--accent-lime)" />
          <div className="eyebrow-row">
            <span className="eyebrow">DAILY · <strong>SOBRES</strong></span>
          </div>
          <div style={{display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:'16px'}}>
            <div className="pack-counter">
              <div className="pack-counter-num">{packsLeft}</div>
              <div className="pack-counter-sub">de 2<br/>hoy</div>
            </div>
            <div className={`pack-stack ${packsLeft===0?'empty':''}`}>
              {[...Array(2)].map((_, i) => (
                <div key={i} style={{opacity: i < packsLeft ? 1 : 0.18}}>
                  <PackMini />
                </div>
              ))}
            </div>
          </div>
          <div style={{borderTop:'1px dashed var(--border-hairline)', paddingTop:'12px', display:'grid', gap:'8px'}}>
            <div className="eyebrow">PRÓX. RECARGA</div>
            <NextReset resetAt={state.nextReset} onReset={actions.resetDaily}/>
          </div>
        </div>
      </div>

      {/* KPI ROW */}
      <div className="kpi-grid">
        <div className="kpi accent-cyan">
          <div className="kpi-label">Cartas en colección</div>
          <div className="kpi-value">{ownedCount}<span className="small">/ {totalCards}</span></div>
          <div className="kpi-foot"><span className="dot"></span>{Math.round(100*ownedCount/totalCards)}% completada</div>
        </div>
        <div className="kpi accent-lime">
          <div className="kpi-label">Colecciones completas</div>
          <div className="kpi-value">{collProgress.filter(c=>c.complete).length}<span className="small">/ 5</span></div>
          <div className="kpi-foot"><span className="dot" style={{background:'var(--accent-lime)'}}></span>proveedores dominados</div>
        </div>
        <div className="kpi accent-orange">
          <div className="kpi-label">Campeones derrotados</div>
          <div className="kpi-value">{champsDefeated}<span className="small">/ 5</span></div>
          <div className="kpi-foot"><span className="dot" style={{background:'var(--accent-orange)'}}></span>desafíos completados</div>
        </div>
        <div className="kpi accent-violet">
          <div className="kpi-label">Cartas míticas</div>
          <div className="kpi-value">{mythicsOwned}<span className="small">/ 5</span></div>
          <div className="kpi-foot"><span className="dot" style={{background:'var(--accent-violet)'}}></span>solo vía desafío</div>
        </div>
      </div>

      {/* COLLECTIONS PREVIEW */}
      <div className="eyebrow-row">
        <span className="eyebrow">02 / <strong>COLECCIONES</strong></span>
      </div>
      <div className="section-title">Progreso por proveedor</div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(260px, 1fr))', gap:'16px', marginBottom:'48px'}}>
        {collProgress.map(coll => {
          const p = HP[coll.provider];
          return (
            <div key={coll.id} className="panel" style={{padding:'16px', cursor:'pointer'}}
                 onClick={() => actions.go('collection')}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:'12px'}}>
                <ProvChip providerId={p.id} />
                <span className="mono" style={{fontFamily:'var(--font-mono)', fontSize:'10px', color:'var(--fg-3)', textTransform:'uppercase', letterSpacing:'0.12em'}}>
                  {coll.complete ? '✓ COMPLETA' : `${coll.have}/${coll.total}`}
                </span>
              </div>
              <div style={{fontFamily:'var(--font-sans)', fontWeight:700, fontSize:'18px', color:'var(--fg-1)', textTransform:'uppercase', letterSpacing:'-0.01em', marginBottom:'4px'}}>
                {p.name}
              </div>
              <div style={{fontFamily:'var(--font-mono)', fontSize:'11px', color:'var(--fg-3)', textTransform:'uppercase', letterSpacing:'0.12em', marginBottom:'14px'}}>
                {p.tagline}
              </div>
              <div className="coll-bar" style={{width:'100%'}}>
                <div className={`coll-bar-fill ${coll.complete?'complete':''}`} style={{width: coll.pct + '%'}}></div>
              </div>
              <div style={{display:'flex', justifyContent:'space-between', marginTop:'8px', fontFamily:'var(--font-mono)', fontSize:'10px', color:'var(--fg-3)'}}>
                <span>{coll.pct}%</span>
                <span style={{color: coll.complete?'var(--accent-lime)':'var(--fg-3)'}}>
                  {coll.complete ? '◆ +1500 CRD reclamado' : `${coll.total - coll.have} restantes`}
                </span>
              </div>
            </div>
          );
        })}
      </div>

      {/* CHAMPIONS PREVIEW */}
      <div className="eyebrow-row">
        <span className="eyebrow">03 / <strong>CAMPEONES</strong></span>
      </div>
      <div className="section-title">Maestros · Duelo de cartas</div>
      <div className="champ-grid">
        {HCH.map((champ, i) => {
          const defeated = state.defeatedChamps.includes(champ.id);
          const required = i; // each requires previous
          const locked = i > 0 && !state.defeatedChamps.includes(HCH[i-1].id);
          return (
            <ChampionCard key={champ.id}
                          champion={champ}
                          defeated={defeated}
                          locked={locked}
                          onClick={() => !locked && !defeated && actions.battle(champ.id)} />
          );
        })}
      </div>
    </div>
  );
}

function ChampionCard({ champion, defeated, locked, onClick }) {
  const c = champion;
  return (
    <div className={`champ-card ${defeated?'defeated':''} ${locked?'locked':''}`} onClick={onClick}>
      <div className="champ-header">
        <span>BOSS · {String(c.difficulty).padStart(2,'0')}/05</span>
        <span style={{color: defeated ? 'var(--accent-lime)' : (locked ? 'var(--fg-4)' : 'var(--accent-orange)')}}>
          {defeated ? '✓ CLEAR' : locked ? '◇ LOCK' : '◆ OPEN'}
        </span>
      </div>
      <div className="champ-art">
        <span className="champ-sigil">[{c.sigil}]</span>
        <ChampionSigil champion={c} />
      </div>
      <div className="champ-info">
        <div className="champ-name">{c.name}</div>
        <div className="champ-title-sub">{c.title}</div>
        <div className="champ-quote">"{c.quote}"</div>
        <div className="champ-meta">
          <div className="diff-pips">
            {[...Array(5)].map((_, j) => (
              <span key={j} className={`diff-pip ${j < c.difficulty ? 'on' : ''}`}></span>
            ))}
          </div>
          <span>+{c.reward.credits.toLocaleString()} CRD · 1× MÍTICA</span>
        </div>
      </div>
    </div>
  );
}

function NextReset({ resetAt, onReset }) {
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  if (!resetAt) return <div className="mono">recarga al recargar</div>;
  const remain = Math.max(0, resetAt - now);
  if (remain === 0) {
    return <button className="btn lime" onClick={onReset}>◆ RECARGAR SOBRES</button>;
  }
  const h = Math.floor(remain / 3.6e6);
  const m = Math.floor((remain % 3.6e6) / 6e4);
  const s = Math.floor((remain % 6e4) / 1000);
  return (
    <div style={{display:'flex', alignItems:'center', gap:'8px'}}>
      <div style={{fontFamily:'var(--font-mono)', fontSize:'18px', fontWeight:700, color:'var(--accent-lime)', fontVariantNumeric:'tabular-nums'}}>
        {String(h).padStart(2,'0')}:{String(m).padStart(2,'0')}:{String(s).padStart(2,'0')}
      </div>
      <button className="btn ghost" onClick={onReset} style={{fontSize:'10px', padding:'6px 10px'}}>SKIP</button>
    </div>
  );
}

window.Hub = Hub;
