// Pro Dashboard v2 — Team Development Focus
function ProDashboard({ onNavigate, onPlayerSelect }) {
  const { team, games, players, upcomingEvents } = window.TData;
  const { physicalData, tasks, completions, computeDevScore } = window.TDataExt;

  const lastGame = games[games.length-1];
  const avgPts = (games.reduce((s,g)=>s+g.scoreUs,0)/games.length).toFixed(1);
  const teamAtt = Math.round(players.reduce((s,p)=>s+p.attendancePct,0)/players.length);
  const teamTaskPct = Math.round(players.reduce((s,p)=>{
    const done = tasks.filter(t=>completions[p.id]?.[t.id]).length;
    return s + (tasks.length ? done/tasks.length*100 : 0);
  },0)/players.length);

  // Dev scores
  const devScores = players.map(p=>({...p, dev: computeDevScore(p.id)}));
  const topDev = [...devScores].sort((a,b)=>b.dev-a.dev).slice(0,5);
  const needsAtt = [...devScores].sort((a,b)=>a.dev-b.dev).filter(p=>p.dev<60).slice(0,4);
  const teamDevAvg = Math.round(devScores.reduce((s,p)=>s+p.dev,0)/players.length);

  // Physical team trend (sprint avg across evals)
  const evalDates = window.TDataExt.evalDates;
  const sprintByEval = evalDates.map((_,ei)=>
    +(players.reduce((s,p)=>{
      const d = physicalData[p.id];
      return s + (d&&d[ei] ? d[ei].sprint : 3.35);
    },0)/players.length).toFixed(2)
  );
  const saltoByEval = evalDates.map((_,ei)=>
    +(players.reduce((s,p)=>{
      const d = physicalData[p.id];
      return s + (d&&d[ei] ? d[ei].salto : 38);
    },0)/players.length).toFixed(1)
  );

  // Game score trend
  const scoreTrend = games.map(g=>g.scoreUs);
  const gameLabels = games.map(g=>g.rival.slice(0,4));

  // Most improved (sprint delta)
  const mostImproved = [...players].map(p=>{
    const d = physicalData[p.id];
    const sprintDelta = d ? +(d[0].sprint - d[d.length-1].sprint).toFixed(2) : 0;
    return {...p, sprintDelta};
  }).sort((a,b)=>b.sprintDelta-a.sprintDelta).slice(0,3);

  const devColor = v => v>=80?T.green:v>=60?T.yellow:T.red;

  return (
    <div style={{display:"flex",flexDirection:"column",gap:20}}>

      {/* Header */}
      <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between"}}>
        <div>
          <h2 style={{margin:0,fontSize:20,fontWeight:700,color:T.text,letterSpacing:"-0.02em"}}>Panel de Desarrollo</h2>
          <p style={{margin:"4px 0 0",fontSize:13,color:T.muted}}>Visión integral del equipo · Temporada 2025–26</p>
        </div>
        <div style={{
          padding:"10px 16px",background:T.stripe,borderRadius:6,
          border:`1px solid ${T.border}`,textAlign:"right"
        }}>
          <div style={{fontSize:11,color:T.muted,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em"}}>Récord</div>
          <div style={{fontSize:20,fontWeight:800,color:T.text,marginTop:2}}>{team.wins}–{team.losses}</div>
        </div>
      </div>

      {/* KPI row */}
      <div className="t-grid-6" style={{display:"grid",gridTemplateColumns:"repeat(6,1fr)",gap:10}}>
        {[
          {l:"Índice de Desarrollo",  v:`${teamDevAvg}`,        c:devColor(teamDevAvg),  sub:"/100 promedio"},
          {l:"Asistencia a Entrenos", v:`${teamAtt}%`,           c:teamAtt>=80?T.green:T.yellow, sub:"promedio equipo"},
          {l:"Tareas Completadas",    v:`${teamTaskPct}%`,       c:teamTaskPct>=70?T.green:T.yellow, sub:"cumplimiento"},
          {l:"Pts Promedio",          v:avgPts,                  c:T.accent, sub:"por partido"},
          {l:"Racha",                 v:team.streak,             c:T.green, sub:"victorias consecutivas"},
          {l:"Sprint Equipo",         v:`${sprintByEval[sprintByEval.length-1]}"`, c:T.text, sub:"↓ mejorando"},
        ].map(s=><PKPICard key={s.l} label={s.l} value={s.v} color={s.c} sub={s.sub} />)}
      </div>

      {/* Row 2: development chart + alerts */}
      <div className="t-grid-3" style={{display:"grid",gridTemplateColumns:"1fr 1fr 300px",gap:14}}>

        {/* Rendimiento en cancha */}
        <PCard>
          <PSectionHeader title="Puntos por partido" action="Ver partidos" onAction={()=>onNavigate("partidos")} />
          <PLineChart data={scoreTrend} labels={gameLabels} color={T.accent} height={130} />
        </PCard>

        {/* Físico: velocidad */}
        <PCard>
          <PSectionHeader title="Velocidad media equipo (sprint 20m)" action="Ver físico" onAction={()=>onNavigate("fisico")} />
          <PLineChart data={sprintByEval} labels={evalDates.map(d=>d.slice(5))} color={T.green} height={130} />
          <p style={{fontSize:11,color:T.muted,margin:"6px 0 0"}}>Segundos — menor es mejor</p>
        </PCard>

        {/* Alerts */}
        <PCard>
          <PSectionHeader title="Requieren atención" />
          {needsAtt.length === 0 ? (
            <div style={{textAlign:"center",padding:"20px 0",color:T.muted,fontSize:13}}>Todo el equipo bien</div>
          ) : needsAtt.map(p=>(
            <div key={p.id} style={{
              display:"flex",alignItems:"center",gap:10,padding:"8px 0",
              borderBottom:`1px solid ${T.border}`
            }}>
              <PAvatar initials={p.initials} color={posColorsP[p.pos]||T.accent} size={28} />
              <div style={{flex:1,minWidth:0}}>
                <div style={{fontSize:12,fontWeight:500,color:T.text,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{p.name}</div>
                <div style={{fontSize:11,color:T.muted}}>Asist. {p.attendancePct}% · Dev. {p.dev}/100</div>
              </div>
              <span style={{fontSize:11,fontWeight:700,color:T.red}}>{p.dev}</span>
            </div>
          ))}
        </PCard>
      </div>

      {/* Row 3: dev rankings + tasks + physical + upcoming */}
      <div className="t-grid-3" style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:14}}>

        {/* Top development */}
        <PCard>
          <PSectionHeader title="Top desarrollo" action="Ver jugadoras" onAction={()=>onNavigate("jugadoras")} />
          <div style={{display:"flex",flexDirection:"column",gap:8}}>
            {topDev.map((p,i)=>{
              const dc = devColor(p.dev);
              return (
                <div key={p.id} onClick={()=>onPlayerSelect(p)} style={{
                  display:"flex",alignItems:"center",gap:10,padding:"9px 10px",
                  borderRadius:6,cursor:"pointer",transition:"background 0.1s"
                }}
                onMouseEnter={e=>e.currentTarget.style.background=T.stripe}
                onMouseLeave={e=>e.currentTarget.style.background=""}
                >
                  <span style={{fontSize:11,fontWeight:700,color:T.subtle,width:16}}>{i+1}</span>
                  <PAvatar initials={p.initials} color={posColorsP[p.pos]||T.accent} size={28} />
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:12,fontWeight:500,color:T.text,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{p.name}</div>
                    <PProgress value={p.dev} max={100} color={dc} height={3} />
                  </div>
                  <span style={{fontSize:12,fontWeight:700,color:dc,minWidth:36,textAlign:"right"}}>{p.dev}/100</span>
                </div>
              );
            })}
          </div>
        </PCard>

        {/* Most improved physically */}
        <PCard>
          <PSectionHeader title="Mayor mejora física" action="Ver físico" onAction={()=>onNavigate("fisico")} />
          <div style={{display:"flex",flexDirection:"column",gap:10}}>
            {mostImproved.map((p,i)=>(
              <div key={p.id} onClick={()=>onPlayerSelect(p)} style={{
                display:"flex",alignItems:"center",gap:12,padding:"9px 10px",
                borderRadius:6,cursor:"pointer",transition:"background 0.1s"
              }}
              onMouseEnter={e=>e.currentTarget.style.background=T.stripe}
              onMouseLeave={e=>e.currentTarget.style.background=""}
              >
                <span style={{fontSize:11,fontWeight:700,color:T.subtle,width:16}}>{i+1}</span>
                <PAvatar initials={p.initials} color={posColorsP[p.pos]||T.accent} size={28} />
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:12,fontWeight:500,color:T.text}}>{p.name}</div>
                  <div style={{fontSize:11,color:T.muted}}>Sprint mejora</div>
                </div>
                <span style={{fontSize:12,fontWeight:700,color:T.green}}>−{p.sprintDelta}"</span>
              </div>
            ))}
          </div>

          <PDivider />
          <PLabel>Salto vertical equipo</PLabel>
          <PBarChart data={saltoByEval.map(Number)} labels={evalDates.map(d=>d.slice(5))} color={T.accent} height={80} />
        </PCard>

        {/* Tasks + next event */}
        <div style={{display:"flex",flexDirection:"column",gap:14}}>
          <PCard>
            <PSectionHeader title="Tareas en casa" action="Ver tareas" onAction={()=>onNavigate("tareas")} />
            {tasks.slice(0,3).map(t=>{
              const done = players.filter(p=>completions[p.id]?.[t.id]).length;
              const pct = Math.round(done/players.length*100);
              const catColor = {Técnica:T.accent,Físico:T.red,Táctica:"#7c3aed",Recuperación:T.green}[t.category]||T.accent;
              return (
                <div key={t.id} style={{marginBottom:12}}>
                  <div style={{display:"flex",justifyContent:"space-between",marginBottom:4}}>
                    <span style={{fontSize:12,fontWeight:500,color:T.text}}>{t.title}</span>
                    <span style={{fontSize:11,fontWeight:700,color:pct>=75?T.green:pct>=50?T.yellow:T.red}}>{pct}%</span>
                  </div>
                  <PProgress value={pct} max={100} color={pct>=75?T.green:pct>=50?T.yellow:T.red} height={4} />
                </div>
              );
            })}
          </PCard>

          <PCard>
            <PSectionHeader title="Próximos eventos" action="Ver agenda" onAction={()=>onNavigate("agenda")} />
            {upcomingEvents.slice(0,3).map(ev=>(
              <div key={ev.id} style={{
                display:"flex",gap:10,alignItems:"flex-start",
                padding:"8px 0",borderBottom:`1px solid ${T.border}`
              }}>
                <div style={{
                  width:6,height:6,borderRadius:"50%",flexShrink:0,marginTop:5,
                  background:ev.type==="partido"?T.accent:T.green
                }} />
                <div style={{flex:1}}>
                  <div style={{fontSize:12,fontWeight:500,color:T.text}}>
                    {ev.type==="partido"?`vs ${ev.rival}`:ev.title}
                  </div>
                  <div style={{fontSize:11,color:T.muted}}>{ev.date} · {ev.time}</div>
                </div>
              </div>
            ))}
          </PCard>
        </div>
      </div>

    </div>
  );
}
window.ProDashboard = ProDashboard;
