// Pro Físico: Physical measurements screen
function ProFisico({ onPlayerSelect }) {
  const { players } = window.TData;
  const { physicalData, evalDates } = window.TDataExt;
  const [selected, setSelected] = React.useState(null);
  const [metric, setMetric] = React.useState("sprint");

  if (selected) return <ProFisicoDetail player={selected} physData={physicalData[selected.id]} evalDates={evalDates} onBack={()=>setSelected(null)} />;

  const metrics = [
    {key:"sprint",  label:"Velocidad 20m", unit:"seg", lower:true},
    {key:"salto",   label:"Salto vertical",unit:"cm",  lower:false},
    {key:"agilidad",label:"Agilidad",      unit:"seg", lower:true},
    {key:"musculo", label:"Masa muscular", unit:"%",   lower:false},
    {key:"vo2",     label:"VO₂ est.",      unit:"",    lower:false},
  ];
  const cur = metrics.find(m=>m.key===metric);

  const sorted = [...players].sort((a,b)=>{
    const va = physicalData[a.id]?.latest?.[metric]||0;
    const vb = physicalData[b.id]?.latest?.[metric]||0;
    return cur.lower ? va-vb : vb-va;
  });

  const cols = [
    {key:"rank",    label:"#",           color:T.muted},
    {key:"player",  label:"Jugadora"},
    {key:"pos",     label:"Posición"},
    {key:"altura",  label:"Altura",      right:true},
    {key:"peso",    label:"Peso",        right:true},
    {key:"grasa",   label:"Grasa %",     right:true, color:T.muted},
    {key:"musculo", label:"Músculo %",   right:true, bold:true, color:T.accent},
    {key:"sprint",  label:"Sprint 20m",  right:true},
    {key:"salto",   label:"Salto V.",    right:true},
    {key:"agilidad",label:"Agilidad",    right:true},
    {key:"vo2",     label:"VO₂ est.",    right:true},
    {key:"trend",   label:"Tendencia",   right:true},
  ];

  const rows = sorted.map((p,i)=>{
    const d = physicalData[p.id];
    if (!d) return null;
    const lat = d.latest;
    const delta = d.delta;
    const sprintImproved = delta.sprint < 0;
    const musImproved = delta.musculo > 0;
    return {
      _player: p,
      rank: <span style={{color:T.subtle,fontSize:12,fontWeight:600}}>{i+1}</span>,
      player: (
        <div style={{display:"flex",alignItems:"center",gap:10}}>
          <PAvatar initials={p.initials} color={posColorsP[p.pos]||T.accent} size={28} />
          <span style={{fontWeight:500,color:T.text}}>#{p.num} {p.name}</span>
        </div>
      ),
      pos:     <PBadge text={p.pos} color={posColorsP[p.pos]} variant="pill" />,
      altura:  `${lat.altura} cm`,
      peso:    `${lat.peso} kg`,
      grasa:   `${lat.grasa}%`,
      musculo: `${lat.musculo}%`,
      sprint:  `${lat.sprint}"`,
      salto:   `${lat.salto} cm`,
      agilidad:`${lat.agilidad}"`,
      vo2:     lat.vo2,
      trend: (
        <span style={{
          fontSize:11,fontWeight:600,
          color:sprintImproved&&musImproved?T.green:delta.sprint<0||delta.musculo>0?T.yellow:T.muted
        }}>
          {sprintImproved&&musImproved?"↑ Mejorando":delta.sprint<0||delta.musculo>0?"~ Progresando":"→ Estable"}
        </span>
      ),
    };
  }).filter(Boolean);

  // Team averages (latest eval)
  const avg = key => (players.reduce((s,p)=>s+(physicalData[p.id]?.latest?.[key]||0),0)/players.length).toFixed(1);

  return (
    <div>
      <div style={{marginBottom:24}}>
        <h2 style={{margin:0,fontSize:20,fontWeight:700,color:T.text,letterSpacing:"-0.02em"}}>Condición Física</h2>
        <p style={{margin:"4px 0 0",fontSize:13,color:T.muted}}>Mediciones del equipo · {evalDates[evalDates.length-1]} (última evaluación)</p>
      </div>

      {/* Team KPIs */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(5,1fr)",gap:12,marginBottom:20}}>
        <PKPICard label="Sprint 20m prom." value={`${avg("sprint")}"`} color={T.text} sub="↓ mejor" />
        <PKPICard label="Salto vertical" value={`${avg("salto")} cm`} color={T.accent} sub="↑ mejor" />
        <PKPICard label="Agilidad" value={`${avg("agilidad")}"`} color={T.text} sub="↓ mejor" />
        <PKPICard label="Masa muscular" value={`${avg("musculo")}%`} color={T.green} sub="promedio equipo" />
        <PKPICard label="VO₂ estimado" value={avg("vo2")} color={T.text} sub="ml/kg/min est." />
      </div>

      {/* Metric selector */}
      <div style={{display:"flex",gap:6,marginBottom:16,alignItems:"center"}}>
        <span style={{fontSize:11,fontWeight:600,color:T.muted,textTransform:"uppercase",letterSpacing:"0.06em",marginRight:4}}>Ordenar por:</span>
        {metrics.map(m=>(
          <button key={m.key} onClick={()=>setMetric(m.key)} style={{
            padding:"5px 14px",borderRadius:4,border:`1px solid ${metric===m.key?T.accent:T.border}`,
            background:metric===m.key?T.accentLt:"#fff",
            color:metric===m.key?T.accent:T.muted,
            fontWeight:metric===m.key?600:400,fontSize:12,
            cursor:"pointer",fontFamily:"inherit",transition:"all 0.12s"
          }}>{m.label}</button>
        ))}
      </div>

      <PCard padding="0">
        <div style={{padding:"16px 24px 0"}}>
          <PLabel>Comparativa por jugadora · haz clic para ver detalle</PLabel>
        </div>
        <PTable columns={cols} rows={rows} onRowClick={row=>setSelected(row._player)} />
        <div style={{height:4}} />
      </PCard>

      {/* Eval dates */}
      <div style={{marginTop:14,display:"flex",gap:10,alignItems:"center"}}>
        <span style={{fontSize:11,color:T.muted,fontWeight:600}}>Evaluaciones realizadas:</span>
        {evalDates.map(d=>(
          <span key={d} style={{fontSize:11,color:T.text,border:`1px solid ${T.border}`,borderRadius:4,padding:"2px 10px"}}>{d}</span>
        ))}
      </div>
    </div>
  );
}

function ProFisicoDetail({ player:p, physData, evalDates, onBack }) {
  const [tab, setTab] = React.useState("resumen");
  if (!physData) return <div><PBackBtn onClick={onBack} label="Condición Física" />Sin datos</div>;
  const lat = physData.latest;
  const delta = physData.delta;
  const accentColor = posColorsP[p.pos]||T.accent;

  const deltaColor = (val, lower=false) => {
    if (val === 0) return T.muted;
    const improved = lower ? val < 0 : val > 0;
    return improved ? T.green : T.red;
  };
  const deltaStr = (val, unit="") => `${val>0?"+":""}${val}${unit}`;

  return (
    <div>
      <PBackBtn onClick={onBack} label="Condición Física" />
      <div style={{display:"grid",gridTemplateColumns:"240px 1fr",gap:20,alignItems:"start"}}>

        {/* Left */}
        <div style={{display:"flex",flexDirection:"column",gap:12}}>
          <PCard>
            <div style={{textAlign:"center",marginBottom:16}}>
              <PAvatar initials={p.initials} color={accentColor} size={56} style={{margin:"0 auto 12px"}} />
              <div style={{fontWeight:700,fontSize:16,color:T.text}}>{p.name}</div>
              <div style={{fontSize:12,color:T.muted,marginTop:3}}>#{p.num} · <PBadge text={p.pos} color={accentColor} variant="pill" /></div>
            </div>
            <PDivider />
            <PLabel>Última medición · {lat.date}</PLabel>
            {[
              {l:"Altura",          v:`${lat.altura} cm`,  d:null},
              {l:"Peso",            v:`${lat.peso} kg`,    d:delta.peso,    lower:true,  unit:" kg"},
              {l:"Grasa corporal",  v:`${lat.grasa}%`,     d:delta.grasa,   lower:true,  unit:"%"},
              {l:"Masa muscular",   v:`${lat.musculo}%`,   d:delta.musculo, lower:false, unit:"%"},
              {l:"Sprint 20m",      v:`${lat.sprint}"`,    d:delta.sprint,  lower:true,  unit:'"'},
              {l:"Salto vertical",  v:`${lat.salto} cm`,   d:delta.salto,   lower:false, unit:" cm"},
              {l:"Agilidad",        v:`${lat.agilidad}"`,  d:delta.agilidad,lower:true,  unit:'"'},
              {l:"VO₂ est.",        v:lat.vo2,             d:delta.vo2,     lower:false, unit:""},
              {l:"Fuerza agarre",   v:`${lat.fuerza} kg`,  d:null},
            ].map(s=>(
              <div key={s.l} style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8}}>
                <span style={{fontSize:12,color:T.muted}}>{s.l}</span>
                <div style={{display:"flex",alignItems:"center",gap:8}}>
                  {s.d !== null && s.d !== undefined && (
                    <span style={{fontSize:10,fontWeight:600,color:deltaColor(s.d,s.lower)}}>
                      {deltaStr(s.d,s.unit)}
                    </span>
                  )}
                  <span style={{fontSize:13,fontWeight:600,color:T.text}}>{s.v}</span>
                </div>
              </div>
            ))}
          </PCard>
        </div>

        {/* Right */}
        <div>
          <PTabBar tabs={[["resumen","Resumen"],["progreso","Progreso por medición"]]} active={tab} onChange={setTab} />

          {tab==="resumen" && (
            <div style={{display:"flex",flexDirection:"column",gap:16}}>
              <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:12}}>
                <PKPICard label="Sprint 20m" value={`${lat.sprint}"`} color={delta.sprint<0?T.green:T.text} sub={delta.sprint<0?`Mejoró ${Math.abs(delta.sprint)}" desde inicio`:"Sin mejora aún"} />
                <PKPICard label="Salto vertical" value={`${lat.salto} cm`} color={delta.salto>0?T.green:T.text} sub={delta.salto>0?`+${delta.salto} cm desde inicio`:"Sin mejora aún"} />
                <PKPICard label="Masa muscular" value={`${lat.musculo}%`} color={delta.musculo>0?T.green:T.text} sub={delta.musculo>0?`+${delta.musculo}% desde inicio`:"Sin cambio"} />
              </div>
              <PCard>
                <PSectionHeader title="Progreso de velocidad (sprint 20m)" />
                <PLineChart
                  data={physData.slice(0,3).map(e=>e.sprint)}
                  labels={evalDates.map(d=>d.slice(5))}
                  color={accentColor} height={130}
                />
                <p style={{fontSize:11,color:T.muted,margin:"8px 0 0"}}>Menor es mejor — mejora visible entre evaluaciones</p>
              </PCard>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12}}>
                <PCard>
                  <PSectionHeader title="Salto vertical (cm)" />
                  <PBarChart data={physData.slice(0,3).map(e=>e.salto)} labels={evalDates.map(d=>d.slice(5))} color={accentColor} height={110} />
                </PCard>
                <PCard>
                  <PSectionHeader title="Composición corporal" />
                  {[
                    {l:"Masa muscular",  v:lat.musculo, max:60, color:T.accent},
                    {l:"Grasa corporal", v:lat.grasa,   max:35, color:T.muted},
                  ].map(s=>(
                    <div key={s.l} style={{marginBottom:14}}>
                      <div style={{display:"flex",justifyContent:"space-between",marginBottom:5}}>
                        <span style={{fontSize:12,color:T.muted}}>{s.l}</span>
                        <span style={{fontSize:12,fontWeight:700,color:s.color}}>{s.v}%</span>
                      </div>
                      <PProgress value={s.v} max={s.max} color={s.color} height={5} />
                    </div>
                  ))}
                </PCard>
              </div>
            </div>
          )}

          {tab==="progreso" && (
            <PCard padding="0">
              <div style={{padding:"16px 24px 0"}}><PLabel>Historial de evaluaciones</PLabel></div>
              <PTable
                columns={[
                  {key:"date",    label:"Fecha"},
                  {key:"peso",    label:"Peso (kg)",       right:true},
                  {key:"grasa",   label:"Grasa %",         right:true},
                  {key:"musculo", label:"Músculo %",       right:true, bold:true, color:T.accent},
                  {key:"sprint",  label:'Sprint 20m"',     right:true},
                  {key:"salto",   label:"Salto (cm)",      right:true},
                  {key:"agilidad",label:'Agilidad"',       right:true},
                  {key:"vo2",     label:"VO₂",             right:true},
                  {key:"fuerza",  label:"Fuerza (kg)",     right:true},
                ]}
                rows={physData.slice(0,3).map(e=>({
                  date:e.date, peso:e.peso, grasa:`${e.grasa}%`,
                  musculo:`${e.musculo}%`, sprint:`${e.sprint}"`,
                  salto:`${e.salto} cm`, agilidad:`${e.agilidad}"`,
                  vo2:e.vo2, fuerza:`${e.fuerza} kg`
                }))}
              />
              <div style={{height:4}} />
            </PCard>
          )}
        </div>
      </div>
    </div>
  );
}

window.ProFisico = ProFisico;
