// Pro Screens: Partidos, Asistencia, Agenda, Mensajes

// ── PARTIDOS ─────────────────────────────────────────────
function ProPartidos({ onPlayerSelect }) {
  const { games, players, rawStats } = window.TData;
  const [selected, setSelected] = React.useState(null);

  if (selected) return <ProGameDetail game={selected} players={players} rawStats={rawStats} onBack={()=>setSelected(null)} onPlayerSelect={onPlayerSelect} />;

  const cols = [
    {key:"date",    label:"Fecha"},
    {key:"rival",   label:"Rival"},
    {key:"loc",     label:"Sede"},
    {key:"score",   label:"Marcador", bold:true},
    {key:"diff",    label:"Dif."},
    {key:"pts",     label:"Pts nuestros", right:true},
    {key:"con",     label:"Pts rival", right:true, color:T.muted},
  ];

  const rows = [...games].reverse().map(g=>{
    const win=g.result==="W", diff=g.scoreUs-g.scoreThem;
    return {
      _game:g,
      date: new Date(g.date).toLocaleDateString("es-MX",{day:"numeric",month:"short",year:"numeric"}),
      rival:<span style={{fontWeight:600,color:T.text}}>{g.rival}</span>,
      loc:  <PBadge text={g.location} />,
      score:<span style={{fontWeight:700,color:win?T.green:T.red}}>{g.scoreUs}–{g.scoreThem}</span>,
      diff: <span style={{fontWeight:600,color:win?T.green:T.red}}>{win?"+":""}{diff}</span>,
      pts:  g.scoreUs,
      con:  g.scoreThem,
    };
  });

  const wins=games.filter(g=>g.result==="W").length;
  const avgPts=(games.reduce((s,g)=>s+g.scoreUs,0)/games.length).toFixed(1);
  const avgCon=(games.reduce((s,g)=>s+g.scoreThem,0)/games.length).toFixed(1);
  const avgDiff=((games.reduce((s,g)=>s+g.scoreUs,0)-games.reduce((s,g)=>s+g.scoreThem,0))/games.length).toFixed(1);

  return (
    <div>
      <div style={{marginBottom:24}}>
        <h2 style={{margin:0,fontSize:20,fontWeight:700,color:T.text,letterSpacing:"-0.02em"}}>Partidos</h2>
        <p style={{margin:"4px 0 0",fontSize:13,color:T.muted}}>Temporada 2025–26 · {games.length} partidos</p>
      </div>

      <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:12,marginBottom:20}}>
        <PKPICard label="Victorias" value={`${wins}/${games.length}`} color={T.green} sub="partidos ganados" />
        <PKPICard label="Pts promedio" value={avgPts} color={T.accent} sub="por partido" />
        <PKPICard label="Pts concedidos" value={avgCon} color={T.muted} sub="promedio rival" />
        <PKPICard label="Diferencial" value={`+${avgDiff}`} color={parseFloat(avgDiff)>0?T.green:T.red} sub="promedio" />
      </div>

      <div style={{display:"grid",gridTemplateColumns:"1fr 280px",gap:16,alignItems:"start"}}>
        <PCard padding="0">
          <div style={{padding:"20px 24px 0"}}>
            <PLabel>Historial de partidos — haz clic para ver estadísticas</PLabel>
          </div>
          <PTable columns={cols} rows={rows} onRowClick={row=>setSelected(row._game)} />
          <div style={{height:4}} />
        </PCard>
        <PCard>
          <PSectionHeader title="Tendencia de puntos" />
          <PLineChart data={games.map(g=>g.scoreUs)} labels={games.map(g=>g.rival.slice(0,4))} color={T.accent} height={160} />
        </PCard>
      </div>
    </div>
  );
}

function ProGameDetail({ game:g, players, rawStats, onBack, onPlayerSelect }) {
  const stats = rawStats[g.id]||{};
  const win = g.result==="W";
  const played = players.filter(p=>stats[p.id]&&stats[p.id][9]>0).sort((a,b)=>(stats[b.id][0]||0)-(stats[a.id][0]||0));

  const cols = [
    {key:"player",label:"Jugadora"},
    {key:"min",   label:"Min", right:true},
    {key:"pts",   label:"Pts", right:true, bold:true, color:T.accent},
    {key:"reb",   label:"Reb", right:true},
    {key:"ast",   label:"Ast", right:true},
    {key:"stl",   label:"Rob", right:true},
    {key:"fg",    label:"FG",  right:true},
    {key:"fgpct", label:"FG%", right:true},
    {key:"ft",    label:"TL",  right:true},
    {key:"fouls", label:"F",   right:true, color:T.muted},
    {key:"to",    label:"P",   right:true, color:T.muted},
  ];

  const rows = played.map(p=>{
    const s=stats[p.id]||[];
    return {
      _player:p,
      player:(
        <div style={{display:"flex",alignItems:"center",gap:10}}>
          <PAvatar initials={p.initials} color={posColorsP[p.pos]||T.accent} size={26} />
          <span style={{fontWeight:500,fontSize:13}}>#{p.num} {p.name}</span>
        </div>
      ),
      min:`${s[9]}'`,pts:s[0],reb:s[1],ast:s[2],stl:s[3],
      fg:`${s[6]}/${s[7]}`,
      fgpct:s[7]?`${Math.round(s[6]/s[7]*100)}%`:"—",
      ft:`${s[4]}/${s[5]}`,fouls:s[8],to:s[10]
    };
  });

  return (
    <div>
      <PBackBtn onClick={onBack} label="Partidos" />

      {/* Result header */}
      <div style={{
        display:"flex",alignItems:"center",justifyContent:"space-between",
        padding:"24px 28px",borderRadius:8,marginBottom:20,
        border:`1px solid ${win?T.green+"30":T.red+"30"}`,
        background:win?T.greenLt:T.redLt
      }}>
        <div>
          <div style={{fontSize:12,fontWeight:600,color:T.muted,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6}}>
            {new Date(g.date).toLocaleDateString("es-MX",{weekday:"long",day:"numeric",month:"long",year:"numeric"})} · {g.location}
          </div>
          <div style={{fontWeight:700,fontSize:20,color:T.text}}>Tormentas vs {g.rival}</div>
        </div>
        <div style={{display:"flex",alignItems:"center",gap:24}}>
          <div style={{textAlign:"center"}}>
            <div style={{fontSize:44,fontWeight:800,color:T.text,lineHeight:1}}>{g.scoreUs}</div>
            <div style={{fontSize:11,color:T.muted,marginTop:4,fontWeight:600}}>TORMENTAS</div>
          </div>
          <div style={{color:T.subtle,fontSize:24,fontWeight:300}}>–</div>
          <div style={{textAlign:"center"}}>
            <div style={{fontSize:44,fontWeight:800,color:win?T.muted:T.text,lineHeight:1}}>{g.scoreThem}</div>
            <div style={{fontSize:11,color:T.muted,marginTop:4,fontWeight:600}}>{g.rival.toUpperCase()}</div>
          </div>
          <div style={{
            padding:"6px 16px",borderRadius:6,
            border:`1px solid ${win?T.green+"40":T.red+"40"}`,
            fontWeight:700,fontSize:14,color:win?T.green:T.red,
            background:"#fff"
          }}>{win?"Victoria":"Derrota"}</div>
        </div>
      </div>

      <PCard padding="0">
        <div style={{padding:"20px 24px 0"}}>
          <PLabel>Estadísticas individuales · haz clic para ver perfil</PLabel>
        </div>
        <PTable columns={cols} rows={rows} onRowClick={row=>onPlayerSelect(row._player)} />
        <div style={{height:4}} />
      </PCard>
    </div>
  );
}

// ── ASISTENCIA ────────────────────────────────────────────
function ProAsistencia() {
  const { players, trainingDates, attendance } = window.TData;
  const [att, setAtt] = React.useState(()=>{
    const s={};
    players.forEach(p=>{ s[p.id]={}; trainingDates.forEach((d,i)=>{ s[p.id][d]=attendance[p.id][i].present; }); });
    return s;
  });

  const toggle=(pid,d)=>setAtt(p=>({...p,[pid]:{...p[pid],[d]:!p[pid][d]}}));
  const getPct=pid=>{ const v=Object.values(att[pid]); return Math.round(v.filter(Boolean).length/v.length*100); };
  const dLabel=d=>new Date(d+"T12:00:00").toLocaleDateString("es-MX",{day:"numeric",month:"short"}).replace(".","");
  const teamAvg=Math.round(players.reduce((s,p)=>s+getPct(p.id),0)/players.length);

  return (
    <div>
      <div style={{marginBottom:24}}>
        <h2 style={{margin:0,fontSize:20,fontWeight:700,color:T.text,letterSpacing:"-0.02em"}}>Asistencia</h2>
        <p style={{margin:"4px 0 0",fontSize:13,color:T.muted}}>Haz clic en una celda para marcar o desmarcar asistencia</p>
      </div>

      <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:12,marginBottom:20}}>
        <PKPICard label="Promedio equipo" value={`${teamAvg}%`} color={teamAvg>=80?T.green:T.yellow} />
        <PKPICard label="Entrenamientos" value={trainingDates.length} color={T.text} />
        <PKPICard label="Asistencia perfecta" value={players.filter(p=>getPct(p.id)===100).length} sub="jugadoras" color={T.green} />
        <PKPICard label="Requieren atención" value={players.filter(p=>getPct(p.id)<70).length} sub="menos de 70%" color={T.red} />
      </div>

      <PCard padding="0">
        <div style={{overflowX:"auto"}}>
          <table style={{borderCollapse:"collapse",width:"100%",minWidth:1000}}>
            <thead>
              <tr style={{background:T.stripe}}>
                <th style={{
                  padding:"10px 20px",textAlign:"left",fontSize:11,fontWeight:700,
                  color:T.muted,textTransform:"uppercase",letterSpacing:"0.06em",
                  borderBottom:`2px solid ${T.border}`,position:"sticky",left:0,background:T.stripe,
                  zIndex:2,minWidth:200,whiteSpace:"nowrap"
                }}>Jugadora</th>
                {trainingDates.map(d=>(
                  <th key={d} style={{
                    padding:"10px 8px",textAlign:"center",fontSize:10,fontWeight:600,
                    color:T.muted,borderBottom:`2px solid ${T.border}`,minWidth:50,whiteSpace:"nowrap"
                  }}>{dLabel(d)}</th>
                ))}
                <th style={{
                  padding:"10px 14px",textAlign:"center",fontSize:11,fontWeight:700,
                  color:T.muted,textTransform:"uppercase",letterSpacing:"0.06em",
                  borderBottom:`2px solid ${T.border}`,minWidth:80,whiteSpace:"nowrap"
                }}>%</th>
              </tr>
            </thead>
            <tbody>
              {players.map((p,pi)=>{
                const pct=getPct(p.id);
                const attColor=pct>=85?T.green:pct>=70?T.yellow:T.red;
                return (
                  <tr key={p.id} style={{background:pi%2===1?T.stripe:"#fff"}}>
                    <td style={{
                      padding:"10px 20px",borderBottom:`1px solid ${T.border}`,
                      position:"sticky",left:0,background:pi%2===1?T.stripe:"#fff",zIndex:1
                    }}>
                      <div style={{display:"flex",alignItems:"center",gap:10}}>
                        <PAvatar initials={p.initials} color={posColorsP[p.pos]||T.accent} size={28} />
                        <div>
                          <div style={{fontWeight:500,fontSize:13,color:T.text}}>#{p.num} {p.name}</div>
                          <PBadge text={p.pos} color={posColorsP[p.pos]} variant="pill" />
                        </div>
                      </div>
                    </td>
                    {trainingDates.map(d=>(
                      <td key={d} style={{padding:"8px",textAlign:"center",borderBottom:`1px solid ${T.border}`}}>
                        <div onClick={()=>toggle(p.id,d)} style={{
                          width:30,height:30,borderRadius:5,cursor:"pointer",margin:"0 auto",
                          background:att[p.id][d]?T.accentLt:T.redLt,
                          border:`1px solid ${att[p.id][d]?T.accentMd:"#fecaca"}`,
                          display:"flex",alignItems:"center",justifyContent:"center",
                          fontSize:13,color:att[p.id][d]?T.accent:T.red,
                          fontWeight:700,transition:"all 0.12s",userSelect:"none"
                        }}>{att[p.id][d]?"✓":"–"}</div>
                      </td>
                    ))}
                    <td style={{padding:"8px 14px",textAlign:"center",borderBottom:`1px solid ${T.border}`}}>
                      <span style={{fontWeight:700,fontSize:13,color:attColor}}>{pct}%</span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <div style={{height:4}} />
      </PCard>
    </div>
  );
}

// ── AGENDA ────────────────────────────────────────────────
function ProAgenda() {
  const { upcomingEvents, trainingSessions, games } = window.TData;
  const [tab, setTab] = React.useState("proximos");

  return (
    <div>
      <div style={{marginBottom:24}}>
        <h2 style={{margin:0,fontSize:20,fontWeight:700,color:T.text,letterSpacing:"-0.02em"}}>Agenda</h2>
        <p style={{margin:"4px 0 0",fontSize:13,color:T.muted}}>Partidos y plan de entrenamiento</p>
      </div>

      <PTabBar tabs={[["proximos","Próximos eventos"],["entrenamientos","Plan de entrenamientos"],["historial","Historial"]]} active={tab} onChange={setTab} />

      {tab==="proximos" && (
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(280px,1fr))",gap:14}}>
          {upcomingEvents.map(ev=>(
            <PCard key={ev.id}>
              <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",marginBottom:12}}>
                <PBadge text={ev.type==="partido"?"Partido":"Entrenamiento"} color={ev.type==="partido"?T.accent:T.green} variant="pill" />
                <span style={{fontSize:11,color:T.muted}}>{ev.date}</span>
              </div>
              <div style={{fontWeight:600,fontSize:15,color:T.text,marginBottom:6}}>
                {ev.type==="partido"?`vs ${ev.rival}`:ev.title}
              </div>
              <div style={{fontSize:12,color:T.muted}}>{ev.location}</div>
              <div style={{fontSize:12,color:T.muted,marginTop:2}}>{ev.time} hrs</div>
            </PCard>
          ))}
        </div>
      )}

      {tab==="entrenamientos" && (
        <div style={{display:"flex",flexDirection:"column",gap:12}}>
          {trainingSessions.map(s=>(
            <PCard key={s.id}>
              <div style={{display:"flex",gap:20,alignItems:"flex-start"}}>
                <div style={{minWidth:100,flexShrink:0}}>
                  <div style={{fontSize:12,fontWeight:600,color:T.muted,marginBottom:2}}>
                    {new Date(s.date).toLocaleDateString("es-MX",{day:"numeric",month:"short"})}
                  </div>
                  <div style={{fontSize:11,color:T.subtle}}>{s.duration} min</div>
                  <PBadge text={s.type} color={s.type==="Táctica"?T.accent:s.type==="Físico"?T.red:T.green} variant="pill" />
                </div>
                <div style={{flex:1,borderLeft:`2px solid ${T.border}`,paddingLeft:20}}>
                  <div style={{fontWeight:600,fontSize:15,color:T.text,marginBottom:4}}>{s.title}</div>
                  <div style={{fontSize:13,color:T.muted,fontStyle:"italic",marginBottom:10}}>{s.focus}</div>
                  <div style={{display:"flex",flexWrap:"wrap",gap:6}}>
                    {s.drills.map(d=>(
                      <span key={d} style={{
                        fontSize:12,color:T.text,background:T.stripe,
                        border:`1px solid ${T.border}`,borderRadius:4,padding:"3px 10px"
                      }}>{d}</span>
                    ))}
                  </div>
                </div>
              </div>
            </PCard>
          ))}
        </div>
      )}

      {tab==="historial" && (
        <PCard padding="0">
          <PTable
            columns={[
              {key:"date",label:"Fecha"},
              {key:"rival",label:"Rival"},
              {key:"loc",label:"Sede"},
              {key:"score",label:"Marcador",bold:true},
              {key:"diff",label:"Dif."},
            ]}
            rows={[...games].reverse().map(g=>{
              const win=g.result==="W";
              return {
                date:new Date(g.date).toLocaleDateString("es-MX",{day:"numeric",month:"long",year:"numeric"}),
                rival:g.rival,
                loc:<PBadge text={g.location} />,
                score:<span style={{fontWeight:700,color:win?T.green:T.red}}>{g.scoreUs}–{g.scoreThem}</span>,
                diff:<span style={{fontWeight:600,color:win?T.green:T.red}}>{win?"+":" "}{g.scoreUs-g.scoreThem}</span>
              };
            })}
          />
          <div style={{height:4}} />
        </PCard>
      )}
    </div>
  );
}

// ── MENSAJES ──────────────────────────────────────────────
function ProMensajes() {
  const { messages, players } = window.TData;
  const [selected, setSelected] = React.useState(null);
  const [compose, setCompose] = React.useState(false);
  const [newMsg, setNewMsg] = React.useState({subject:"",body:""});
  const [localMsgs, setLocalMsgs] = React.useState(messages);

  const send=()=>{
    if(!newMsg.subject.trim()) return;
    setLocalMsgs(p=>[{id:Date.now(),date:new Date().toISOString().split("T")[0],from:"Entrenadora García",to:"Todos",subject:newMsg.subject,body:newMsg.body,avatar:"EG"},...p]);
    setNewMsg({subject:"",body:""}); setCompose(false);
  };

  return (
    <div>
      <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",marginBottom:24}}>
        <div>
          <h2 style={{margin:0,fontSize:20,fontWeight:700,color:T.text,letterSpacing:"-0.02em"}}>Comunicación</h2>
          <p style={{margin:"4px 0 0",fontSize:13,color:T.muted}}>Avisos y mensajes para padres de familia</p>
        </div>
        <button onClick={()=>setCompose(true)} style={{
          padding:"9px 18px",background:T.accent,color:"#fff",
          border:"none",borderRadius:6,fontWeight:600,fontSize:13,
          cursor:"pointer",fontFamily:"inherit",transition:"opacity 0.15s"
        }} onMouseEnter={e=>e.currentTarget.style.opacity="0.88"} onMouseLeave={e=>e.currentTarget.style.opacity="1"}>
          Nuevo aviso
        </button>
      </div>

      <div style={{display:"grid",gridTemplateColumns:"1fr 300px",gap:20,alignItems:"start"}}>
        <div>
          {compose && (
            <PCard style={{marginBottom:16}}>
              <PLabel>Nuevo aviso para padres</PLabel>
              <div style={{marginBottom:10}}>
                <label style={{fontSize:11,fontWeight:600,color:T.muted,display:"block",marginBottom:5,textTransform:"uppercase",letterSpacing:"0.06em"}}>Asunto</label>
                <input value={newMsg.subject} onChange={e=>setNewMsg(p=>({...p,subject:e.target.value}))}
                  placeholder="Asunto del mensaje..."
                  style={{width:"100%",padding:"9px 12px",border:`1px solid ${T.border}`,borderRadius:6,
                    fontSize:13,color:T.text,outline:"none",fontFamily:"inherit",boxSizing:"border-box"}} />
              </div>
              <div style={{marginBottom:14}}>
                <label style={{fontSize:11,fontWeight:600,color:T.muted,display:"block",marginBottom:5,textTransform:"uppercase",letterSpacing:"0.06em"}}>Mensaje</label>
                <textarea value={newMsg.body} onChange={e=>setNewMsg(p=>({...p,body:e.target.value}))} rows={5}
                  placeholder="Escribe el aviso para los padres..."
                  style={{width:"100%",padding:"9px 12px",border:`1px solid ${T.border}`,borderRadius:6,
                    fontSize:13,color:T.text,outline:"none",fontFamily:"inherit",resize:"vertical",boxSizing:"border-box"}} />
              </div>
              <div style={{display:"flex",gap:8}}>
                <button onClick={send} style={{padding:"9px 20px",background:T.accent,color:"#fff",border:"none",
                  borderRadius:6,fontWeight:600,fontSize:13,cursor:"pointer",fontFamily:"inherit"}}>Enviar</button>
                <button onClick={()=>setCompose(false)} style={{padding:"9px 16px",background:"#fff",
                  border:`1px solid ${T.border}`,borderRadius:6,fontWeight:500,fontSize:13,
                  cursor:"pointer",color:T.muted,fontFamily:"inherit"}}>Cancelar</button>
              </div>
            </PCard>
          )}

          {selected ? (
            <PCard>
              <PBackBtn onClick={()=>setSelected(null)} label="Todos los avisos" />
              <div style={{borderBottom:`1px solid ${T.border}`,paddingBottom:16,marginBottom:16}}>
                <div style={{fontWeight:700,fontSize:18,color:T.text}}>{selected.subject}</div>
                <div style={{fontSize:12,color:T.muted,marginTop:4}}>{selected.from} · {selected.date} · Para: {selected.to}</div>
              </div>
              <p style={{fontSize:14,color:T.text,lineHeight:1.7,margin:0}}>{selected.body}</p>
            </PCard>
          ) : (
            <PCard padding="0">
              {localMsgs.map((m,i)=>(
                <div key={m.id} onClick={()=>setSelected(m)} style={{
                  display:"flex",gap:14,alignItems:"flex-start",
                  padding:"16px 24px",
                  borderBottom:i<localMsgs.length-1?`1px solid ${T.border}`:"none",
                  cursor:"pointer",transition:"background 0.1s"
                }}
                onMouseEnter={e=>e.currentTarget.style.background=T.stripe}
                onMouseLeave={e=>e.currentTarget.style.background=""}
                >
                  <div style={{
                    width:36,height:36,borderRadius:"50%",flexShrink:0,
                    background:T.accent,display:"flex",alignItems:"center",
                    justifyContent:"center",color:"#fff",fontWeight:700,fontSize:13
                  }}>{m.avatar}</div>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
                      <div style={{fontWeight:600,fontSize:13,color:T.text}}>{m.subject}</div>
                      <div style={{fontSize:11,color:T.muted,marginLeft:12,flexShrink:0}}>{m.date}</div>
                    </div>
                    <div style={{fontSize:12,color:T.muted,marginTop:3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{m.body}</div>
                    <div style={{fontSize:11,color:T.subtle,marginTop:3}}>Para: {m.to}</div>
                  </div>
                </div>
              ))}
            </PCard>
          )}
        </div>

        {/* Side panel */}
        <div style={{display:"flex",flexDirection:"column",gap:14}}>
          <PCard>
            <PLabel>Logros recientes</PLabel>
            <p style={{fontSize:12,color:T.muted,margin:"0 0 14px"}}>Comparte con los padres para mantenerlos comprometidos</p>
            {players.filter(p=>p.achievements.length>0).slice(0,6).map(p=>(
              <div key={p.id} style={{
                display:"flex",alignItems:"center",gap:10,
                padding:"9px 0",borderBottom:`1px solid ${T.border}`
              }}>
                <PAvatar initials={p.initials} color={posColorsP[p.pos]||T.accent} size={30} />
                <div style={{flex:1}}>
                  <div style={{fontWeight:500,fontSize:12,color:T.text}}>{p.name}</div>
                  <div style={{fontSize:11,color:T.muted,marginTop:1}}>{p.achievements[0]}</div>
                </div>
              </div>
            ))}
          </PCard>
          <PCard style={{background:T.accentLt,border:`1px solid ${T.accentMd}`}}>
            <PLabel>Dato de la semana</PLabel>
            <p style={{fontSize:13,color:T.accent,lineHeight:1.6,margin:0,fontWeight:500}}>
              Las jugadoras con más del 85% de asistencia promedian <strong>34% más puntos</strong> en partidos que sus compañeras con menor asistencia.
            </p>
          </PCard>
        </div>
      </div>
    </div>
  );
}

window.ProPartidos   = ProPartidos;
window.ProAsistencia = ProAsistencia;
window.ProAgenda     = ProAgenda;
window.ProMensajes   = ProMensajes;
