// Tormentas — Pantallas administrativas
const ADMIN_KEY = 'TormPortal2026';

// ── PAGOS ─────────────────────────────────────────────────
function AdminPagos() {
  const { players } = window.TData;
  const { payments: init, MONTHLY_FEE, paymentMonths, monthLabels, contacts } = window.TAdmin;

  const [selMonth, setSelMonth] = React.useState(paymentMonths[paymentMonths.length - 1]);
  const [payments, setPayments] = React.useState(init);
  const [methodPick, setMethodPick] = React.useState(null); // {pid, month}

  // Sync a single payment entry to the server
  const syncPayment = (pid, pay) => {
    fetch('/api/pagos.php?action=upsert', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        adminKey: ADMIN_KEY,
        playerId: parseInt(pid),
        mes:    monthLabels[pay.month] || pay.month,
        monto:  MONTHLY_FEE,
        status: pay.paid ? 'pagado' : 'pendiente',
        fecha:  pay.date || '',
        metodo: pay.method || '',
      })
    }).catch(() => {});
  };

  // On mount: load payments from server and ensure all players have entries
  React.useEffect(() => {
    const reverseLabels = Object.fromEntries(Object.entries(monthLabels).map(([k, v]) => [v, k]));
    const emptyMonths = () => paymentMonths.map(month => ({ month, amount: MONTHLY_FEE, paid: false, date: null, method: null }));
    fetch('/api/pagos.php')
      .then(r => r.json())
      .then(serverData => {
        const sd = (serverData && typeof serverData === 'object') ? serverData : {};
        setPayments(prev => {
          const next = { ...prev };
          // Init entries for players not in TAdmin defaults
          players.forEach(p => { if (!next[p.id]) next[p.id] = emptyMonths(); });
          // Override with server-stored payments
          Object.entries(sd).forEach(([pkey, entries]) => {
            const pid = parseInt(pkey.slice(1));
            if (!next[pid]) next[pid] = emptyMonths();
            entries.forEach(entry => {
              const month = reverseLabels[entry.mes] || entry.mes;
              const idx = next[pid].findIndex(p => p.month === month);
              if (idx >= 0) {
                next[pid] = next[pid].map((p, i) => i !== idx ? p : {
                  ...p, paid: entry.status === 'pagado', date: entry.fecha || null,
                });
              }
            });
          });
          return next;
        });
      })
      .catch(() => {
        // Even if server fails, ensure all players have entries
        setPayments(prev => {
          const next = { ...prev };
          players.forEach(p => { if (!next[p.id]) next[p.id] = emptyMonths(); });
          return next;
        });
      });
  }, []);

  const confirmPay = (pid, month, method) => {
    const playerPays = payments[pid] || [];
    const existing   = playerPays.find(p => p.month === month);
    if (!existing) return;
    const fecha  = new Date().toISOString().split('T')[0];
    const newPay = { ...existing, paid: true, date: fecha, method };
    const next   = { ...payments, [pid]: playerPays.map(p => p.month === month ? newPay : p) };
    setPayments(next);
    setMethodPick(null);
    syncPayment(pid, newPay);
    // Send payment confirmation email to parents
    const player  = players.find(p => p.id === pid);
    if (player) {
      const staticParents = (contacts && contacts[pid] && Array.isArray(contacts[pid].parents))
        ? contacts[pid].parents : [];
      // Always call API; if no static parents, server will look up from registration
      fetch('/api/send-mail.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          adminKey:   ADMIN_KEY,
          playerId:   pid,
          playerName: player.name,
          mes:        monthLabels[month] || month,
          monto:      MONTHLY_FEE,
          metodo:     method,
          fecha,
          parents:    staticParents,
        }),
      }).catch(() => {});
    }
  };

  const unpay = (pid, month) => {
    const playerPays = payments[pid] || [];
    const existing   = playerPays.find(p => p.month === month);
    if (!existing) return;
    const newPay = { ...existing, paid: false, date: null, method: null };
    const next   = { ...payments, [pid]: playerPays.map(p => p.month === month ? newPay : p) };
    setPayments(next);
    syncPayment(pid, newPay);
  };

  const curIdx    = paymentMonths.indexOf(selMonth);
  const lastIdx   = paymentMonths.length - 1;
  const rows      = players.map(p => ({ player:p, pay: payments[p.id]?.find(x => x.month === selMonth) }));
  const paid      = rows.filter(r => r.pay?.paid).length;
  const pending   = rows.length - paid;
  const totalPaid = paid * MONTHLY_FEE;
  const totalPend = pending * MONTHLY_FEE;

  // Season totals
  const seasonPaid = players.reduce((s, p) =>
    s + (payments[p.id]?.filter(x => x.paid).length || 0) * MONTHLY_FEE, 0);

  return (
    <div>
      <div style={{marginBottom:24}}>
        <h2 style={{margin:0,fontSize:20,fontWeight:700,color:T.text,letterSpacing:"-0.02em"}}>Pagos mensuales</h2>
        <p style={{margin:"4px 0 0",fontSize:13,color:T.muted}}>Cuota: ${MONTHLY_FEE} MXN / jugadora / mes &nbsp;·&nbsp; Vence el día <strong style={{color:T.accent}}>27</strong> de cada mes</p>
      </div>

      <div className="t-grid-6" style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:12,marginBottom:20}}>
        <PKPICard label="Recaudado este mes"  value={`$${totalPaid.toLocaleString()}`}  color={T.green}  sub={`${paid} de ${players.length} jugadoras`} />
        <PKPICard label="Pendiente este mes"  value={`$${totalPend.toLocaleString()}`}  color={pending>0?T.red:T.green}  sub={`${pending} jugadoras`} />
        <PKPICard label="Cumplimiento"        value={`${Math.round(paid/players.length*100)}%`} color={paid/players.length>=0.8?T.green:T.yellow} />
        <PKPICard label="Total temporada"     value={`$${seasonPaid.toLocaleString()}`} color={T.text}   sub="acumulado" />
      </div>

      {/* Month tabs */}
      <div style={{display:"flex",gap:6,marginBottom:16}}>
        {paymentMonths.map(m => (
          <button key={m} onClick={() => setSelMonth(m)} style={{
            padding:"7px 20px", border:`1px solid ${selMonth===m?T.accent:T.border}`,
            borderRadius:6, background:selMonth===m?T.accentLt:"#fff",
            color:selMonth===m?T.accent:T.muted,
            fontWeight:selMonth===m?600:400, fontSize:13,
            cursor:"pointer", fontFamily:"inherit", transition:"all 0.12s"
          }}>{monthLabels[m]}</button>
        ))}
      </div>

      <PCard padding="0">
        <PTable
          columns={[
            {key:"player",  label:"Jugadora"},
            {key:"pos",     label:"Posición"},
            {key:"amount",  label:"Cuota",       right:true},
            {key:"status",  label:"Estado"},
            {key:"date",    label:"Fecha de pago"},
            {key:"method",  label:"Método"},
            {key:"action",  label:"",            right:true},
          ]}
          rows={rows.map(({player:p, pay}) => {
            const isPaid   = !!pay?.paid;
            const overdue  = !isPaid && curIdx < lastIdx;
            const statusColor = isPaid ? T.green : overdue ? T.red : T.yellow;
            const statusBg    = isPaid ? T.greenLt : overdue ? T.redLt : T.yellowLt;
            const statusBdr   = isPaid ? "#bbf7d0" : overdue ? "#fecaca" : "#fde68a";
            const statusLabel = isPaid ? "Pagado" : overdue ? "Vencido" : "Pendiente";
            return {
              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.name}</span>
                </div>
              ),
              pos:    <PBadge text={p.pos} color={posColorsP[p.pos]} variant="pill" />,
              amount: `$${MONTHLY_FEE}`,
              status: (
                <span style={{fontSize:12,fontWeight:700,color:statusColor,background:statusBg,
                  padding:"3px 10px",borderRadius:4,border:`1px solid ${statusBdr}`}}>
                  {statusLabel}
                </span>
              ),
              date:   pay?.date   || <span style={{color:T.subtle,fontSize:12}}>—</span>,
              method: pay?.method || <span style={{color:T.subtle,fontSize:12}}>—</span>,
              action: (() => {
                const picking = methodPick && methodPick.pid === p.id && methodPick.month === selMonth;
                if (isPaid) return (
                  <button onClick={e=>{e.stopPropagation();unpay(p.id,selMonth);}} style={{
                    padding:"5px 12px", borderRadius:5, fontWeight:600, fontSize:11,
                    cursor:"pointer", fontFamily:"inherit",
                    border:"1px solid #fecaca", background:T.redLt, color:T.red,
                  }}>Marcar pendiente</button>
                );
                if (picking) return (
                  <div style={{display:"flex",gap:6,alignItems:"center"}}>
                    <span style={{fontSize:11,color:T.muted,marginRight:2}}>Método:</span>
                    {["Efectivo","Transferencia"].map(m => (
                      <button key={m} onClick={e=>{e.stopPropagation();confirmPay(p.id,selMonth,m);}} style={{
                        padding:"5px 10px", borderRadius:5, fontWeight:600, fontSize:11,
                        cursor:"pointer", fontFamily:"inherit",
                        border:`1px solid ${T.accentMd}`, background:T.accentLt, color:T.accent,
                      }}>{m}</button>
                    ))}
                    <button onClick={e=>{e.stopPropagation();setMethodPick(null);}} style={{
                      padding:"5px 8px", borderRadius:5, fontWeight:700, fontSize:12,
                      cursor:"pointer", fontFamily:"inherit",
                      border:`1px solid ${T.border}`, background:"#fff", color:T.muted,
                    }}>✕</button>
                  </div>
                );
                return (
                  <button onClick={e=>{e.stopPropagation();setMethodPick({pid:p.id,month:selMonth});}} style={{
                    padding:"5px 12px", borderRadius:5, fontWeight:600, fontSize:11,
                    cursor:"pointer", fontFamily:"inherit",
                    border:`1px solid ${T.accentMd}`, background:T.accentLt, color:T.accent,
                  }}>Marcar pagado</button>
                );
              })(),
            };
          })}
        />
        <div style={{height:4}} />
      </PCard>
    </div>
  );
}

// ── REGISTRO ──────────────────────────────────────────────
// ── DOCUMENTOS ────────────────────────────────────────────
function AdminDocumentos() {
  const { players } = window.TData;
  const { documents: init, DOC_TYPES } = window.TAdmin;

  const [docs, setDocs] = React.useState(init);

  // On mount: load docs from server
  React.useEffect(() => {
    fetch('/api/documentos.php')
      .then(r => r.json())
      .then(serverDocs => {
        if (serverDocs && typeof serverDocs === 'object' && Object.keys(serverDocs).length > 0) {
          setDocs(prev => {
            const next = { ...prev };
            Object.entries(serverDocs).forEach(([pid, fields]) => {
              if (next[+pid]) next[+pid] = { ...next[+pid], ...fields };
            });
            return next;
          });
        }
      })
      .catch(() => {});
  }, []);

  const CYCLE = ["ok","pendiente","faltante"];
  const cycle = (pid, key) => {
    if (!docs[pid]) return;
    const cur  = docs[pid][key];
    const next = { ...docs, [pid]: { ...docs[pid], [key]: CYCLE[(CYCLE.indexOf(cur)+1)%CYCLE.length] } };
    setDocs(next);
    fetch('/api/documentos.php', {
      method: 'POST', headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ adminKey: ADMIN_KEY, docs: next }),
    }).catch(() => {});
  };

  const sc = s => s==="ok" ? T.green  : s==="pendiente" ? T.yellow  : T.red;
  const sb = s => s==="ok" ? T.greenLt: s==="pendiente" ? T.yellowLt: T.redLt;
  const sl = s => s==="ok" ? "OK"     : s==="pendiente" ? "Pendiente": "Faltante";

  const total       = players.length * DOC_TYPES.length;
  const totalOk     = players.reduce((n,p)=>n+DOC_TYPES.filter(d=>docs[p.id]?.[d.key]==="ok").length,0);
  const totalFalta  = players.reduce((n,p)=>n+DOC_TYPES.filter(d=>docs[p.id]?.[d.key]==="faltante").length,0);
  const totalPend   = players.reduce((n,p)=>n+DOC_TYPES.filter(d=>docs[p.id]?.[d.key]==="pendiente").length,0);

  return (
    <div>
      <div style={{marginBottom:24}}>
        <h2 style={{margin:0,fontSize:20,fontWeight:700,color:T.text,letterSpacing:"-0.02em"}}>Documentos</h2>
        <p style={{margin:"4px 0 0",fontSize:13,color:T.muted}}>Haz clic en cada celda para cambiar el estado</p>
      </div>

      <div className="t-grid-6" style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:12,marginBottom:20}}>
        <PKPICard label="Completos"   value={totalOk}    color={T.green}                          sub={`de ${total} totales`} />
        <PKPICard label="Faltantes"   value={totalFalta}  color={totalFalta>0?T.red:T.green}      sub="sin entregar" />
        <PKPICard label="Pendientes"  value={totalPend}   color={totalPend>0?T.yellow:T.green}    sub="en proceso" />
        <PKPICard label="Cumplimiento" value={`${Math.round(totalOk/total*100)}%`} color={totalOk/total>=0.8?T.green:T.yellow} />
      </div>

      <PCard padding="0">
        <div style={{overflowX:"auto"}}>
          <table style={{width:"100%",borderCollapse:"collapse",fontSize:13}}>
            <thead>
              <tr style={{background:T.stripe}}>
                <th style={{padding:"10px 16px",textAlign:"left",color:T.muted,fontWeight:600,
                  fontSize:11,textTransform:"uppercase",letterSpacing:"0.06em",
                  borderBottom:`2px solid ${T.border}`,minWidth:200,position:"sticky",left:0,background:T.stripe,zIndex:2}}>
                  Jugadora
                </th>
                {DOC_TYPES.map(dt=>(
                  <th key={dt.key} style={{padding:"10px 16px",textAlign:"center",color:T.muted,
                    fontWeight:600,fontSize:11,textTransform:"uppercase",letterSpacing:"0.06em",
                    borderBottom:`2px solid ${T.border}`,minWidth:140}}>
                    {dt.label}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {players.map((p, pi) => (
                <tr key={p.id} style={{background:pi%2===1?T.stripe:"#fff"}}>
                  <td style={{padding:"10px 16px",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={26} />
                      <div>
                        <div style={{fontWeight:500,fontSize:13,color:T.text}}>{p.name}</div>
                        <div style={{fontSize:11,color:T.muted}}>#{p.num}</div>
                      </div>
                    </div>
                  </td>
                  {DOC_TYPES.map(dt => {
                    const s = docs[p.id]?.[dt.key] || "faltante";
                    return (
                      <td key={dt.key} style={{padding:"10px 16px",textAlign:"center",borderBottom:`1px solid ${T.border}`}}>
                        <span onClick={() => cycle(p.id, dt.key)} style={{
                          display:"inline-block", padding:"4px 12px", borderRadius:4,
                          background:sb(s), color:sc(s), fontWeight:700, fontSize:11,
                          border:`1px solid ${sc(s)}30`, cursor:"pointer",
                          transition:"all 0.12s", userSelect:"none"
                        }}>{sl(s)}</span>
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{display:"flex",gap:20,padding:"12px 16px",fontSize:11,color:T.muted,borderTop:`1px solid ${T.border}`}}>
          <span><span style={{color:T.green,fontWeight:700}}>OK</span> = Entregado</span>
          <span><span style={{color:T.yellow,fontWeight:700}}>Pendiente</span> = En revisión</span>
          <span><span style={{color:T.red,fontWeight:700}}>Faltante</span> = Sin entregar</span>
          <span style={{marginLeft:"auto"}}>Clic en celda para cambiar estado</span>
        </div>
      </PCard>
    </div>
  );
}

window.AdminPagos       = AdminPagos;
window.AdminDocumentos  = AdminDocumentos;

// ── JUGADORAS (ROSTER + CONTACTOS) ───────────────────────────
const POSITIONS = ["Base","Escolta","Alero","Ala-Pívot","Pívot"];
const AVATAR_COLORS = ["#2bbdf7","#e8508a","#8b6db8","#1a7ecf","#10b981","#f59e0b","#ef4444","#6366f1"];

function AdminJugadoras() {
  const [activeTab, setActiveTab] = React.useState("roster");
  const [pendCount, setPendCount] = React.useState(0);

  // Refresh pending count from server on mount
  React.useEffect(() => {
    fetch('/api/registros.php').then(r => r.json()).then(data => {
      const n = Array.isArray(data) ? data.filter(r => r.status === 'pendiente').length : 0;
      setPendCount(n);
    }).catch(() => {});
  }, []);

  const tabBtn = (id, label, badge) => (
    <button key={id} onClick={() => setActiveTab(id)} style={{
      padding:"8px 16px", border:"none", cursor:"pointer", fontFamily:"inherit",
      background: activeTab === id ? T.accent : "transparent",
      color: activeTab === id ? "#fff" : T.muted,
      fontWeight: activeTab === id ? 700 : 500,
      fontSize:13, borderRadius:6, transition:"all 0.12s",
      display:"flex", alignItems:"center", gap:6
    }}>
      {label}
      {badge > 0 && (
        <span style={{
          background: activeTab === id ? "rgba(255,255,255,0.3)" : T.accent,
          color:"#fff", fontSize:10, fontWeight:800,
          borderRadius:99, padding:"1px 6px", minWidth:18, textAlign:"center"
        }}>{badge}</span>
      )}
    </button>
  );

  return (
    <div style={{ display:"flex", flexDirection:"column", gap:20 }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", flexWrap:"wrap", gap:10 }}>
        <div>
          <h2 style={{ margin:0, fontSize:20, fontWeight:700, color:T.text, letterSpacing:"-0.02em" }}>Jugadoras</h2>
          <p style={{ margin:"4px 0 0", fontSize:13, color:T.muted }}>Roster, contactos y registros pendientes</p>
        </div>
        <div style={{ display:"flex", gap:4, background:T.stripe, borderRadius:8, padding:4 }}>
          {tabBtn("roster","Roster")}
          {tabBtn("registros","Registros")}
          {tabBtn("pendientes","Pendientes", pendCount)}
        </div>
      </div>

      {activeTab === "roster"     && <RosterTab />}
      {activeTab === "registros"  && <RegistrosTab />}
      {activeTab === "pendientes" && <PendientesTab onApprove={() => { setPendCount(c => Math.max(0, c-1)); }} />}
    </div>
  );
}

function syncRoster(list) {
  window.TData.players = list;
  fetch('/api/roster.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ adminKey: 'TormPortal2026', players: list }),
  }).catch(() => {});
}

function RosterTab() {
  const [players, setPlayers] = React.useState(() => [...window.TData.players]);
  const [modal,   setModal]   = React.useState(null);
  const [form,    setForm]    = React.useState({});
  const [deleteId, setDeleteId] = React.useState(null);

  // Load from server on mount, prefer server over data.js defaults
  React.useEffect(() => {
    fetch('/api/roster.php').then(r => r.json()).then(data => {
      if (Array.isArray(data) && data.length > 0) {
        window.TData.players = data;
        setPlayers(data);
      }
    }).catch(() => {});
  }, []);

  const persist = (list) => {
    syncRoster(list);
    setPlayers(list);
  };

  const openAdd = () => {
    setForm({ name:"", num:"", pos:"Base", hand:"Derecha", color:"#2bbdf7" });
    setModal("add");
  };

  const openEdit = (p) => {
    setForm({...p, num: String(p.num)});
    setModal("edit");
  };

  const handleSubmit = () => {
    if (!form.name.trim() || !form.num) return;
    const words = form.name.trim().split(" ").filter(Boolean);
    const initials = words.map(w => w[0].toUpperCase()).join("").slice(0, 2);
    const num = parseInt(form.num) || 0;
    if (modal === "add") {
      const id = Math.max(0, ...players.map(p => p.id)) + 1;
      persist([...players, { ...form, id, num, initials, attendancePct: 90 }]);
    } else {
      persist(players.map(p => p.id === form.id ? { ...form, num, initials } : p));
    }
    setModal(null);
  };

  const confirmDelete = () => {
    persist(players.filter(p => p.id !== deleteId));
    setDeleteId(null);
  };

  const inputSt = {
    width:"100%", padding:"10px 12px", border:"1.5px solid #e2e8f0", borderRadius:8,
    fontSize:13, fontFamily:"inherit", outline:"none", color:"#0f172a", background:"#f8fafc"
  };
  const btnSt = (color, bg) => ({
    padding:"8px 16px", borderRadius:8, border:"none", cursor:"pointer",
    fontWeight:600, fontSize:13, fontFamily:"inherit", color, background:bg
  });
  const field = (label, key, type="text", opts=null) => (
    <div style={{ marginBottom:16 }}>
      <label style={{ fontSize:11, fontWeight:700, color:"#64748b", textTransform:"uppercase", letterSpacing:"0.07em", display:"block", marginBottom:6 }}>{label}</label>
      {opts ? (
        <select value={form[key]||""} onChange={e=>setForm(f=>({...f,[key]:e.target.value}))} style={inputSt}>
          {opts.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      ) : (
        <input type={type} value={form[key]||""} onChange={e=>setForm(f=>({...f,[key]:e.target.value}))} style={inputSt} />
      )}
    </div>
  );

  return (
    <>
      <div style={{ display:"flex", justifyContent:"flex-end" }}>
        <button onClick={openAdd} style={{ ...btnSt("#fff","#2563eb"), padding:"10px 20px", fontSize:14 }}>
          + Agregar jugadora
        </button>
      </div>

      <div style={{ background:"#fff", borderRadius:12, border:`1px solid ${T.border}`, overflow:"hidden" }}>
        {players.map((p, i) => (
          <div key={p.id} style={{
            display:"flex", alignItems:"center", gap:14, padding:"14px 20px",
            borderBottom: i < players.length-1 ? `1px solid ${T.border}` : "none",
          }}>
            <PAvatar initials={p.initials} color={p.color || posColorsP[p.pos] || T.accent} size={40} />
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontSize:14, fontWeight:600, color:T.text }}>{p.name}</div>
              <div style={{ fontSize:12, color:T.muted, marginTop:2 }}>#{p.num} · {p.pos} · {p.hand}</div>
            </div>
            <div style={{ display:"flex", gap:8, flexShrink:0 }}>
              <button onClick={() => openEdit(p)} style={{ ...btnSt("#2563eb","#eff6ff"), padding:"7px 14px" }}>Editar</button>
              <button onClick={() => setDeleteId(p.id)} style={{ ...btnSt("#dc2626","#fef2f2"), padding:"7px 14px" }}>Eliminar</button>
            </div>
          </div>
        ))}
      </div>

      {modal && (
        <div style={{ position:"fixed", inset:0, background:"rgba(0,0,0,0.5)", zIndex:300, display:"flex", alignItems:"center", justifyContent:"center", padding:16 }}>
          <div style={{ background:"#fff", borderRadius:16, padding:32, width:"min(460px,100%)", maxHeight:"90vh", overflowY:"auto" }}>
            <h3 style={{ margin:"0 0 24px", fontSize:18, fontWeight:700, color:T.text }}>
              {modal === "add" ? "Agregar jugadora" : "Editar jugadora"}
            </h3>
            {field("Nombre completo", "name")}
            <div className="t-grid-2" style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:14 }}>
              <div>{field("Número", "num", "number")}</div>
              <div>{field("Posición", "pos", "text", POSITIONS)}</div>
            </div>
            {field("Mano dominante", "hand", "text", ["Derecha","Izquierda"])}
            <div style={{ marginBottom:16 }}>
              <label style={{ fontSize:11, fontWeight:700, color:"#64748b", textTransform:"uppercase", letterSpacing:"0.07em", display:"block", marginBottom:8 }}>Color del avatar</label>
              <div style={{ display:"flex", gap:10, flexWrap:"wrap" }}>
                {AVATAR_COLORS.map(c => (
                  <div key={c} onClick={() => setForm(f=>({...f, color:c}))} style={{
                    width:28, height:28, borderRadius:"50%", background:c, cursor:"pointer",
                    border: form.color===c ? "3px solid #0f172a" : "3px solid transparent",
                    boxSizing:"border-box"
                  }} />
                ))}
              </div>
            </div>
            <div style={{ display:"flex", gap:10, marginTop:24 }}>
              <button onClick={handleSubmit} style={{ ...btnSt("#fff","#2563eb"), flex:1, padding:"12px" }}>Guardar</button>
              <button onClick={() => setModal(null)} style={{ ...btnSt("#64748b","#f1f5f9"), flex:1, padding:"12px" }}>Cancelar</button>
            </div>
          </div>
        </div>
      )}

      {deleteId && (
        <div style={{ position:"fixed", inset:0, background:"rgba(0,0,0,0.5)", zIndex:300, display:"flex", alignItems:"center", justifyContent:"center", padding:16 }}>
          <div style={{ background:"#fff", borderRadius:16, padding:32, width:"min(360px,100%)", textAlign:"center" }}>
            <div style={{ fontSize:40, marginBottom:12 }}>⚠️</div>
            <h3 style={{ margin:"0 0 8px", fontSize:17, fontWeight:700, color:T.text }}>¿Eliminar jugadora?</h3>
            <p style={{ margin:"0 0 24px", fontSize:13, color:T.muted }}>
              {players.find(p=>p.id===deleteId)?.name} — Esta acción no se puede deshacer.
            </p>
            <div style={{ display:"flex", gap:10 }}>
              <button onClick={confirmDelete} style={{ ...btnSt("#fff","#dc2626"), flex:1, padding:"12px" }}>Eliminar</button>
              <button onClick={() => setDeleteId(null)} style={{ ...btnSt("#64748b","#f1f5f9"), flex:1, padding:"12px" }}>Cancelar</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

const CATEGORIAS_EDIT = ["2014","2017","Mini","Infantil","Cadete","Juvenil","Mayor"];
const POSICIONES_EDIT = ["Base","Escolta","Alero","Ala-Pivot","Pivot"];

function RegistrosTab() {
  const [regs,     setRegs]     = React.useState([]);
  const [loading,  setLoading]  = React.useState(true);
  const [expanded, setExpanded] = React.useState(null);
  const [editing,  setEditing]  = React.useState(null);
  const [form,     setForm]     = React.useState({});
  const [saving,   setSaving]   = React.useState(false);
  const [pdfReg,   setPdfReg]   = React.useState(null);
  const [search,   setSearch]   = React.useState("");

  function load() {
    fetch('/api/registros.php').then(r => r.json()).then(data => {
      setRegs(Array.isArray(data) ? data : []);
      setLoading(false);
    }).catch(() => setLoading(false));
  }
  React.useEffect(() => { load(); }, []);

  const filtered = regs.filter(r => {
    const q = search.toLowerCase();
    return !q ||
      (r.jugadora?.nombre||'').toLowerCase().includes(q) ||
      (r.jugadora?.categoria||'').toLowerCase().includes(q) ||
      (r.contactos?.c1?.nombre||'').toLowerCase().includes(q);
  });

  const statusColor = { aprobada:'#16A34A', pendiente:'#D97706', rechazado:'#DC2626' };
  const statusLabel = { aprobada:'Aprobada', pendiente:'Pendiente', rechazado:'Rechazado' };

  function openEdit(reg) {
    const j = reg.jugadora || {};
    setForm({
      id: reg.id,
      nombre:    j.nombre    || '',
      categoria: j.categoria || '',
      numero:    j.numero    || '',
      posicion:  j.posicion  || '',
      escuela:   j.escuela   || '',
      fechaNac:  j.fechaNac  || '',
      curp:      j.curp      || '',
    });
    setEditing(reg.id);
  }

  function saveEdit() {
    setSaving(true);
    fetch('/api/registros.php?action=admin_edit', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ adminKey:'TormPortal2026', ...form }),
    })
    .then(r => r.json())
    .then(d => {
      setSaving(false);
      if (d.ok) {
        setEditing(null);
        // Update local state immediately
        setRegs(prev => prev.map(r => r.id !== form.id ? r : {
          ...r, jugadora: { ...r.jugadora,
            nombre: form.nombre, categoria: form.categoria, numero: form.numero,
            posicion: form.posicion, escuela: form.escuela, fechaNac: form.fechaNac, curp: form.curp,
          }
        }));
        // Also update TData.players name/num if this reg has a playerId
        const reg = regs.find(r => r.id === form.id);
        if (reg?.playerId) {
          const pid = parseInt(reg.playerId);
          const updated = window.TData.players.map(p => p.id !== pid ? p : {
            ...p, name: form.nombre, num: parseInt(form.numero)||p.num, pos: form.posicion||p.pos,
            initials: form.nombre.trim().split(' ').filter(Boolean).map(w=>w[0].toUpperCase()).join('').slice(0,2),
          });
          syncRoster(updated);
        }
      }
    })
    .catch(() => setSaving(false));
  }

  const inputSt = { width:'100%', padding:'9px 11px', border:`1.5px solid ${T.border}`, borderRadius:8, fontSize:13, fontFamily:'inherit', color:T.text, outline:'none' };
  const lbl = txt => <label style={{display:'block',fontSize:10,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.06em',marginBottom:5}}>{txt}</label>;

  if (loading) return <div style={{textAlign:'center',padding:'60px 20px',color:T.muted,fontSize:13}}>Cargando registros...</div>;

  return (
    <>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:12,flexWrap:'wrap'}}>
        <div style={{fontSize:13,color:T.muted}}>{regs.length} registro{regs.length!==1?'s':''} en total</div>
        <div style={{position:'relative'}}>
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Buscar jugadora o tutor..."
            style={{padding:'7px 12px 7px 32px',borderRadius:6,border:`1px solid ${T.border}`,fontSize:13,color:T.text,outline:'none',fontFamily:'inherit',width:220,background:'#fff'}} />
          <span style={{position:'absolute',left:10,top:'50%',transform:'translateY(-50%)',color:T.muted,fontSize:13}}>⌕</span>
        </div>
      </div>

      <div style={{display:'flex',flexDirection:'column',gap:8}}>
        {filtered.length === 0 && <div style={{textAlign:'center',padding:'40px 20px',color:T.muted,fontSize:13}}>Sin registros{search?' que coincidan':' aun'}.</div>}
        {filtered.map(reg => {
          const j   = reg.jugadora || {};
          const c   = reg.contactos || {};
          const isOpen = expanded === reg.id;
          const st  = reg.status || 'pendiente';
          const ini = (j.nombre||'?').trim().split(' ').filter(Boolean).map(w=>w[0].toUpperCase()).join('').slice(0,2);

          return (
            <PCard key={reg.id} style={{padding:0,overflow:'hidden'}}>
              {/* Row */}
              <div style={{display:'flex',alignItems:'center',gap:14,padding:'14px 20px'}}>
                {reg.foto
                  ? <img src={reg.foto} alt={j.nombre} style={{width:40,height:40,borderRadius:'50%',objectFit:'cover',flexShrink:0,border:`2px solid ${T.accent}`}} />
                  : <PAvatar initials={ini} color={T.accent} size={40} />
                }
                <div style={{flex:1,minWidth:0,cursor:'pointer'}} onClick={() => setExpanded(isOpen ? null : reg.id)}>
                  <div style={{fontWeight:600,fontSize:14,color:T.text}}>{j.nombre || '—'}</div>
                  <div style={{fontSize:12,color:T.muted,marginTop:2,display:'flex',gap:8,flexWrap:'wrap'}}>
                    {j.categoria && <span style={{background:T.accent+'18',color:T.accent,padding:'1px 8px',borderRadius:10,fontWeight:700,fontSize:10}}>{j.categoria}</span>}
                    {j.numero   && <span>#{j.numero}</span>}
                    {j.posicion && <span>{j.posicion}</span>}
                    {c.c1?.nombre && <span style={{color:T.muted}}>· {c.c1.nombre}</span>}
                  </div>
                </div>
                <div style={{display:'flex',gap:8,flexShrink:0,alignItems:'center'}}>
                  <span style={{fontSize:10,fontWeight:700,padding:'3px 10px',borderRadius:10,background:statusColor[st]+'18',color:statusColor[st]}}>{statusLabel[st]||st}</span>
                  <button onClick={()=>openEdit(reg)} style={{padding:'6px 12px',background:'#EFF6FF',border:`1px solid #BFDBFE`,borderRadius:7,fontWeight:600,fontSize:11,cursor:'pointer',fontFamily:'inherit',color:'#2563EB'}}>Editar</button>
                  <button onClick={()=>setPdfReg(reg)} style={{padding:'6px 12px',background:T.stripe,border:`1px solid ${T.border}`,borderRadius:7,fontWeight:600,fontSize:11,cursor:'pointer',fontFamily:'inherit',color:T.text}}>Ver registro</button>
                  <button onClick={()=>setExpanded(isOpen?null:reg.id)} style={{background:'none',border:'none',cursor:'pointer',color:T.muted,fontSize:12,padding:'4px 6px'}}>{isOpen?'▲':'▼'}</button>
                </div>
              </div>

              {/* Expanded: quick summary */}
              {isOpen && (
                <div style={{padding:'16px 20px',borderTop:`1px solid ${T.border}`,background:'#fafbfd',display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:16}}>
                  <div>
                    <PLabel>Datos de salud</PLabel>
                    {[
                      ['Tipo de sangre', reg.salud?.tipoSangre],
                      ['Alergias',       reg.salud?.alergias],
                      ['Medicamentos',   reg.salud?.medicamentos],
                      ['Condiciones',    reg.salud?.condiciones],
                      ['Medico',         reg.salud?.medico],
                    ].filter(([,v])=>v).map(([l,v])=>(
                      <div key={l} style={{display:'flex',justifyContent:'space-between',marginBottom:7,gap:8}}>
                        <span style={{fontSize:11,color:T.muted,flexShrink:0}}>{l}</span>
                        <span style={{fontSize:11,fontWeight:600,color:T.text,textAlign:'right'}}>{v}</span>
                      </div>
                    ))}
                  </div>
                  <div>
                    <PLabel>Contacto familiar</PLabel>
                    {[c.c1, c.c2].filter(Boolean).map((p,i) => (
                      <div key={i} style={{marginBottom:8,padding:'8px 10px',background:'#fff',borderRadius:6,border:`1px solid ${T.border}`}}>
                        <div style={{fontSize:12,fontWeight:600,color:T.text}}>{p.nombre} <span style={{fontWeight:400,color:T.muted,fontSize:10}}>({p.relacion})</span></div>
                        <div style={{fontSize:11,color:T.muted}}>{p.tel}</div>
                        <div style={{fontSize:11,color:T.muted}}>{p.email}</div>
                      </div>
                    ))}
                  </div>
                  <div>
                    <PLabel>Emergencia</PLabel>
                    <div style={{padding:'8px 10px',background:'#fff',borderRadius:6,border:`1px solid ${T.border}`}}>
                      <div style={{fontSize:12,fontWeight:600,color:T.text}}>{c.emergencia?.nombre}</div>
                      <div style={{fontSize:13,fontWeight:700,color:T.accent}}>{c.emergencia?.tel}</div>
                    </div>
                    <div style={{marginTop:12}}>
                      <PLabel>Fecha de registro</PLabel>
                      <div style={{fontSize:12,color:T.muted}}>{reg.fecha}</div>
                    </div>
                  </div>
                </div>
              )}
            </PCard>
          );
        })}
      </div>

      {/* Edit modal */}
      {editing && (
        <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.55)',zIndex:300,display:'flex',alignItems:'center',justifyContent:'center',padding:16,overflowY:'auto'}}>
          <div style={{background:'#fff',borderRadius:14,padding:28,width:'min(480px,100%)',boxShadow:'0 24px 60px #00000040'}}>
            <div style={{fontSize:16,fontWeight:700,color:T.text,marginBottom:20}}>Editar datos de la jugadora</div>
            <div style={{marginBottom:14}}>{lbl('Nombre completo')}<input value={form.nombre} onChange={e=>setForm(f=>({...f,nombre:e.target.value}))} style={inputSt} /></div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginBottom:14}}>
              <div>{lbl('Categoria')}
                <select value={form.categoria} onChange={e=>setForm(f=>({...f,categoria:e.target.value}))} style={inputSt}>
                  <option value="">— Sin asignar —</option>
                  {CATEGORIAS_EDIT.map(c=><option key={c} value={c}>{c}</option>)}
                </select>
              </div>
              <div>{lbl('Posicion')}
                <select value={form.posicion} onChange={e=>setForm(f=>({...f,posicion:e.target.value}))} style={inputSt}>
                  <option value="">— Sin asignar —</option>
                  {POSICIONES_EDIT.map(p=><option key={p} value={p}>{p}</option>)}
                </select>
              </div>
            </div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginBottom:14}}>
              <div>{lbl('No. de jersey')}<input type="number" min="0" max="99" value={form.numero} onChange={e=>setForm(f=>({...f,numero:e.target.value}))} style={inputSt} /></div>
              <div>{lbl('Escuela')}<input value={form.escuela} onChange={e=>setForm(f=>({...f,escuela:e.target.value}))} style={inputSt} /></div>
            </div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginBottom:22}}>
              <div>{lbl('Fecha de nacimiento')}<input type="date" value={form.fechaNac} onChange={e=>setForm(f=>({...f,fechaNac:e.target.value}))} style={inputSt} /></div>
              <div>{lbl('CURP')}<input value={form.curp} onChange={e=>setForm(f=>({...f,curp:e.target.value.toUpperCase()}))} maxLength={18} style={{...inputSt,textTransform:'uppercase'}} /></div>
            </div>
            <div style={{display:'flex',gap:10}}>
              <button onClick={()=>setEditing(null)} style={{flex:1,padding:'11px',background:'#F8FAFC',border:`1px solid ${T.border}`,borderRadius:8,fontWeight:600,fontSize:13,cursor:'pointer',fontFamily:'inherit',color:T.text}}>Cancelar</button>
              <button onClick={saveEdit} disabled={saving} style={{flex:2,padding:'11px',background:'#2563EB',color:'#fff',border:'none',borderRadius:8,fontWeight:700,fontSize:13,cursor:saving?'not-allowed':'pointer',opacity:saving?0.5:1,fontFamily:'inherit'}}>
                {saving ? 'Guardando...' : 'Guardar cambios'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* PDF / Full registration view */}
      {pdfReg && <RegistroPdfModal reg={pdfReg} onClose={() => setPdfReg(null)} />}
    </>
  );
}

function RegistroPdfModal({ reg, onClose }) {
  const j  = reg.jugadora  || {};
  const s  = reg.salud     || {};
  const c  = reg.contactos || {};
  const au = reg.autorizaciones || [];

  const section = (title, rows) => (
    <div style={{marginBottom:20}}>
      <div style={{fontSize:10,fontWeight:700,color:'#64748B',textTransform:'uppercase',letterSpacing:'.09em',borderBottom:'2px solid #E2EBF3',paddingBottom:6,marginBottom:10}}>{title}</div>
      {rows.filter(([,v])=>v!=null&&v!=='').map(([l,v])=>(
        <div key={l} style={{display:'flex',gap:8,marginBottom:6}}>
          <span style={{fontSize:12,color:'#64748B',width:160,flexShrink:0}}>{l}:</span>
          <span style={{fontSize:12,fontWeight:600,color:'#0A2540',flex:1}}>{v}</span>
        </div>
      ))}
    </div>
  );

  const AUTH_LABELS = {
    auth_foto:         'Autorizo uso de fotografía y video',
    auth_medica:       'Autorizo atención médica de emergencia',
    auth_transporte:   'Autorizo transporte a eventos',
    auth_datos:        'Autorizo uso de datos personales',
  };

  return (
    <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.6)',zIndex:400,display:'flex',alignItems:'flex-start',justifyContent:'center',padding:'20px 16px',overflowY:'auto'}}>
      <div style={{background:'#fff',borderRadius:14,width:'min(640px,100%)',boxShadow:'0 32px 80px #00000050',marginBottom:20}}>
        {/* Modal header */}
        <div style={{background:'#0A2540',borderRadius:'14px 14px 0 0',padding:'18px 24px',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div>
            <div style={{color:'#fff',fontSize:16,fontWeight:800,letterSpacing:'-.01em'}}>Hoja de registro</div>
            <div style={{color:'#94B4C8',fontSize:12,marginTop:2}}>{j.nombre} · Tormentas Basketball 2026</div>
          </div>
          <div style={{display:'flex',gap:10}}>
            <button onClick={()=>window.print()} style={{padding:'8px 16px',background:'#FF6B9D',color:'#fff',border:'none',borderRadius:7,fontWeight:700,fontSize:12,cursor:'pointer'}}>Imprimir</button>
            <button onClick={onClose} style={{padding:'8px 14px',background:'rgba(255,255,255,.12)',color:'#fff',border:'none',borderRadius:7,fontWeight:600,fontSize:13,cursor:'pointer'}}>✕</button>
          </div>
        </div>

        <div style={{padding:'24px'}}>
          {/* Photo + basic */}
          <div style={{display:'flex',gap:20,marginBottom:20,alignItems:'flex-start'}}>
            {reg.foto && <img src={reg.foto} alt="" style={{width:90,height:90,borderRadius:10,objectFit:'cover',border:'2px solid #E2EBF3',flexShrink:0}} />}
            <div style={{flex:1}}>
              <div style={{fontSize:22,fontWeight:800,color:'#0A2540',letterSpacing:'-.02em'}}>{j.nombre}</div>
              <div style={{display:'flex',gap:8,flexWrap:'wrap',marginTop:6}}>
                {j.categoria && <span style={{background:'#FF6B9D18',color:'#FF6B9D',padding:'3px 10px',borderRadius:10,fontWeight:700,fontSize:11}}>{j.categoria}</span>}
                {j.posicion  && <span style={{background:'#5B9BD518',color:'#5B9BD5',padding:'3px 10px',borderRadius:10,fontWeight:700,fontSize:11}}>{j.posicion}</span>}
                {j.numero    && <span style={{background:'#0A254010',color:'#0A2540',padding:'3px 10px',borderRadius:10,fontWeight:700,fontSize:11}}>#{j.numero}</span>}
              </div>
              <div style={{fontSize:12,color:'#64748B',marginTop:8}}>Registrada el {reg.fecha} · ID: {reg.id}</div>
            </div>
          </div>

          {section('Datos de la jugadora', [
            ['Fecha de nacimiento', j.fechaNac],
            ['CURP',               j.curp],
            ['Escuela / Colegio',  j.escuela],
          ])}

          {section('Salud', [
            ['Tipo de sangre',  s.tipoSangre],
            ['Alergias',        s.alergias],
            ['Medicamentos',    s.medicamentos],
            ['Condiciones',     s.condiciones],
            ['Seguro médico',   s.seguro],
            ['Médico',          s.medico],
            ['Tel. médico',     s.telMedico],
          ])}

          {section('Contacto 1', [
            ['Nombre',    c.c1?.nombre],
            ['Relación',  c.c1?.relacion],
            ['Teléfono',  c.c1?.tel],
            ['Correo',    c.c1?.email],
          ])}

          {c.c2?.nombre && section('Contacto 2', [
            ['Nombre',    c.c2?.nombre],
            ['Relación',  c.c2?.relacion],
            ['Teléfono',  c.c2?.tel],
            ['Correo',    c.c2?.email],
          ])}

          {section('Contacto de emergencia', [
            ['Nombre',    c.emergencia?.nombre],
            ['Teléfono',  c.emergencia?.tel],
          ])}

          {/* Autorizaciones */}
          {au.length > 0 && (
            <div style={{marginBottom:20}}>
              <div style={{fontSize:10,fontWeight:700,color:'#64748B',textTransform:'uppercase',letterSpacing:'.09em',borderBottom:'2px solid #E2EBF3',paddingBottom:6,marginBottom:10}}>Autorizaciones otorgadas</div>
              {au.map(k => (
                <div key={k} style={{display:'flex',alignItems:'center',gap:8,marginBottom:6}}>
                  <span style={{color:'#16A34A',fontSize:14,fontWeight:700}}>✓</span>
                  <span style={{fontSize:12,color:'#0A2540'}}>{AUTH_LABELS[k] || k}</span>
                </div>
              ))}
            </div>
          )}

          {/* Firma */}
          {reg.firma && (
            <div style={{marginBottom:20}}>
              <div style={{fontSize:10,fontWeight:700,color:'#64748B',textTransform:'uppercase',letterSpacing:'.09em',borderBottom:'2px solid #E2EBF3',paddingBottom:6,marginBottom:12}}>Firma del responsable</div>
              <div style={{border:'1px solid #E2EBF3',borderRadius:8,padding:8,background:'#F8FAFC',display:'inline-block'}}>
                <img src={reg.firma} alt="Firma" style={{display:'block',maxWidth:280,height:'auto',borderRadius:4}} />
              </div>
              <div style={{fontSize:11,color:'#64748B',marginTop:6}}>{c.c1?.nombre} — {c.c1?.relacion}</div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── PENDIENTES TAB ────────────────────────────────────────────
function PendientesTab({ onApprove }) {
  const [regs, setRegs] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [expanded, setExpanded] = React.useState(null);
  const [confirm, setConfirm] = React.useState(null);

  React.useEffect(() => {
    fetch('/api/registros.php')
      .then(r => r.json())
      .then(serverRegs => {
        setRegs(Array.isArray(serverRegs) ? serverRegs : []);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  const pending = regs.filter(r => r.status === 'pendiente');

  const approveReg = (reg) => {
    const players = window.TData.players;
    const newId = Math.max(0, ...players.map(p => p.id)) + 1;
    const words = reg.jugadora.nombre.trim().split(' ').filter(Boolean);
    const initials = words.map(w => w[0].toUpperCase()).join('').slice(0, 2);
    const num = parseInt(reg.jugadora.numero) || 0;
    const pos = reg.jugadora.posicion || 'Base';
    const newPlayer = {
      id: newId, name: reg.jugadora.nombre, num, pos, initials,
      hand: 'Derecha', color: '#FF6B9D', attendancePct: 100,
    };
    const updPlayers = [...players, newPlayer];
    syncRoster(updPlayers);

    // Save contact data
    const parents = [reg.contactos.c1, reg.contactos.c2].filter(Boolean).map(c => ({
      name: c.nombre, rel: c.relacion, phone: c.tel, email: c.email || '',
    }));
    const contact = {
      dob:       reg.jugadora.fechaNac,
      school:    reg.jugadora.escuela || '',
      blood:     reg.salud.tipoSangre,
      allergies: reg.salud.alergias || 'Ninguna',
      parents,
      emergency: { name: reg.contactos.emergencia.nombre, phone: reg.contactos.emergencia.tel },
      seguro:    reg.salud.seguro || '',
      medicamentos: reg.salud.medicamentos || '',
      condiciones:  reg.salud.condiciones || '',
      medico:    reg.salud.medico || '',
      telMedico: reg.salud.telMedico || '',
      curp:      reg.jugadora.curp || '',
      categoria: reg.jugadora.categoria || '',
      firma: reg.firma,
      autorizaciones: reg.autorizaciones,
    };
    // Transfer photo server-side if present
    if (reg.foto) {
      fetch('/api/photos.php', {
        method: 'POST', headers: {'Content-Type':'application/json'},
        body: JSON.stringify({ adminKey: 'TormPortal2026', playerId: newId, photo: reg.foto }),
      }).catch(() => {});
    }

    // Update server
    fetch('/api/registros.php?action=update', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: reg.id, status: 'aprobada', playerId: newId }),
    }).catch(() => {});

    setRegs(prev => prev.map(r => r.id === reg.id ? { ...r, status: 'aprobada', playerId: newId } : r));
    setConfirm(null);
    setExpanded(null);
    onApprove && onApprove();
  };

  const rejectReg = (regId) => {
    fetch('/api/registros.php?action=update', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: regId, status: 'rechazado' }),
    }).catch(() => {});
    setRegs(prev => prev.map(r => r.id === regId ? { ...r, status: 'rechazado' } : r));
    setExpanded(null);
    onApprove && onApprove();
  };

  if (loading) return (
    <div style={{ textAlign:'center', padding:'60px 20px', color:T.muted }}>
      <div style={{ fontSize:13 }}>Cargando registros...</div>
    </div>
  );

  if (pending.length === 0) return (
    <div style={{ textAlign:'center', padding:'60px 20px', color:T.muted }}>
      <div style={{ fontSize:40, marginBottom:12, opacity:.4 }}>✓</div>
      <div style={{ fontSize:15, fontWeight:700, color:T.text }}>Sin registros pendientes</div>
      <div style={{ fontSize:13, marginTop:6 }}>Los registros del formulario publico apareceran aqui.</div>
      <div style={{ fontSize:11, marginTop:16, padding:'10px 16px', background:T.stripe, borderRadius:8, display:'inline-block' }}>
        URL del formulario: <strong>tormentas.muga.com.mx/registro.html</strong>
      </div>
    </div>
  );

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
      <div style={{ fontSize:13, color:T.muted, marginBottom:4 }}>{pending.length} registro{pending.length !== 1 ? 's' : ''} esperando revision</div>

      {pending.map(reg => {
        const isOpen = expanded === reg.id;
        const photo = reg.foto || null;
        return (
          <PCard key={reg.id} style={{ padding:0, overflow:'hidden' }}>
            {/* Row */}
            <div onClick={() => setExpanded(isOpen ? null : reg.id)} style={{
              display:'flex', alignItems:'center', gap:14, padding:'14px 20px',
              cursor:'pointer', background:isOpen?T.accentLt:'#fff', transition:'background .15s'
            }}>
              {photo
                ? <img src={photo} alt="" style={{ width:38, height:38, borderRadius:'50%', objectFit:'cover', flexShrink:0 }} />
                : <PAvatar initials={reg.jugadora.nombre.split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase()} color={T.accent} size={38} />
              }
              <div style={{ flex:1 }}>
                <div style={{ fontWeight:700, fontSize:14, color:T.text }}>{reg.jugadora.nombre}</div>
                <div style={{ fontSize:12, color:T.muted, marginTop:2 }}>
                  {reg.jugadora.categoria} &nbsp;·&nbsp; Registrado {reg.fecha} &nbsp;·&nbsp; {reg.contactos.c1.tel}
                </div>
              </div>
              <span style={{
                fontSize:11, fontWeight:700, color:T.yellow, background:T.yellowLt,
                padding:'3px 10px', borderRadius:4, border:`1px solid #fde68a`, marginRight:8
              }}>Pendiente</span>
              <span style={{ color:T.muted, fontSize:12 }}>{isOpen ? '▲' : '▼'}</span>
            </div>

            {/* Detail */}
            {isOpen && (
              <div style={{ borderTop:`1px solid ${T.border}`, background:'#fafbfd', padding:'20px' }}>
                <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:20, marginBottom:20 }}>

                  {/* Datos jugadora */}
                  <div>
                    <PLabel>Datos de la jugadora</PLabel>
                    {[
                      ['Nombre completo', reg.jugadora.nombre],
                      ['Fecha de nac.',   reg.jugadora.fechaNac],
                      ['Categoria',       reg.jugadora.categoria],
                      ['Escuela',         reg.jugadora.escuela || '—'],
                      ['Posicion',        reg.jugadora.posicion || '—'],
                      ['No. jersey',      reg.jugadora.numero || '—'],
                      ['CURP',            reg.jugadora.curp || '—'],
                    ].map(([l,v]) => (
                      <div key={l} style={{ display:'flex', justifyContent:'space-between', marginBottom:8 }}>
                        <span style={{ fontSize:12, color:T.muted }}>{l}</span>
                        <span style={{ fontSize:12, fontWeight:600, color:T.text }}>{v}</span>
                      </div>
                    ))}
                    <PDivider />
                    <PLabel>Salud</PLabel>
                    {[
                      ['Tipo de sangre', reg.salud.tipoSangre],
                      ['Seguro',         reg.salud.seguro || '—'],
                      ['Alergias',       reg.salud.alergias || '—'],
                      ['Medicamentos',   reg.salud.medicamentos || '—'],
                      ['Condiciones',    reg.salud.condiciones || '—'],
                    ].map(([l,v]) => (
                      <div key={l} style={{ display:'flex', justifyContent:'space-between', marginBottom:8 }}>
                        <span style={{ fontSize:12, color:T.muted }}>{l}</span>
                        <span style={{ fontSize:12, fontWeight:600, color:T.text, maxWidth:'60%', textAlign:'right' }}>{v}</span>
                      </div>
                    ))}
                  </div>

                  {/* Contactos */}
                  <div>
                    <PLabel>Padres / tutores</PLabel>
                    {[reg.contactos.c1, reg.contactos.c2].filter(Boolean).map((c, i) => (
                      <div key={i} style={{ padding:'10px 12px', background:'#fff', borderRadius:6, border:`1px solid ${T.border}`, marginBottom:10 }}>
                        <div style={{ fontWeight:700, fontSize:13, color:T.text }}>{c.nombre} <span style={{ fontWeight:400, color:T.muted, fontSize:11 }}>({c.relacion})</span></div>
                        <div style={{ fontSize:12, color:T.muted, marginTop:4 }}>{c.tel}</div>
                        {c.email && <div style={{ fontSize:12, color:T.muted }}>{c.email}</div>}
                      </div>
                    ))}
                    <PLabel style={{ marginTop:12 }}>Emergencia</PLabel>
                    <div style={{ padding:'10px 12px', background:'#fff', borderRadius:6, border:`1px solid ${T.border}` }}>
                      <div style={{ fontWeight:700, fontSize:13, color:T.text }}>{reg.contactos.emergencia.nombre}</div>
                      <div style={{ fontSize:15, fontWeight:800, color:T.accent, marginTop:4 }}>{reg.contactos.emergencia.tel}</div>
                    </div>
                    <PDivider />
                    <PLabel>Autorizaciones</PLabel>
                    {[
                      ['Datos personales', reg.autorizaciones.datos],
                      ['Uso de imagen',    reg.autorizaciones.imagen],
                      ['Atencion medica',  reg.autorizaciones.medica],
                    ].map(([l,v]) => (
                      <div key={l} style={{ display:'flex', justifyContent:'space-between', marginBottom:6 }}>
                        <span style={{ fontSize:12, color:T.muted }}>{l}</span>
                        <span style={{ fontSize:11, fontWeight:700, color:v?T.green:T.red }}>{v?'Autorizado':'No autorizado'}</span>
                      </div>
                    ))}
                  </div>

                  {/* Firma + foto */}
                  <div>
                    <PLabel>Fotografia</PLabel>
                    {photo
                      ? <img src={photo} alt="" style={{ width:'100%', maxWidth:120, borderRadius:8, marginBottom:16 }} />
                      : <div style={{ fontSize:12, color:T.muted, marginBottom:16 }}>Sin fotografia</div>
                    }
                    <PLabel>Firma digital</PLabel>
                    <div style={{ border:`1px solid ${T.border}`, borderRadius:8, overflow:'hidden', marginBottom:8 }}>
                      <img src={reg.firma.imagen} alt="Firma" style={{ width:'100%', display:'block', background:'#fff' }} />
                    </div>
                    <div style={{ fontSize:12, color:T.muted }}>
                      Firmado por: <strong style={{ color:T.text }}>{reg.firma.nombre}</strong>
                    </div>
                  </div>
                </div>

                {/* Actions */}
                <div style={{ display:'flex', gap:10, paddingTop:16, borderTop:`1px solid ${T.border}` }}>
                  <button onClick={() => setConfirm(reg)} style={{
                    padding:'10px 24px', borderRadius:8, border:'none', cursor:'pointer',
                    background:'#2563eb', color:'#fff', fontWeight:700, fontSize:13, fontFamily:'inherit'
                  }}>Aprobar y agregar al roster</button>
                  <button onClick={() => rejectReg(reg.id)} style={{
                    padding:'10px 18px', borderRadius:8, border:`1px solid ${T.border}`,
                    cursor:'pointer', background:'#fff', color:T.muted, fontWeight:600, fontSize:13, fontFamily:'inherit'
                  }}>Rechazar</button>
                </div>
              </div>
            )}
          </PCard>
        );
      })}

      {/* Confirm modal */}
      {confirm && (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:300, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}>
          <div style={{ background:'#fff', borderRadius:16, padding:32, width:'min(380px,100%)', textAlign:'center' }}>
            <div style={{ fontSize:36, marginBottom:12 }}>✓</div>
            <h3 style={{ margin:'0 0 8px', fontSize:17, fontWeight:700, color:T.text }}>Aprobar registro</h3>
            <p style={{ margin:'0 0 24px', fontSize:13, color:T.muted }}>
              Se agregara a <strong>{confirm.jugadora.nombre}</strong> al roster del equipo y sus datos de contacto quedaran guardados.
            </p>
            <div style={{ display:'flex', gap:10 }}>
              <button onClick={() => approveReg(confirm)} style={{
                flex:1, padding:'12px', borderRadius:8, border:'none', cursor:'pointer',
                background:'#2563eb', color:'#fff', fontWeight:700, fontSize:13, fontFamily:'inherit'
              }}>Confirmar</button>
              <button onClick={() => setConfirm(null)} style={{
                flex:1, padding:'12px', borderRadius:8, border:`1px solid ${T.border}`,
                cursor:'pointer', background:'#fff', color:T.muted, fontWeight:600, fontSize:13, fontFamily:'inherit'
              }}>Cancelar</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.AdminJugadoras = AdminJugadoras;

// ── SPRINT CRONOMETRO ─────────────────────────────────────────
function SprintCronometro({ history, onSave }) {
  const DISTS = [10, 20, 30, 40, 60];
  const [metros,    setMetros]    = React.useState(20);
  const [running,   setRunning]   = React.useState(false);
  const [tiempo,    setTiempo]    = React.useState(0);
  const [justSaved, setJustSaved] = React.useState(false);
  const intervalRef = React.useRef(null);
  const startRef    = React.useRef(null);

  React.useEffect(() => () => clearInterval(intervalRef.current), []);

  const start = () => {
    if (running) return;
    startRef.current = Date.now() - tiempo * 10;
    intervalRef.current = setInterval(() => {
      setTiempo(Math.round((Date.now() - startRef.current) / 10));
    }, 50);
    setRunning(true);
  };
  const stop  = () => { clearInterval(intervalRef.current); setRunning(false); };
  const reset = () => { clearInterval(intervalRef.current); setRunning(false); setTiempo(0); setJustSaved(false); };
  const guardar = () => {
    const seg = (tiempo / 100).toFixed(2);
    onSave({ metros, seg });
    setJustSaved(true);
    setTimeout(() => { reset(); }, 1800);
  };
  const fmt = (cs) => `${Math.floor(cs/100)}.${String(cs%100).padStart(2,'0')}`;
  const best = history.length ? history.reduce((b,r) => parseFloat(r.seg) < parseFloat(b.seg) ? r : b) : null;

  return (
    <div style={{background:'#F0F9FF',border:'2px solid #BAE6FD',borderRadius:14,padding:20}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:14}}>
        <div style={{fontSize:12,fontWeight:700,color:'#0369A1',textTransform:'uppercase',letterSpacing:'.07em'}}>Cronometro Sprint</div>
        {best && <div style={{fontSize:11,color:'#0369A1',background:'#E0F2FE',padding:'3px 10px',borderRadius:99,fontWeight:700}}>Mejor: {best.seg}s · {best.metros}m</div>}
      </div>
      {/* Distance */}
      <div style={{display:'flex',gap:6,marginBottom:16}}>
        {DISTS.map(d => (
          <button key={d} onClick={()=>{if(!running){setMetros(d);setTiempo(0);setJustSaved(false);}}} style={{
            flex:1,padding:'7px 0',borderRadius:7,border:'none',
            cursor:running?'default':'pointer',fontWeight:700,fontSize:12,fontFamily:'inherit',
            background:metros===d?'#0369A1':'#E0F2FE',color:metros===d?'#fff':'#0369A1',
            opacity:running&&metros!==d?0.4:1,transition:'all .12s',
          }}>{d}m</button>
        ))}
      </div>
      {/* Timer */}
      <div style={{textAlign:'center',marginBottom:16}}>
        <div style={{fontFamily:"'Bebas Neue',Impact,monospace",fontSize:58,color:justSaved?'#16A34A':running?'#0369A1':'#0f172a',letterSpacing:'.03em',lineHeight:1,transition:'color .15s'}}>
          {fmt(tiempo)}
        </div>
        <div style={{fontSize:11,color:'#64748B',marginTop:4}}>seg · Sprint {metros}m</div>
      </div>
      {/* Controls */}
      <div style={{display:'flex',gap:8}}>
        {!running
          ? <button onClick={start} style={{flex:2,padding:'11px',background:'#0369A1',color:'#fff',border:'none',borderRadius:8,fontWeight:700,fontSize:13,cursor:'pointer',fontFamily:'inherit'}}>▶ Iniciar</button>
          : <button onClick={stop}  style={{flex:2,padding:'11px',background:'#DC2626',color:'#fff',border:'none',borderRadius:8,fontWeight:700,fontSize:13,cursor:'pointer',fontFamily:'inherit'}}>■ Detener</button>
        }
        {tiempo > 0 && !running && !justSaved && (
          <button onClick={guardar} style={{flex:2,padding:'11px',background:'#16A34A',color:'#fff',border:'none',borderRadius:8,fontWeight:700,fontSize:13,cursor:'pointer',fontFamily:'inherit'}}>
            ✓ Guardar {(tiempo/100).toFixed(2)}s
          </button>
        )}
        {justSaved && <div style={{flex:2,padding:'11px',background:'#DCFCE7',borderRadius:8,fontSize:13,fontWeight:700,color:'#16A34A',textAlign:'center'}}>✓ Guardado</div>}
        <button onClick={reset} style={{flex:1,padding:'11px',background:'#F1F5F9',border:`1px solid ${T.border}`,borderRadius:8,fontWeight:600,fontSize:12,cursor:'pointer',fontFamily:'inherit',color:T.muted}}>Reset</button>
      </div>
      {/* History */}
      {history.length > 0 && (
        <div style={{marginTop:16,borderTop:`1px solid #BAE6FD`,paddingTop:12}}>
          <div style={{fontSize:10,fontWeight:700,color:'#0369A1',textTransform:'uppercase',letterSpacing:'.07em',marginBottom:8}}>Historial</div>
          <div style={{display:'flex',flexDirection:'column',gap:6}}>
            {history.slice(0,6).map((r,i) => (
              <div key={r.id||i} style={{display:'flex',alignItems:'center',gap:10,padding:'6px 10px',background:'#fff',borderRadius:8,border:'1px solid #BAE6FD'}}>
                <span style={{fontFamily:"'Bebas Neue',Impact,sans-serif",fontSize:20,color:'#0369A1',lineHeight:1,minWidth:48}}>{r.seg}s</span>
                <span style={{fontSize:11,fontWeight:600,color:T.text}}>{r.metros}m</span>
                <span style={{fontSize:11,color:T.muted,marginLeft:'auto'}}>{r.fecha} {r.hora}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ── SALTO DE CUERDA ───────────────────────────────────────────
function SaltoCuerda({ history, onSave }) {
  const DURAS = [30, 45, 60, 90, 120];
  const [duracion, setDuracion] = React.useState(60);
  const [phase,    setPhase]    = React.useState('idle');
  const [remaining,setRemaining]= React.useState(60);
  const [saltos,   setSaltos]   = React.useState(0);
  const [tapAnim,  setTapAnim]  = React.useState(false);
  const [justSaved,setJustSaved]= React.useState(false);
  const intervalRef = React.useRef(null);
  React.useEffect(() => () => clearInterval(intervalRef.current), []);

  const start = () => {
    setRemaining(duracion); setSaltos(0); setPhase('running'); setJustSaved(false);
    intervalRef.current = setInterval(() => {
      setRemaining(r => {
        if (r <= 1) { clearInterval(intervalRef.current); setPhase('done'); return 0; }
        return r - 1;
      });
    }, 1000);
  };
  const stop  = () => { clearInterval(intervalRef.current); setPhase('done'); };
  const reset = () => { clearInterval(intervalRef.current); setPhase('idle'); setRemaining(duracion); setSaltos(0); setJustSaved(false); };
  const tap   = () => {
    if (phase !== 'running') return;
    setSaltos(s => s + 1);
    setTapAnim(true);
    setTimeout(() => setTapAnim(false), 100);
  };
  const guardar = () => {
    const durReal = phase === 'done' ? duracion - remaining : duracion;
    onSave({ duracion: durReal, saltos });
    setJustSaved(true);
    setTimeout(() => { reset(); setJustSaved(false); }, 1800);
  };
  const fmtTime = s => `${Math.floor(s/60)}:${String(s%60).padStart(2,'0')}`;
  const pct     = duracion > 0 ? Math.round((1 - remaining/duracion) * 100) : 0;
  const best    = history.length ? Math.max(...history.map(h => h.saltos)) : null;

  return (
    <div style={{background:'#F0FDF4',border:'2px solid #BBF7D0',borderRadius:14,padding:20}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14}}>
        <div style={{fontSize:12,fontWeight:700,color:'#15803D',textTransform:'uppercase',letterSpacing:'.07em'}}>Salto de Cuerda</div>
        {best !== null && (
          <div style={{fontSize:11,fontWeight:700,color:'#15803D',background:'#DCFCE7',padding:'3px 10px',borderRadius:20,border:'1px solid #BBF7D0'}}>
            Mejor: {best} saltos
          </div>
        )}
      </div>
      {/* Duration selector */}
      <div style={{display:'flex',gap:6,marginBottom:16}}>
        {DURAS.map(d => (
          <button key={d} onClick={()=>{if(phase==='idle'){setDuracion(d);setRemaining(d);}}} style={{
            flex:1,padding:'7px 0',borderRadius:7,border:'none',
            cursor:phase!=='idle'?'default':'pointer',fontWeight:700,fontSize:11,fontFamily:'inherit',
            background:duracion===d?'#15803D':'#DCFCE7',color:duracion===d?'#fff':'#15803D',
            opacity:phase!=='idle'&&duracion!==d?0.4:1,
          }}>{d}s</button>
        ))}
      </div>
      {/* Timer + tap */}
      <div style={{display:'flex',gap:12,marginBottom:14}}>
        <div style={{flex:1,textAlign:'center',background:'#fff',borderRadius:12,padding:'16px 10px',border:'1px solid #BBF7D0'}}>
          <div style={{fontFamily:"'Bebas Neue',Impact,monospace",fontSize:48,color:phase==='running'?'#15803D':phase==='done'?'#DC2626':'#0f172a',lineHeight:1}}>
            {fmtTime(remaining)}
          </div>
          <div style={{fontSize:11,color:'#64748B',marginTop:4}}>tiempo restante</div>
          <div style={{height:4,background:'#E2EBF3',borderRadius:4,marginTop:10,overflow:'hidden'}}>
            <div style={{height:'100%',background:'#15803D',borderRadius:4,width:`${pct}%`,transition:'width .8s linear'}} />
          </div>
        </div>
        <div onClick={tap} style={{
          width:96,flexShrink:0,background:phase==='running'?(tapAnim?'#166534':'#15803D'):'#f8fafc',
          borderRadius:12,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',
          cursor:phase==='running'?'pointer':'default',
          border:`2px solid ${phase==='running'?'#15803D':'#E2EBF3'}`,
          userSelect:'none',WebkitTapHighlightColor:'transparent',
          transform:tapAnim?'scale(0.93)':'scale(1)',transition:'all .08s',
        }}>
          <div style={{fontSize:42,fontWeight:900,color:phase==='running'?'#fff':'#64748B',lineHeight:1}}>{saltos}</div>
          <div style={{fontSize:11,color:phase==='running'?'rgba(255,255,255,.7)':'#64748B',marginTop:4,fontWeight:700}}>
            {phase==='running'?'TAP':'saltos'}
          </div>
        </div>
      </div>
      {/* Controls */}
      <div style={{display:'flex',gap:8,marginBottom:12}}>
        {phase==='idle' && <button onClick={start} style={{flex:2,padding:'11px',background:'#15803D',color:'#fff',border:'none',borderRadius:8,fontWeight:700,fontSize:13,cursor:'pointer',fontFamily:'inherit'}}>▶ Iniciar</button>}
        {phase==='running' && <button onClick={stop} style={{flex:2,padding:'11px',background:'#DC2626',color:'#fff',border:'none',borderRadius:8,fontWeight:700,fontSize:13,cursor:'pointer',fontFamily:'inherit'}}>■ Detener</button>}
        {phase==='done' && (
          <button onClick={guardar} disabled={justSaved} style={{flex:2,padding:'11px',background:justSaved?'#16A34A':'#15803D',color:'#fff',border:'none',borderRadius:8,fontWeight:700,fontSize:13,cursor:justSaved?'default':'pointer',fontFamily:'inherit'}}>
            {justSaved ? `✓ Guardado` : `Guardar ${saltos} saltos`}
          </button>
        )}
        <button onClick={reset} style={{flex:1,padding:'11px',background:'#F1F5F9',border:`1px solid ${T.border}`,borderRadius:8,fontWeight:600,fontSize:12,cursor:'pointer',fontFamily:'inherit',color:T.muted}}>Reset</button>
      </div>
      {/* History */}
      {history.length > 0 && (
        <div style={{marginTop:12,display:'flex',flexDirection:'column',gap:5}}>
          <div style={{fontSize:11,fontWeight:700,color:'#15803D',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:4}}>Historial</div>
          {history.slice(0,6).map(h => (
            <div key={h.id} style={{padding:'6px 12px',background:'#fff',borderRadius:8,border:'1px solid #BBF7D0',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
              <span style={{fontSize:11,color:T.muted}}>{h.fecha} {h.hora}</span>
              <span style={{fontSize:13,fontWeight:700,color:'#15803D'}}>{h.saltos} saltos · {h.duracion}s</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── TIROS DE 3 ────────────────────────────────────────────────
function Tiros3({ history, onSave }) {
  const OPTS = [5, 10, 15, 20, 25];
  const [total,     setTotal]    = React.useState(10);
  const [shots,     setShots]    = React.useState([]);
  const [anotados,  setAnotados] = React.useState(0);
  const [justSaved, setJustSaved]= React.useState(false);

  const reset = () => { setShots([]); setAnotados(0); setJustSaved(false); };
  const tiro = (made) => {
    if (shots.length >= total) return;
    setShots(s => [...s, made]);
    if (made) setAnotados(a => a + 1);
  };
  const done = shots.length >= total;
  const pct  = shots.length > 0 ? Math.round(anotados/shots.length*100) : 0;
  const guardar = () => {
    onSave({ intentos: shots.length, anotados, total });
    setJustSaved(true);
    setTimeout(() => { reset(); }, 1800);
  };
  const bestPct = history.length ? Math.max(...history.map(h => h.intentos > 0 ? Math.round(h.anotados/h.intentos*100) : 0)) : null;

  return (
    <div style={{background:'#FFF7ED',border:'2px solid #FED7AA',borderRadius:14,padding:20}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14}}>
        <div style={{fontSize:12,fontWeight:700,color:'#C2410C',textTransform:'uppercase',letterSpacing:'.07em'}}>Tiros de 3 Puntos</div>
        {bestPct !== null && (
          <div style={{fontSize:11,fontWeight:700,color:'#C2410C',background:'#FED7AA',padding:'3px 10px',borderRadius:20,border:'1px solid #FDBA74'}}>
            Mejor: {bestPct}%
          </div>
        )}
      </div>
      {/* Intentos selector */}
      <div style={{display:'flex',gap:6,marginBottom:14}}>
        {OPTS.map(n => (
          <button key={n} onClick={()=>{if(!shots.length)setTotal(n);}} style={{
            flex:1,padding:'7px 0',borderRadius:7,border:'none',
            cursor:shots.length?'default':'pointer',fontWeight:700,fontSize:12,fontFamily:'inherit',
            background:total===n?'#C2410C':'#FED7AA',color:total===n?'#fff':'#C2410C',
            opacity:shots.length&&total!==n?0.4:1,
          }}>{n}</button>
        ))}
      </div>
      {/* Shot bubbles */}
      <div style={{display:'flex',flexWrap:'wrap',gap:8,marginBottom:14,padding:'12px',background:'#fff',borderRadius:10,border:'1px solid #FED7AA',minHeight:64}}>
        {Array.from({length:total}).map((_,i) => {
          const shot = shots[i];
          const isNext = i===shots.length;
          return (
            <div key={i} style={{
              width:36,height:36,borderRadius:'50%',display:'flex',alignItems:'center',justifyContent:'center',
              fontSize:14,fontWeight:900,flexShrink:0,transition:'all .12s',
              background:shot===true?'#15803D':shot===false?'#DC2626':isNext?'#FFF7ED':'#F8FAFC',
              border:`2px solid ${shot===true?'#15803D':shot===false?'#DC2626':isNext?'#C2410C':'#E2EBF3'}`,
              color:shot!==undefined?'#fff':isNext?'#C2410C':'#64748B',
            }}>
              {shot===true?'✓':shot===false?'✗':i+1}
            </div>
          );
        })}
      </div>
      {/* Score */}
      <div style={{textAlign:'center',marginBottom:14}}>
        <div style={{fontFamily:"'Bebas Neue',Impact,sans-serif",fontSize:52,color:pct>=50?'#15803D':'#C2410C',lineHeight:1}}>
          {anotados}<span style={{fontSize:28,opacity:.5}}>/{shots.length||total}</span>
        </div>
        {shots.length>0&&<div style={{fontSize:13,color:T.muted,marginTop:2}}>{pct}% efectividad</div>}
      </div>
      {/* Buttons */}
      {!done ? (
        <div style={{display:'flex',gap:8}}>
          <button onClick={()=>tiro(true)}  style={{flex:2,padding:'14px',background:'#15803D',color:'#fff',border:'none',borderRadius:10,fontWeight:800,fontSize:15,cursor:'pointer',fontFamily:'inherit'}}>✓ Anoto</button>
          <button onClick={()=>tiro(false)} style={{flex:2,padding:'14px',background:'#DC2626',color:'#fff',border:'none',borderRadius:10,fontWeight:800,fontSize:15,cursor:'pointer',fontFamily:'inherit'}}>✗ Fallo</button>
          <button onClick={reset}           style={{flex:1,padding:'14px',background:'#F1F5F9',border:`1px solid ${T.border}`,borderRadius:10,fontWeight:700,fontSize:14,cursor:'pointer',fontFamily:'inherit',color:T.muted}}>↩</button>
        </div>
      ) : (
        <div>
          <div style={{padding:'11px',background:'#DCFCE7',border:'1px solid #BBF7D0',borderRadius:8,textAlign:'center',marginBottom:10,fontSize:14,fontWeight:700,color:'#15803D'}}>
            Serie completa: {anotados} de {total} ({pct}%)
          </div>
          <div style={{display:'flex',gap:8}}>
            <button onClick={reset} style={{flex:1,padding:'9px',background:'#FFF7ED',border:'1px solid #FED7AA',borderRadius:8,fontWeight:700,fontSize:12,cursor:'pointer',fontFamily:'inherit',color:'#C2410C'}}>Nueva serie</button>
            <button onClick={guardar} disabled={justSaved} style={{flex:2,padding:'9px',background:justSaved?'#16A34A':'#C2410C',color:'#fff',border:'none',borderRadius:8,fontWeight:700,fontSize:12,cursor:justSaved?'default':'pointer',fontFamily:'inherit'}}>
              {justSaved ? '✓ Guardado' : `Guardar ${anotados}/${total}`}
            </button>
          </div>
        </div>
      )}
      {/* History */}
      {history.length > 0 && (
        <div style={{marginTop:12,display:'flex',flexDirection:'column',gap:5}}>
          <div style={{fontSize:11,fontWeight:700,color:'#C2410C',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:4}}>Historial</div>
          {history.slice(0,6).map(h => {
            const p = h.intentos>0?Math.round(h.anotados/h.intentos*100):0;
            return (
              <div key={h.id} style={{padding:'6px 12px',background:'#fff',borderRadius:8,border:'1px solid #FED7AA',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                <span style={{fontSize:11,color:T.muted}}>{h.fecha} {h.hora}</span>
                <span style={{fontSize:13,fontWeight:700,color:'#C2410C'}}>{h.anotados}/{h.intentos} · {p}%</span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ── FISICO (ADMIN) ────────────────────────────────────────────
function AdminFisico() {
  const { players } = window.TData;
  const { evalDates } = window.TDataExt;
  const [selPlayer, setSelPlayer] = React.useState(null);
  const [form,      setForm]      = React.useState(null);
  const [actTab,    setActTab]    = React.useState('sprint');
  const [actHistory, setActHistory] = React.useState({ sprint:[], cuerda:[], tiros3:[] });

  const loadHistory = (pid) => {
    fetch(`/api/fisico.php?playerId=${pid}`)
      .then(r => r.json())
      .then(d => setActHistory({ sprint: d.sprint||[], cuerda: d.cuerda||[], tiros3: d.tiros3||[] }))
      .catch(() => {});
  };

  const FIELDS = [
    { key:"altura",   label:"Altura (cm)",       step:1   },
    { key:"peso",     label:"Peso (kg)",          step:0.1 },
    { key:"grasa",    label:"Grasa corporal (%)", step:0.1 },
    { key:"musculo",  label:"Masa muscular (%)",  step:0.1 },
    { key:"sprint",   label:"Sprint 20m (seg)",   step:0.01},
    { key:"salto",    label:"Salto vertical (cm)",step:1   },
    { key:"agilidad", label:"Agilidad (seg)",      step:0.01},
    { key:"vo2",      label:"VO₂ estimado",        step:1   },
    { key:"fuerza",   label:"Fuerza agarre (kg)", step:0.5 },
  ];

  const openPlayer = (p) => {
    setSelPlayer(p);
    setActHistory({ sprint:[], cuerda:[], tiros3:[] });
    loadHistory(p.id);
    fetch('/api/physdata.php?playerId=' + p.id)
      .then(r => r.json())
      .then(rawArr => {
        if (Array.isArray(rawArr) && rawArr.length > 0) {
          setForm(rawArr.map(e => ({
            altura:e[0]||"", peso:e[1]||"", grasa:e[2]||"", musculo:e[3]||"",
            sprint:e[4]||"", salto:e[5]||"", agilidad:e[6]||"", vo2:e[7]||"", fuerza:e[8]||""
          })));
        } else {
          const pd = window.TDataExt.physicalData[p.id];
          setForm(evalDates.map((_, i) => {
            const e = pd ? pd[i] : null;
            return {
              altura:e?.altura||"", peso:e?.peso||"", grasa:e?.grasa||"", musculo:e?.musculo||"",
              sprint:e?.sprint||"", salto:e?.salto||"", agilidad:e?.agilidad||"", vo2:e?.vo2||"", fuerza:e?.fuerza||""
            };
          }));
        }
      })
      .catch(() => {
        const pd = window.TDataExt.physicalData[p.id];
        setForm(evalDates.map((_, i) => {
          const e = pd ? pd[i] : null;
          return {
            altura:e?.altura||"", peso:e?.peso||"", grasa:e?.grasa||"", musculo:e?.musculo||"",
            sprint:e?.sprint||"", salto:e?.salto||"", agilidad:e?.agilidad||"", vo2:e?.vo2||"", fuerza:e?.fuerza||""
          };
        }));
      });
  };

  const handleSave = () => {
    const rawArr = form.map(e => [
      +e.altura||0, +e.peso||0, +e.grasa||0, +e.musculo||0,
      +e.sprint||0, +e.salto||0, +e.agilidad||0, +e.vo2||0, +e.fuerza||0
    ]);
    fetch('/api/physdata.php', {
      method: 'POST', headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ adminKey: 'TormPortal2026', playerId: selPlayer.id, data: rawArr }),
    }).catch(() => {});
    // Update in memory so ProFisico reflects changes immediately
    const mapped = rawArr.map((e, i) => ({
      date:evalDates[i]||"", altura:e[0], peso:e[1], grasa:e[2], musculo:e[3],
      sprint:e[4], salto:e[5], agilidad:e[6], vo2:e[7], fuerza:e[8]
    }));
    const first = rawArr[0], last = rawArr[rawArr.length-1];
    mapped.delta = {
      peso:    +(last[1]-first[1]).toFixed(1),
      grasa:   +(last[2]-first[2]).toFixed(1),
      musculo: +(last[3]-first[3]).toFixed(1),
      sprint:  +(last[4]-first[4]).toFixed(2),
      salto:   +(last[5]-first[5]).toFixed(0),
      agilidad:+(last[6]-first[6]).toFixed(2),
      vo2:     +(last[7]-first[7]).toFixed(0),
    };
    mapped.latest = mapped[mapped.length-1];
    window.TDataExt.physicalData[selPlayer.id] = mapped;
    setSelPlayer(null);
    setForm(null);
  };

  const inputSt = {
    width:"100%", padding:"8px 10px", border:"1.5px solid #e2e8f0", borderRadius:6,
    fontSize:13, fontFamily:"inherit", outline:"none", color:"#0f172a", background:"#f8fafc",
    boxSizing:"border-box"
  };

  const saveActivity = (type, result) => {
    const now = new Date();
    const fecha = now.toLocaleDateString('es-MX', { day:'2-digit', month:'2-digit', year:'numeric' });
    const hora  = now.toLocaleTimeString('es-MX', { hour:'2-digit', minute:'2-digit' });
    const entry = { id: Date.now(), fecha, hora, ...result };
    setActHistory(prev => ({
      ...prev,
      [type]: [entry, ...prev[type]].slice(0, 100),
    }));
    fetch('/api/fisico.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ adminKey: 'TormPortal2026', playerId: selPlayer.id, type, result: entry }),
    }).catch(() => {});
  };

  if (selPlayer && form) {

    const ACT_TABS = [
      { id:'sprint',  label:'Sprint',        color:'#0369A1', bg:'#F0F9FF' },
      { id:'cuerda',  label:'Salto de Cuerda',color:'#15803D', bg:'#F0FDF4' },
      { id:'tiros3',  label:'Tiros de 3',    color:'#C2410C', bg:'#FFF7ED' },
      { id:'mediciones', label:'Mediciones', color:T.muted,   bg:T.stripe  },
    ];

    return (
      <div>
        <PBackBtn onClick={() => { setSelPlayer(null); setForm(null); }} label="Condición Física" />
        <div style={{ display:"flex", alignItems:"center", gap:14, marginBottom:20 }}>
          <PAvatar initials={selPlayer.initials} color={posColorsP[selPlayer.pos]||T.accent} size={44} />
          <div>
            <div style={{ fontSize:17, fontWeight:700, color:T.text }}>{selPlayer.name}</div>
            <div style={{ fontSize:12, color:T.muted }}>#{selPlayer.num} · {selPlayer.pos}</div>
          </div>
        </div>

        {/* Activity tabs */}
        <div style={{ display:"flex", gap:6, marginBottom:20, background:T.stripe, borderRadius:10, padding:4 }}>
          {ACT_TABS.map(t => (
            <button key={t.id} onClick={() => setActTab(t.id)} style={{
              flex:1, padding:"9px 6px", border:"none", cursor:"pointer", fontFamily:"inherit",
              background: actTab===t.id ? t.bg : "transparent",
              color: actTab===t.id ? t.color : T.muted,
              fontWeight: actTab===t.id ? 700 : 500,
              fontSize:12, borderRadius:7, transition:"all .12s",
              outline: actTab===t.id ? `1.5px solid ${t.color}30` : "none",
            }}>{t.label}</button>
          ))}
        </div>

        {/* Sprint tab */}
        {actTab === 'sprint' && (
          <SprintCronometro
            history={actHistory.sprint}
            onSave={result => saveActivity('sprint', result)}
          />
        )}

        {/* Salto de Cuerda tab */}
        {actTab === 'cuerda' && (
          <SaltoCuerda history={actHistory.cuerda} onSave={result => saveActivity('cuerda', result)} />
        )}

        {/* Tiros de 3 tab */}
        {actTab === 'tiros3' && (
          <Tiros3 history={actHistory.tiros3} onSave={result => saveActivity('tiros3', result)} />
        )}

        {/* Mediciones tab */}
        {actTab === 'mediciones' && (
          <>
            <div style={{ display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:16 }}>
              {evalDates.map((date, ei) => (
                <PCard key={date}>
                  <div style={{ fontSize:13, fontWeight:700, color:T.accent, marginBottom:14 }}>Evaluación · {date}</div>
                  {FIELDS.map(f => (
                    <div key={f.key} style={{ marginBottom:11 }}>
                      <label style={{ fontSize:11, fontWeight:600, color:T.muted, textTransform:"uppercase", letterSpacing:"0.06em", display:"block", marginBottom:4 }}>{f.label}</label>
                      <input
                        type="number" step={f.step} value={form[ei][f.key]}
                        onChange={e => setForm(prev => prev.map((row, i) => i===ei ? {...row, [f.key]:e.target.value} : row))}
                        style={inputSt}
                      />
                    </div>
                  ))}
                </PCard>
              ))}
            </div>
            <div style={{ marginTop:20, display:"flex", gap:10 }}>
              <button onClick={handleSave} style={{ padding:"10px 22px", borderRadius:8, border:"none", cursor:"pointer", fontWeight:700, fontSize:13, fontFamily:"inherit", color:"#fff", background:"#2563eb" }}>
                Guardar mediciones
              </button>
              <button onClick={() => { setSelPlayer(null); setForm(null); }} style={{ padding:"10px 22px", borderRadius:8, border:"none", cursor:"pointer", fontWeight:700, fontSize:13, fontFamily:"inherit", color:"#64748b", background:"#f1f5f9" }}>
                Cancelar
              </button>
            </div>
          </>
        )}
      </div>
    );
  }

  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 }}>Editar mediciones por jugadora · {evalDates.length} evaluaciones registradas</p>
      </div>
      <div style={{ background:"#fff", borderRadius:12, border:`1px solid ${T.border}`, overflow:"hidden" }}>
        {players.map((p, i) => {
          const hasData = !!window.TDataExt.physicalData[p.id];
          return (
            <div key={p.id} onClick={() => openPlayer(p)} style={{
              display:"flex", alignItems:"center", gap:14, padding:"14px 20px",
              borderBottom: i < players.length-1 ? `1px solid ${T.border}` : "none",
              cursor:"pointer", transition:"background 0.12s"
            }}
            onMouseEnter={e=>e.currentTarget.style.background=T.stripe}
            onMouseLeave={e=>e.currentTarget.style.background="#fff"}
            >
              <PAvatar initials={p.initials} color={posColorsP[p.pos]||T.accent} size={36} />
              <div style={{ flex:1 }}>
                <div style={{ fontSize:14, fontWeight:600, color:T.text }}>{p.name}</div>
                <div style={{ fontSize:12, color:T.muted, marginTop:2 }}>#{p.num} · {p.pos}</div>
              </div>
              <span style={{
                fontSize:11, fontWeight:700, padding:"3px 10px", borderRadius:4,
                color:hasData?T.green:T.red,
                background:hasData?T.greenLt:T.redLt,
                border:`1px solid ${hasData?"#bbf7d0":"#fecaca"}`
              }}>{hasData ? "Con datos" : "Sin datos"}</span>
              <span style={{ color:T.muted, fontSize:16 }}>›</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}
window.AdminFisico = AdminFisico;

// ── ADMIN PARTIDOS (GESTION) ──────────────────────────────────
function AdminPartidos() {
  const today = new Date().toISOString().split("T")[0];
  const [games,   setGames]   = React.useState(() => window.TData.games || []);
  const [loading, setLoading] = React.useState(true);
  const [adding,  setAdding]  = React.useState(false);
  const [form,    setForm]    = React.useState({ rival:'', date:today, home:true, scoreUs:'', scoreThem:'' });
  const [delId,   setDelId]   = React.useState(null);

  React.useEffect(() => {
    fetch('/api/partidos.php').then(r => r.json()).then(data => {
      if (data.games) {
        const g = data.games;
        setGames(g);
        window.TData.games = g;
        if (data.rawStats) {
          window.TData.rawStats = data.rawStats;
        }
      }
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  function syncGames(updGames, updRaw) {
    const rawStats = updRaw || window.TData.rawStats || {};
    setGames(updGames);
    window.TData.games = updGames;
    if (updRaw) {
      window.TData.rawStats = updRaw;
    }
    fetch('/api/partidos.php', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ adminKey:'TormPortal2026', games:updGames, rawStats }),
    }).catch(() => {});
  }

  function addGame() {
    if (!form.rival.trim() || form.scoreUs === '' || form.scoreThem === '') return;
    const us   = parseInt(form.scoreUs)   || 0;
    const them = parseInt(form.scoreThem) || 0;
    const result = us > them ? 'W' : us < them ? 'L' : 'E';
    const id = Math.max(0, ...games.map(g => g.id), 0) + 1;
    const newGame = { id, date:form.date, rival:form.rival.trim(), result, scoreUs:us, scoreThem:them, location:form.home?'Local':'Visita' };
    syncGames([...games, newGame]);
    setAdding(false);
    setForm({ rival:'', date:today, home:true, scoreUs:'', scoreThem:'' });
  }

  function deleteGame(id) {
    const updGames = games.filter(g => g.id !== id);
    const raw = {...(window.TData.rawStats || {})};
    delete raw[id];
    syncGames(updGames, raw);
    setDelId(null);
  }

  const wins   = games.filter(g => g.result === 'W').length;
  const losses = games.filter(g => g.result === 'L').length;
  const avgPts = games.length ? (games.reduce((s,g) => s+(g.scoreUs||0), 0)/games.length).toFixed(1) : '—';
  const avgCon = games.length ? (games.reduce((s,g) => s+(g.scoreThem||0), 0)/games.length).toFixed(1) : '—';

  const inputSt = {
    width:'100%', padding:'10px 12px', border:`1.5px solid ${T.border}`, borderRadius:8,
    fontSize:13, fontFamily:'inherit', color:T.text, outline:'none', background:'#f8fafc', boxSizing:'border-box',
  };
  const btnSt = (c, bg, bd) => ({ padding:'10px 18px', borderRadius:8, border:`1px solid ${bd||bg}`, cursor:'pointer', fontWeight:700, fontSize:13, fontFamily:'inherit', color:c, background:bg });

  return (
    <div>
      <div style={{display:'flex',alignItems:'flex-start',justifyContent:'space-between',flexWrap:'wrap',gap:12,marginBottom:24}}>
        <div>
          <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}}>Historial de partidos de la temporada</p>
        </div>
        <button onClick={()=>setAdding(true)} style={{...btnSt('#fff',T.accent),padding:'9px 18px'}}>+ Agregar partido</button>
      </div>

      {/* KPIs */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:12,marginBottom:20}}>
        <PKPICard label="Partidos jugados" value={games.length}  color={T.text} />
        <PKPICard label="Victorias"        value={wins}          color={T.green}  sub={games.length?`${Math.round(wins/games.length*100)}%`:''} />
        <PKPICard label="Derrotas"         value={losses}        color={losses>wins?T.red:T.muted} />
        <PKPICard label="Pts / partido"    value={avgPts}        color={T.accent} sub={`Contra: ${avgCon}`} />
      </div>

      {loading ? (
        <div style={{textAlign:'center',padding:'60px 20px',color:T.muted,fontSize:13}}>Cargando partidos...</div>
      ) : games.length === 0 ? (
        <div style={{textAlign:'center',padding:'60px 20px',color:T.muted}}>
          <div style={{fontSize:40,marginBottom:12,opacity:.3}}>🏀</div>
          <div style={{fontSize:15,fontWeight:700,color:T.text}}>Sin partidos registrados</div>
          <div style={{fontSize:13,marginTop:6}}>Agrega un partido manualmente o usa el Anotador en vivo.</div>
        </div>
      ) : (
        <PCard padding="0">
          {[...games].reverse().map((g, i) => {
            const isW = g.result === 'W', isL = g.result === 'L';
            const rc  = isW ? T.green  : isL ? T.red  : T.muted;
            const rbg = isW ? T.greenLt: isL ? T.redLt: T.stripe;
            const rl  = isW ? 'Victoria' : isL ? 'Derrota' : 'Empate';
            return (
              <div key={g.id} style={{display:'flex',alignItems:'center',gap:14,padding:'14px 20px',borderTop:i===0?'none':`1px solid ${T.border}`}}>
                <div style={{width:40,height:40,borderRadius:8,background:rbg,display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0,fontSize:14,fontWeight:900,color:rc,fontFamily:"'Bebas Neue',Impact,sans-serif",letterSpacing:'.02em'}}>
                  {g.result||'?'}
                </div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontWeight:600,fontSize:14,color:T.text}}>{g.rival}</div>
                  <div style={{fontSize:12,color:T.muted,marginTop:2,display:'flex',gap:6,flexWrap:'wrap'}}>
                    <span>{g.date}</span>
                    <span>·</span>
                    <span style={{color:rc,fontWeight:700}}>{rl}</span>
                    <span>·</span>
                    <span>{g.location||'Local'}</span>
                  </div>
                </div>
                <div style={{textAlign:'center',flexShrink:0,paddingRight:8}}>
                  <div style={{fontFamily:"'Bebas Neue',Impact,sans-serif",fontSize:24,letterSpacing:'.05em',color:T.text,lineHeight:1}}>{g.scoreUs} - {g.scoreThem}</div>
                  <div style={{fontSize:10,color:T.muted}}>Tormentas vs Rival</div>
                </div>
                <button onClick={()=>setDelId(g.id)} style={{padding:'6px 10px',background:'#FEF2F2',border:'1px solid #FECACA',borderRadius:7,fontWeight:600,fontSize:11,cursor:'pointer',fontFamily:'inherit',color:'#DC2626',flexShrink:0}}>×</button>
              </div>
            );
          })}
        </PCard>
      )}

      {/* Add modal */}
      {adding && (
        <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.5)',zIndex:300,display:'flex',alignItems:'center',justifyContent:'center',padding:16}}>
          <div style={{background:'#fff',borderRadius:14,padding:28,width:'min(440px,100%)',boxShadow:'0 24px 60px #00000040'}}>
            <div style={{fontSize:16,fontWeight:700,color:T.text,marginBottom:20}}>Agregar partido</div>
            <div style={{marginBottom:14}}>
              <label style={{display:'block',fontSize:10,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.06em',marginBottom:5}}>Rival</label>
              <input value={form.rival} onChange={e=>setForm(f=>({...f,rival:e.target.value}))} placeholder="Nombre del equipo rival" style={inputSt} />
            </div>
            <div style={{marginBottom:14}}>
              <label style={{display:'block',fontSize:10,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.06em',marginBottom:5}}>Fecha</label>
              <input type="date" value={form.date} onChange={e=>setForm(f=>({...f,date:e.target.value}))} style={inputSt} />
            </div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginBottom:14}}>
              <div>
                <label style={{display:'block',fontSize:10,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.06em',marginBottom:5}}>Tormentas</label>
                <input type="number" min="0" value={form.scoreUs} onChange={e=>setForm(f=>({...f,scoreUs:e.target.value}))} placeholder="0" style={inputSt} />
              </div>
              <div>
                <label style={{display:'block',fontSize:10,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.06em',marginBottom:5}}>Rival</label>
                <input type="number" min="0" value={form.scoreThem} onChange={e=>setForm(f=>({...f,scoreThem:e.target.value}))} placeholder="0" style={inputSt} />
              </div>
            </div>
            <div style={{marginBottom:22}}>
              <label style={{display:'block',fontSize:10,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.06em',marginBottom:8}}>Sede</label>
              <div style={{display:'flex',gap:8}}>
                {[{l:'Local',v:true},{l:'Visita',v:false}].map(o => (
                  <button key={String(o.v)} onClick={()=>setForm(f=>({...f,home:o.v}))} style={{
                    flex:1, padding:'9px', borderRadius:8,
                    border:`1.5px solid ${form.home===o.v?T.accent:T.border}`,
                    background:form.home===o.v?T.accentLt:'#fff',
                    color:form.home===o.v?T.accent:T.muted,
                    fontWeight:700, fontSize:13, cursor:'pointer', fontFamily:'inherit'
                  }}>{o.l}</button>
                ))}
              </div>
            </div>
            <div style={{display:'flex',gap:10}}>
              <button onClick={()=>setAdding(false)} style={{...btnSt(T.muted,'#f8fafc',T.border),flex:1,padding:'11px'}}>Cancelar</button>
              <button onClick={addGame} disabled={!form.rival.trim()} style={{...btnSt('#fff',T.accent),flex:2,padding:'11px',border:'none',opacity:!form.rival.trim()?0.5:1}}>Guardar partido</button>
            </div>
          </div>
        </div>
      )}

      {/* Delete confirm */}
      {delId && (
        <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.5)',zIndex:300,display:'flex',alignItems:'center',justifyContent:'center',padding:16}}>
          <div style={{background:'#fff',borderRadius:12,padding:28,width:'min(360px,100%)',textAlign:'center',boxShadow:'0 24px 60px #00000040'}}>
            <div style={{fontSize:36,marginBottom:12}}>⚠️</div>
            <h3 style={{margin:'0 0 8px',fontSize:17,fontWeight:700,color:T.text}}>Eliminar partido</h3>
            <p style={{margin:'0 0 24px',fontSize:13,color:T.muted}}>
              vs {games.find(g=>g.id===delId)?.rival} — Se eliminara el partido y sus estadisticas individuales.
            </p>
            <div style={{display:'flex',gap:10}}>
              <button onClick={()=>setDelId(null)} style={{...btnSt(T.muted,'#f8fafc',T.border),flex:1,padding:'11px'}}>Cancelar</button>
              <button onClick={()=>deleteGame(delId)} style={{...btnSt('#fff','#DC2626'),flex:1,padding:'11px',border:'none'}}>Eliminar</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
window.AdminPartidos = AdminPartidos;

// ── ANOTADOR EN VIVO ──────────────────────────────────────────
function AdminPartido() {
  const { players } = window.TData;
  const today = new Date().toISOString().split("T")[0];

  const initStats = () => {
    const s = {};
    players.forEach(p => { s[p.id] = [0,0,0,0,0,0,0,0,0,0,0]; });
    return s;
  };

  const [phase, setPhase] = React.useState("setup");
  const [gameInfo, setGameInfo] = React.useState({ rival:"", date:today, home:true });
  const [stats, setStats] = React.useState(initStats);
  const [scoreUs, setScoreUs] = React.useState(0);
  const [scoreThem, setScoreThem] = React.useState(0);
  const [sel, setSel] = React.useState(null);
  const [hist, setHist] = React.useState([]);
  const [flash, setFlash] = React.useState(null);

  const addStat = (pid, field, delta, scoreDelta) => {
    setStats(prev => {
      const row = [...prev[pid]];
      row[field] = Math.max(0, row[field] + delta);
      setHist(h => [...h.slice(-40), { pid, field, delta, prevRow:[...prev[pid]], scoreDelta:scoreDelta||0 }]);
      return { ...prev, [pid]: row };
    });
    if (scoreDelta) setScoreUs(s => Math.max(0, s + scoreDelta));
    setFlash(pid);
    setTimeout(() => setFlash(f => f === pid ? null : f), 500);
  };

  const undo = () => {
    if (!hist.length) return;
    const last = hist[hist.length - 1];
    setStats(prev => ({ ...prev, [last.pid]: last.prevRow }));
    if (last.scoreDelta) setScoreUs(s => Math.max(0, s - last.scoreDelta));
    setHist(h => h.slice(0, -1));
  };

  const saveGame = () => {
    const games = window.TData.games;
    const newId = Math.max(0, ...games.map(g => g.id)) + 1;
    const result = scoreUs > scoreThem ? "W" : scoreUs < scoreThem ? "L" : "E";
    const newGame = { id:newId, date:gameInfo.date, rival:gameInfo.rival, result, scoreUs, scoreThem, location: gameInfo.home ? "Local" : "Visita" };
    const savedGames = [...games, newGame];
    const savedRaw = { ...window.TData.rawStats, [newId]: stats };
    window.TData.games = savedGames;
    window.TData.rawStats = savedRaw;
    // Auto-sync to server so portal de padres updates immediately
    fetch('/api/partidos.php', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ adminKey: 'TormPortal2026', games: savedGames, rawStats: savedRaw }),
    }).catch(() => {});
    setPhase("done");
  };

  const reset = () => {
    setPhase("setup"); setStats(initStats()); setScoreUs(0); setScoreThem(0);
    setSel(null); setHist([]); setGameInfo({ rival:"", date:today, home:true });
  };

  const ACTIONS = [
    { label:"+ 2 Pts",  color:"#2563eb", bg:"#dbeafe", fn: pid => { addStat(pid,6,1,0); addStat(pid,7,1,2); } },
    { label:"+ 3 Pts",  color:"#7c3aed", bg:"#ede9fe", fn: pid => { addStat(pid,6,1,0); addStat(pid,7,1,3); } },
    { label:"TL ✓",     color:"#059669", bg:"#d1fae5", fn: pid => { addStat(pid,4,1,0); addStat(pid,5,1,1); } },
    { label:"TL ✗",     color:"#b45309", bg:"#fef3c7", fn: pid => { addStat(pid,5,1,0); } },
    { label:"Falla TF", color:"#64748b", bg:"#f1f5f9", fn: pid => { addStat(pid,7,1,0); } },
    { label:"Rebote",   color:"#0891b2", bg:"#cffafe", fn: pid => { addStat(pid,1,1,0); } },
    { label:"Asist.",   color:"#d97706", bg:"#fef9c3", fn: pid => { addStat(pid,2,1,0); } },
    { label:"Robo",     color:"#16a34a", bg:"#dcfce7", fn: pid => { addStat(pid,3,1,0); } },
    { label:"Pérdida",  color:"#dc2626", bg:"#fee2e2", fn: pid => { addStat(pid,10,1,0); } },
    { label:"Falta",    color:"#ea580c", bg:"#ffedd5", fn: pid => { addStat(pid,8,1,0); } },
  ];

  const inputSt = {
    width:"100%", padding:"11px 14px", border:`1.5px solid ${T.border}`, borderRadius:8,
    fontSize:14, fontFamily:"inherit", outline:"none", color:T.text,
    background:"#f8fafc", boxSizing:"border-box"
  };
  const btnSt = (color, bg, bd) => ({
    padding:"10px 18px", borderRadius:8, border:`1.5px solid ${bd||color}`,
    background:bg, color, fontWeight:700, fontSize:13, cursor:"pointer", fontFamily:"inherit"
  });

  /* ── SETUP ── */
  if (phase === "setup") {
    return (
      <div>
        <h2 style={{ margin:"0 0 6px", fontSize:20, fontWeight:700, color:T.text, letterSpacing:"-0.02em" }}>Anotador</h2>
        <p style={{ margin:"0 0 28px", fontSize:13, color:T.muted }}>Registra las estadísticas de un partido en tiempo real</p>
        <div style={{ maxWidth:440 }}>
          <div style={{ marginBottom:16 }}>
            <label style={{ fontSize:11, fontWeight:700, color:T.muted, textTransform:"uppercase", letterSpacing:"0.07em", display:"block", marginBottom:6 }}>Rival</label>
            <input value={gameInfo.rival} onChange={e=>setGameInfo(g=>({...g,rival:e.target.value}))}
              placeholder="Nombre del equipo rival" style={inputSt} />
          </div>
          <div style={{ marginBottom:16 }}>
            <label style={{ fontSize:11, fontWeight:700, color:T.muted, textTransform:"uppercase", letterSpacing:"0.07em", display:"block", marginBottom:6 }}>Fecha</label>
            <input type="date" value={gameInfo.date} onChange={e=>setGameInfo(g=>({...g,date:e.target.value}))} style={inputSt} />
          </div>
          <div style={{ marginBottom:28 }}>
            <label style={{ fontSize:11, fontWeight:700, color:T.muted, textTransform:"uppercase", letterSpacing:"0.07em", display:"block", marginBottom:8 }}>Sede</label>
            <div style={{ display:"flex", gap:8 }}>
              {[{l:"Local",v:true},{l:"Visita",v:false}].map(o => (
                <button key={String(o.v)} onClick={()=>setGameInfo(g=>({...g,home:o.v}))} style={{
                  flex:1, padding:"11px", borderRadius:8,
                  border:`1.5px solid ${gameInfo.home===o.v?T.accent:T.border}`,
                  background:gameInfo.home===o.v?T.accentLt:"#fff",
                  color:gameInfo.home===o.v?T.accent:T.muted,
                  fontWeight:700, fontSize:14, cursor:"pointer", fontFamily:"inherit", transition:"all 0.12s"
                }}>{o.l}</button>
              ))}
            </div>
          </div>
          <button onClick={()=>{ if(gameInfo.rival.trim()) setPhase("live"); }}
            style={{
              width:"100%", padding:"15px", borderRadius:10, border:"none",
              background: gameInfo.rival.trim() ? "#2563eb" : "#cbd5e1",
              color:"#fff", fontWeight:700, fontSize:16, cursor: gameInfo.rival.trim() ? "pointer" : "default",
              fontFamily:"inherit", letterSpacing:"-0.01em"
            }}>
            🏀 Iniciar partido
          </button>
        </div>
      </div>
    );
  }

  /* ── DONE ── */
  if (phase === "done") {
    const result = scoreUs > scoreThem ? "V" : scoreUs < scoreThem ? "D" : "E";
    const resColor = scoreUs > scoreThem ? T.green : scoreUs < scoreThem ? T.red : T.muted;
    const topPts = [...players].sort((a,b) => (stats[b.id]?.[0]||0) - (stats[a.id]?.[0]||0)).slice(0,3);
    return (
      <div style={{ maxWidth:480, margin:"0 auto" }}>
        <div style={{ textAlign:"center", marginBottom:28 }}>
          <div style={{ fontSize:52, marginBottom:8 }}>{scoreUs > scoreThem ? "🏆" : "💪"}</div>
          <div style={{ fontSize:13, color:T.muted, marginBottom:6 }}>vs {gameInfo.rival} · {gameInfo.date}</div>
          <div style={{ fontSize:44, fontWeight:900, color:resColor, lineHeight:1 }}>{scoreUs} - {scoreThem}</div>
          <div style={{ fontSize:16, fontWeight:700, color:resColor, marginTop:4 }}>
            {result === "V" ? "Victoria" : result === "D" ? "Derrota" : "Empate"}
          </div>
        </div>
        <PCard>
          <PLabel>Mejores anotadoras</PLabel>
          {topPts.map((p,i) => (
            <div key={p.id} style={{ display:"flex", alignItems:"center", gap:12, padding:"8px 0", borderBottom: i<2?`1px solid ${T.border}`:"none" }}>
              <span style={{ fontSize:18, fontWeight:900, color:T.muted, width:24 }}>{i+1}</span>
              <PAvatar initials={p.initials} color={posColorsP[p.pos]||T.accent} size={32} />
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13, fontWeight:600, color:T.text }}>{p.name}</div>
                <div style={{ fontSize:11, color:T.muted }}>
                  R:{stats[p.id][1]} A:{stats[p.id][2]} F:{stats[p.id][8]}
                </div>
              </div>
              <div style={{ fontSize:22, fontWeight:900, color:T.accent }}>{stats[p.id][0]}</div>
            </div>
          ))}
        </PCard>
        <button onClick={reset} style={{
          marginTop:20, width:"100%", padding:"13px", borderRadius:10,
          background:"#2563eb", color:"#fff", border:"none",
          fontWeight:700, fontSize:15, cursor:"pointer", fontFamily:"inherit"
        }}>+ Nuevo partido</button>
      </div>
    );
  }

  /* ── LIVE ── */
  const selPlayer = sel ? players.find(p => p.id === sel) : null;

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

      {/* Marcador */}
      <div style={{
        background:"linear-gradient(135deg, #0A2540 0%, #1e3a5f 100%)",
        borderRadius:16, padding:"18px 20px",
        display:"flex", alignItems:"center"
      }}>
        <div style={{ flex:1, textAlign:"center" }}>
          <div style={{ fontSize:11, fontWeight:700, color:"rgba(255,255,255,0.5)", letterSpacing:"0.1em", marginBottom:4 }}>TORMENTAS</div>
          <div style={{ fontSize:56, fontWeight:900, color:"#fff", lineHeight:1 }}>{scoreUs}</div>
        </div>
        <div style={{ display:"flex", flexDirection:"column", gap:6, alignItems:"center", padding:"0 12px" }}>
          <div style={{ fontSize:14, fontWeight:700, color:"rgba(255,255,255,0.3)" }}>VS</div>
          <div style={{ display:"flex", gap:4 }}>
            {[{l:"+2",d:2},{l:"+3",d:3},{l:"TL",d:1}].map(b => (
              <button key={b.l} onClick={()=>setScoreThem(s=>s+b.d)} style={{
                padding:"5px 7px", borderRadius:6, background:"rgba(255,255,255,0.12)",
                border:"none", color:"#fff", fontSize:10, fontWeight:700, cursor:"pointer", fontFamily:"inherit"
              }}>{b.l}</button>
            ))}
            <button onClick={()=>setScoreThem(s=>Math.max(0,s-1))} style={{
              padding:"5px 7px", borderRadius:6, background:"rgba(239,68,68,0.2)",
              border:"none", color:"#fca5a5", fontSize:10, fontWeight:700, cursor:"pointer", fontFamily:"inherit"
            }}>-1</button>
          </div>
        </div>
        <div style={{ flex:1, textAlign:"center" }}>
          <div style={{ fontSize:11, fontWeight:700, color:"rgba(255,255,255,0.5)", letterSpacing:"0.1em", marginBottom:4, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>
            {gameInfo.rival.toUpperCase()}
          </div>
          <div style={{ fontSize:56, fontWeight:900, color:"#fff", lineHeight:1 }}>{scoreThem}</div>
        </div>
      </div>

      {/* Toolbar */}
      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", gap:8, flexWrap:"wrap" }}>
        <div style={{ fontSize:13, color:T.muted }}>
          {sel ? `Acción para ${selPlayer?.name.split(" ")[0]}` : "Selecciona una jugadora"}
        </div>
        <div style={{ display:"flex", gap:6 }}>
          {hist.length > 0 && (
            <button onClick={undo} style={btnSt("#92400e","#fef3c7","#fcd34d")}>↩ Deshacer</button>
          )}
          <button onClick={()=>{ if(window.confirm("¿Guardar y cerrar el partido?")) saveGame(); }}
            style={btnSt("#166534","#dcfce7","#4ade80")}>✓ Terminar</button>
        </div>
      </div>

      {/* Jugadoras grid */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill,minmax(110px,1fr))", gap:8 }}>
        {players.map(p => {
          const s = stats[p.id] || [0,0,0,0,0,0,0,0,0,0,0];
          const isSel = sel === p.id;
          const posColor = posColorsP[p.pos] || T.accent;
          return (
            <div key={p.id} onClick={()=>setSel(p.id)} style={{
              borderRadius:12, padding:"12px 8px", textAlign:"center", cursor:"pointer",
              background: flash === p.id ? "#dcfce7" : isSel ? posColor : "#fff",
              border: `2px solid ${flash === p.id ? "#16a34a" : isSel ? posColor : T.border}`,
              boxShadow: isSel ? `0 4px 14px ${posColor}50` : flash === p.id ? "0 0 0 3px #16a34a30" : "none",
              transition:"background 0.15s, border-color 0.15s, box-shadow 0.15s",
              userSelect:"none", WebkitTapHighlightColor:"transparent"
            }}>
              <div style={{ fontSize:24, fontWeight:900, lineHeight:1, marginBottom:2, color: flash===p.id?"#16a34a": isSel?"#fff":T.text }}>{s[0]}</div>
              <div style={{ fontSize:8, fontWeight:700, letterSpacing:"0.1em", color: isSel?"rgba(255,255,255,0.6)":T.muted, marginBottom:8 }}>PTS</div>
              <div style={{ fontSize:12, fontWeight:700, color: isSel?"#fff":T.text, marginBottom:2, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>
                {p.name.split(" ")[0]}
              </div>
              <div style={{ fontSize:10, color: isSel?"rgba(255,255,255,0.6)":T.muted, marginBottom:6 }}>#{p.num}</div>
              <div style={{ display:"flex", justifyContent:"center", gap:5 }}>
                {[["R",s[1]],["A",s[2]],["F",s[8]]].map(([l,v])=>(
                  <span key={l} style={{ fontSize:9, color: isSel?"rgba(255,255,255,0.65)":T.subtle }}>
                    {l}{v}
                  </span>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      {/* Modal overlay de acciones */}
      {sel && (
        <div
          onClick={() => setSel(null)}
          style={{
            position:"fixed", inset:0, zIndex:1040,
            background:"rgba(0,0,0,0.45)", display:"flex", alignItems:"flex-end"
          }}
        >
          <div
            onClick={e => e.stopPropagation()}
            style={{
              background:"#fff", borderRadius:"20px 20px 0 0",
              padding:"20px 16px 36px", width:"100%",
              boxShadow:"0 -8px 32px rgba(0,0,0,0.2)"
            }}
          >
            {/* Drag handle */}
            <div style={{ width:36, height:4, borderRadius:99, background:T.border, margin:"0 auto 16px" }} />

            {/* Header jugadora */}
            <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:16 }}>
              <div style={{ display:"flex", alignItems:"center", gap:10 }}>
                <PAvatar initials={selPlayer?.initials} color={posColorsP[selPlayer?.pos]||T.accent} size={38} />
                <div>
                  <div style={{ fontSize:15, fontWeight:700, color:T.text }}>{selPlayer?.name} · #{selPlayer?.num}</div>
                  <div style={{ fontSize:12, color:T.muted }}>
                    {stats[sel][0]} pts · {stats[sel][1]} reb · {stats[sel][2]} ast · {stats[sel][8]} f
                  </div>
                </div>
              </div>
              <button onClick={() => setSel(null)} style={{
                width:32, height:32, borderRadius:"50%", border:`1px solid ${T.border}`,
                background:"#f8f8f8", color:T.muted, fontSize:18, lineHeight:1,
                cursor:"pointer", display:"flex", alignItems:"center", justifyContent:"center",
                fontFamily:"inherit", flexShrink:0
              }}>×</button>
            </div>

            {/* Acciones */}
            <div style={{ display:"grid", gridTemplateColumns:"repeat(5,1fr)", gap:8 }}>
              {ACTIONS.map(a => (
                <button key={a.label}
                  onClick={() => { a.fn(sel); }}
                  style={{
                    padding:"14px 4px", borderRadius:12, minHeight:52,
                    border:`1.5px solid ${a.color}30`,
                    background:a.bg, color:a.color,
                    fontWeight:700, fontSize:12, cursor:"pointer", fontFamily:"inherit",
                    lineHeight:1.3, touchAction:"manipulation",
                    WebkitTapHighlightColor:"transparent", transition:"transform 0.08s"
                  }}
                  onMouseDown={e=>e.currentTarget.style.transform="scale(0.91)"}
                  onMouseUp={e=>e.currentTarget.style.transform="scale(1)"}
                  onTouchStart={e=>e.currentTarget.style.transform="scale(0.91)"}
                  onTouchEnd={e=>e.currentTarget.style.transform="scale(1)"}
                >{a.label}</button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
window.AdminPartido = AdminPartido;

// ── PORTAL PADRES ───────────────────────────────────────────
function AdminPortal() {
  const PORTAL_URL  = 'https://tormentas.muga.com.mx/portal.html';
  const [status, setStatus] = React.useState(null); // null | 'publishing' | 'ok' | 'err'
  const [lastPublished, setLastPublished] = React.useState(null);
  const [errMsg, setErrMsg] = React.useState('');

  function publishStats() {
    setStatus('publishing');
    setErrMsg('');
    const players        = window.TData.players;
    const games          = window.TData.games;
    const rawStats       = window.TData.rawStats;
    const upcomingEvents = window.TData.upcomingEvents || [];
    const trainingDates  = window.TData.trainingDates  || [];

    fetch('/api/asistencia.php')
      .then(r => r.json())
      .then(attendance => {
        return fetch('/api/stats.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ adminKey: ADMIN_KEY, players, games, rawStats, attendance, upcomingEvents, trainingDates }),
        });
      })
      .then(r => r.json())
      .then(d => {
        if (d.ok) {
          const ts = new Date().toLocaleString('es-MX', { day:'numeric', month:'long', hour:'2-digit', minute:'2-digit' });
          setLastPublished(ts);
          setStatus('ok');
        } else {
          setErrMsg(d.error || 'Error desconocido');
          setStatus('err');
        }
      })
      .catch(e => { setErrMsg('Error de conexion: ' + e.message); setStatus('err'); });
  }

  function copyLink() {
    navigator.clipboard.writeText(PORTAL_URL).then(() => {
      const btn = document.getElementById('btn-copy-portal');
      if (btn) { btn.textContent = 'Copiado'; setTimeout(() => { btn.textContent = 'Copiar enlace'; }, 2000); }
    }).catch(() => {});
  }

  const { players } = window.TData;
  const rawStats = window.TData.rawStats || {};
  const games    = window.TData.games    || [];
  const gamesWithStats = games.filter(g => rawStats[g.id] && Object.keys(rawStats[g.id]).length > 0).length;

  return (
    <div>
      <div style={{marginBottom:24}}>
        <h2 style={{margin:0,fontSize:20,fontWeight:700,color:T.text,letterSpacing:"-0.02em"}}>Portal de Padres</h2>
        <p style={{margin:"4px 0 0",fontSize:13,color:T.muted}}>Publica las estadisticas para que los padres y tutores puedan verlas.</p>
      </div>

      {/* Status banner */}
      <div className="t-grid-3" style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:12,marginBottom:20}}>
        <PKPICard label="Jugadoras en roster" value={players.length} color={T.text} />
        <PKPICard label="Partidos con stats"  value={gamesWithStats} color={T.accent} sub={`de ${games.length} jugados`} />
        <PKPICard label="Ultimo publicado"    value={lastPublished ? lastPublished.split(',')[0] : '—'} color={lastPublished ? T.green : T.muted} sub={lastPublished ? lastPublished.split(',')[1]?.trim() || '' : 'Nunca publicado'} />
      </div>

      {/* Publish card */}
      <div style={{background:"#fff",border:`1px solid ${T.border}`,borderRadius:10,padding:24,marginBottom:16}}>
        <div style={{marginBottom:16}}>
          <div style={{fontSize:14,fontWeight:700,color:T.text,marginBottom:4}}>Publicar estadisticas al portal</div>
          <p style={{fontSize:13,color:T.muted,lineHeight:1.6}}>
            Envia las estadisticas actuales (jugadoras, partidos y stats) al portal para que los padres registrados puedan verlas.
            Los datos se actualizan cada vez que presiones este boton.
          </p>
        </div>
        {status === 'ok' && (
          <div style={{background:"#F0FDF4",border:"1px solid #BBF7D0",borderRadius:8,padding:"10px 14px",marginBottom:14,fontSize:13,color:"#166534"}}>
            Estadisticas publicadas correctamente. Los padres ya pueden verlas en el portal.
          </div>
        )}
        {status === 'err' && (
          <div style={{background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:8,padding:"10px 14px",marginBottom:14,fontSize:13,color:"#991B1B"}}>
            {errMsg || 'Error al publicar. Intenta de nuevo.'}
          </div>
        )}
        <button
          onClick={publishStats}
          disabled={status === 'publishing'}
          style={{padding:"11px 24px",background:T.accent,color:"#fff",border:"none",borderRadius:8,fontWeight:700,fontSize:14,cursor:status==='publishing'?"not-allowed":"pointer",opacity:status==='publishing'?0.5:1,fontFamily:"inherit"}}
        >
          {status === 'publishing' ? 'Publicando...' : 'Publicar estadisticas ahora'}
        </button>
      </div>

      {/* Portal link card */}
      <div style={{background:"#fff",border:`1px solid ${T.border}`,borderRadius:10,padding:24,marginBottom:16}}>
        <div style={{fontSize:14,fontWeight:700,color:T.text,marginBottom:6}}>Enlace del portal</div>
        <p style={{fontSize:13,color:T.muted,marginBottom:14,lineHeight:1.6}}>
          Comparte este enlace con los padres y tutores para que puedan crear su cuenta y ver las estadisticas de su jugadora.
        </p>
        <div style={{display:"flex",gap:10,alignItems:"center",flexWrap:"wrap"}}>
          <div style={{flex:1,minWidth:0,background:"#F8FAFC",border:`1px solid ${T.border}`,borderRadius:7,padding:"9px 12px",fontSize:12,color:T.muted,fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>
            {PORTAL_URL}
          </div>
          <button id="btn-copy-portal" onClick={copyLink} style={{padding:"9px 16px",background:"#F8FAFC",border:`1px solid ${T.border}`,borderRadius:7,fontWeight:600,fontSize:12,cursor:"pointer",fontFamily:"inherit",color:T.text,flexShrink:0}}>
            Copiar enlace
          </button>
          <a href={PORTAL_URL} target="_blank" rel="noreferrer" style={{padding:"9px 16px",background:T.navy||"#0A2540",color:"#fff",borderRadius:7,fontWeight:600,fontSize:12,textDecoration:"none",flexShrink:0}}>
            Abrir portal
          </a>
        </div>
      </div>

      {/* Info card */}
      <div style={{background:"#F8FAFC",border:`1px solid ${T.border}`,borderRadius:10,padding:20,marginBottom:16}}>
        <div style={{fontSize:12,fontWeight:700,color:T.muted,textTransform:"uppercase",letterSpacing:".06em",marginBottom:10}}>Como funciona</div>
        {[
          ["1", "Los padres reciben el correo de confirmacion con el enlace al portal tras registrar a su jugadora."],
          ["2", "Crean su cuenta con el mismo correo que usaron en el formulario de registro."],
          ["3", "El sistema vincula automaticamente su cuenta con las jugadoras de ese correo."],
          ["4", "Cuando publicas las estadisticas, los padres pueden ver los promedios de su hija y del equipo."],
        ].map(([n, txt]) => (
          <div key={n} style={{display:"flex",gap:10,marginBottom:10,alignItems:"flex-start"}}>
            <div style={{width:22,height:22,borderRadius:"50%",background:T.accent+"22",color:T.accent,fontWeight:800,fontSize:11,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:1}}>{n}</div>
            <p style={{fontSize:13,color:T.muted,lineHeight:1.6,flex:1}}>{txt}</p>
          </div>
        ))}
      </div>

      {/* Resend approval emails */}
      <ResendApprovalCard />
    </div>
  );
}
window.AdminPortal = AdminPortal;

function ResendApprovalCard() {
  const [regs, setRegs] = React.useState([]);
  const [sending, setSending] = React.useState({});
  const [sent, setSent] = React.useState({});

  React.useEffect(() => {
    fetch('/api/registros.php')
      .then(r => r.json())
      .then(data => {
        const approved = (Array.isArray(data) ? data : []).filter(r => r.status === 'aprobada');
        setRegs(approved);
      })
      .catch(() => {});
  }, []);

  function resend(reg) {
    setSending(p => ({ ...p, [reg.id]: true }));
    fetch('/api/registros.php?action=resend_approval', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: reg.id }),
    })
    .then(r => r.json())
    .then(d => {
      setSending(p => ({ ...p, [reg.id]: false }));
      if (d.ok) setSent(p => ({ ...p, [reg.id]: true }));
    })
    .catch(() => setSending(p => ({ ...p, [reg.id]: false })));
  }

  if (!regs.length) return null;

  return (
    <div style={{background:"#fff",border:`1px solid ${T.border}`,borderRadius:10,padding:24}}>
      <div style={{fontSize:14,fontWeight:700,color:T.text,marginBottom:4}}>Reenviar correo de aprobacion</div>
      <p style={{fontSize:13,color:T.muted,marginBottom:16,lineHeight:1.6}}>
        Reenvía el correo de aprobación a los padres de jugadoras ya aprobadas (útil si el correo no llegó).
      </p>
      <div style={{display:"flex",flexDirection:"column",gap:8}}>
        {regs.map(reg => {
          const nombre = reg.jugadora?.nombre || '—';
          const emails = [reg.contactos?.c1?.email, reg.contactos?.c2?.email].filter(Boolean).join(', ');
          const isSending = sending[reg.id];
          const isSent    = sent[reg.id];
          return (
            <div key={reg.id} style={{display:"flex",alignItems:"center",gap:12,padding:"10px 14px",background:"#F8FAFC",border:`1px solid ${T.border}`,borderRadius:8}}>
              <div style={{flex:1,minWidth:0}}>
                <div style={{fontSize:13,fontWeight:600,color:T.text}}>{nombre}</div>
                <div style={{fontSize:11,color:T.muted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{emails || 'Sin email'}</div>
              </div>
              {isSent
                ? <span style={{fontSize:12,color:T.green,fontWeight:700}}>✓ Enviado</span>
                : <button
                    onClick={() => resend(reg)}
                    disabled={isSending}
                    style={{padding:"7px 14px",background:isSending?"#F1F5F9":T.accent+"18",color:isSending?T.muted:T.accent,border:`1px solid ${T.accent}44`,borderRadius:7,fontWeight:600,fontSize:12,cursor:isSending?"not-allowed":"pointer",fontFamily:"inherit",flexShrink:0}}
                  >
                    {isSending ? 'Enviando...' : 'Reenviar'}
                  </button>
              }
            </div>
          );
        })}
      </div>
    </div>
  );
}
window.ResendApprovalCard = ResendApprovalCard;

// ── ADMIN USUARIOS ──────────────────────────────────────────
const ADMIN_KEY_U = 'TormPortal2026';

function AdminUsuarios() {
  const [users,    setUsers]    = React.useState([]);
  const [loading,  setLoading]  = React.useState(true);
  const [editing,  setEditing]  = React.useState(null);   // user object being edited
  const [deleting, setDeleting] = React.useState(null);   // user id pending confirm
  const [saving,   setSaving]   = React.useState(false);
  const [msg,      setMsg]      = React.useState(null);   // {type:'ok'|'err', text}

  // Edit form state
  const [editNombre, setEditNombre] = React.useState('');
  const [editEmail,  setEditEmail]  = React.useState('');
  const [editPass,   setEditPass]   = React.useState('');

  function load() {
    setLoading(true);
    fetch(`/api/usuarios.php?action=admin_list&adminKey=${ADMIN_KEY_U}`)
      .then(r => r.json())
      .then(d => { setUsers(Array.isArray(d) ? d : []); setLoading(false); })
      .catch(() => { setUsers([]); setLoading(false); });
  }

  React.useEffect(() => { load(); }, []);

  function openEdit(user) {
    setEditing(user);
    setEditNombre(user.nombre);
    setEditEmail(user.email);
    setEditPass('');
    setMsg(null);
  }

  function saveEdit() {
    if (!editNombre.trim() || !editEmail.trim()) return;
    setSaving(true);
    const body = { adminKey: ADMIN_KEY_U, id: editing.id, nombre: editNombre.trim(), email: editEmail.trim() };
    if (editPass.length >= 6) body.password = editPass;
    fetch('/api/usuarios.php?action=admin_update', {
      method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body),
    })
    .then(r => r.json())
    .then(d => {
      setSaving(false);
      if (d.ok) {
        setMsg({ type:'ok', text:'Usuario actualizado.' });
        setEditing(null);
        load();
      } else {
        setMsg({ type:'err', text: d.error || 'Error al guardar.' });
      }
    })
    .catch(() => { setSaving(false); setMsg({ type:'err', text:'Error de conexion.' }); });
  }

  function confirmDelete(userId) {
    fetch('/api/usuarios.php?action=admin_delete', {
      method: 'POST', headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ adminKey: ADMIN_KEY_U, id: userId }),
    })
    .then(r => r.json())
    .then(d => {
      setDeleting(null);
      if (d.ok) { setMsg({ type:'ok', text:'Cuenta eliminada.' }); load(); }
      else       setMsg({ type:'err', text: d.error || 'Error al eliminar.' });
    })
    .catch(() => { setDeleting(null); setMsg({ type:'err', text:'Error de conexion.' }); });
  }

  const statusColor = { aprobada:'#16A34A', pendiente:'#D97706', rechazado:'#DC2626' };
  const statusLabel = { aprobada:'Aprobada', pendiente:'Pendiente', rechazado:'Rechazado' };

  return (
    <div>
      <div style={{marginBottom:24}}>
        <h2 style={{margin:0,fontSize:20,fontWeight:700,color:T.text,letterSpacing:"-0.02em"}}>Usuarios del portal</h2>
        <p style={{margin:"4px 0 0",fontSize:13,color:T.muted}}>Padres y tutores con cuenta en el portal de estadisticas.</p>
      </div>

      {/* Global message */}
      {msg && (
        <div style={{
          background: msg.type==='ok' ? '#F0FDF4' : '#FEF2F2',
          border: `1px solid ${msg.type==='ok' ? '#BBF7D0' : '#FECACA'}`,
          color: msg.type==='ok' ? '#166534' : '#991B1B',
          borderRadius:8, padding:'10px 14px', fontSize:13, marginBottom:16,
          display:'flex', alignItems:'center', justifyContent:'space-between', gap:10
        }}>
          <span>{msg.text}</span>
          <button onClick={()=>setMsg(null)} style={{background:'none',border:'none',cursor:'pointer',fontSize:16,color:'inherit',lineHeight:1,padding:'0 2px'}}>×</button>
        </div>
      )}

      {/* KPI */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:12,marginBottom:20}}>
        <PKPICard label="Cuentas activas"    value={users.length}  color={T.text} />
        <PKPICard label="Jugadoras vinculadas" value={users.reduce((s,u)=>s+u.jugadoras.length,0)} color={T.accent} />
        <PKPICard label="Con jugadora aprobada" value={users.filter(u=>u.jugadoras.some(j=>j.status==='aprobada')).length} color={T.green} />
      </div>

      {/* Table */}
      {loading ? (
        <div style={{textAlign:'center',padding:'60px 20px',color:T.muted,fontSize:13}}>Cargando usuarios...</div>
      ) : users.length === 0 ? (
        <div style={{textAlign:'center',padding:'60px 20px',color:T.muted}}>
          <div style={{fontSize:36,marginBottom:12,opacity:.3}}>👤</div>
          <div style={{fontSize:15,fontWeight:700,color:T.text}}>Sin cuentas registradas</div>
          <div style={{fontSize:13,marginTop:6}}>Los padres crean su cuenta desde el portal de padres.</div>
        </div>
      ) : (
        <div style={{background:'#fff',border:`1px solid ${T.border}`,borderRadius:10,overflow:'hidden'}}>
          {/* Table header */}
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr auto',gap:0,padding:'8px 16px',background:'#F8FAFC',borderBottom:`1px solid ${T.border}`}}>
            <div style={{fontSize:9,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.08em'}}>Usuario</div>
            <div style={{fontSize:9,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.08em'}}>Jugadoras vinculadas</div>
            <div style={{fontSize:9,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.08em',width:80,textAlign:'right'}}>Acciones</div>
          </div>

          {users.map((u, i) => (
            <div key={u.id} style={{
              display:'grid', gridTemplateColumns:'1fr 1fr auto', gap:0,
              padding:'14px 16px', borderTop: i===0?'none':`1px solid ${T.border}`,
              alignItems:'center',
            }}>
              {/* User info */}
              <div style={{minWidth:0,paddingRight:16}}>
                <div style={{fontSize:13,fontWeight:600,color:T.text,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{u.nombre}</div>
                <div style={{fontSize:11,color:T.muted,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',marginTop:2}}>{u.email}</div>
                {u.createdAt && <div style={{fontSize:10,color:T.muted,marginTop:3}}>Cuenta creada: {u.createdAt}</div>}
              </div>

              {/* Jugadoras */}
              <div style={{display:'flex',flexDirection:'column',gap:4,paddingRight:12}}>
                {u.jugadoras.length === 0
                  ? <span style={{fontSize:11,color:T.muted}}>Sin jugadoras vinculadas</span>
                  : u.jugadoras.map(j => (
                    <div key={j.regId} style={{display:'flex',alignItems:'center',gap:6}}>
                      <span style={{fontSize:12,fontWeight:600,color:T.text}}>{j.nombre}</span>
                      {j.numero && <span style={{fontFamily:"'Bebas Neue',Impact,sans-serif",fontSize:13,color:T.accent}}>#{j.numero}</span>}
                      <span style={{fontSize:10,padding:'1px 7px',borderRadius:10,background:statusColor[j.status]+'18',color:statusColor[j.status]||T.muted,fontWeight:700}}>
                        {statusLabel[j.status]||j.status}
                      </span>
                    </div>
                  ))
                }
              </div>

              {/* Actions */}
              <div style={{display:'flex',gap:6,flexShrink:0}}>
                <button
                  onClick={() => openEdit(u)}
                  style={{padding:'6px 12px',background:'#F8FAFC',border:`1px solid ${T.border}`,borderRadius:7,fontWeight:600,fontSize:11,cursor:'pointer',fontFamily:'inherit',color:T.text}}
                >
                  Editar
                </button>
                <button
                  onClick={() => setDeleting(u.id)}
                  style={{padding:'6px 10px',background:'#FEF2F2',border:'1px solid #FECACA',borderRadius:7,fontWeight:600,fontSize:11,cursor:'pointer',fontFamily:'inherit',color:'#DC2626'}}
                >
                  ×
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Edit modal */}
      {editing && (
        <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.5)',zIndex:300,display:'flex',alignItems:'center',justifyContent:'center',padding:16}}>
          <div style={{background:'#fff',borderRadius:12,padding:28,width:'100%',maxWidth:400,boxShadow:'0 24px 60px #00000040'}}>
            <div style={{fontSize:15,fontWeight:700,color:T.text,marginBottom:20}}>Editar usuario</div>

            {msg && <div style={{background:msg.type==='ok'?'#F0FDF4':'#FEF2F2',border:`1px solid ${msg.type==='ok'?'#BBF7D0':'#FECACA'}`,color:msg.type==='ok'?'#166534':'#991B1B',borderRadius:8,padding:'9px 13px',fontSize:12,marginBottom:14}}>{msg.text}</div>}

            <div style={{marginBottom:12}}>
              <label style={{display:'block',fontSize:10,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.05em',marginBottom:5}}>Nombre</label>
              <input value={editNombre} onChange={e=>setEditNombre(e.target.value)}
                style={{width:'100%',padding:'9px 11px',border:`1.5px solid ${T.border}`,borderRadius:8,fontSize:13,fontFamily:'inherit',color:T.text}} />
            </div>
            <div style={{marginBottom:12}}>
              <label style={{display:'block',fontSize:10,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.05em',marginBottom:5}}>Correo electronico</label>
              <input type="email" value={editEmail} onChange={e=>setEditEmail(e.target.value)}
                style={{width:'100%',padding:'9px 11px',border:`1.5px solid ${T.border}`,borderRadius:8,fontSize:13,fontFamily:'inherit',color:T.text}} />
            </div>
            <div style={{marginBottom:20}}>
              <label style={{display:'block',fontSize:10,fontWeight:700,color:T.muted,textTransform:'uppercase',letterSpacing:'.05em',marginBottom:5}}>
                Nueva contrasena <span style={{fontWeight:400,textTransform:'none'}}>(dejar vacio para no cambiar)</span>
              </label>
              <input type="password" value={editPass} onChange={e=>setEditPass(e.target.value)} placeholder="Min. 6 caracteres"
                style={{width:'100%',padding:'9px 11px',border:`1.5px solid ${T.border}`,borderRadius:8,fontSize:13,fontFamily:'inherit',color:T.text}} />
            </div>
            <div style={{display:'flex',gap:10}}>
              <button onClick={()=>{setEditing(null);setMsg(null);}} style={{flex:1,padding:'10px',background:'#F8FAFC',border:`1px solid ${T.border}`,borderRadius:8,fontWeight:600,fontSize:13,cursor:'pointer',fontFamily:'inherit',color:T.text}}>
                Cancelar
              </button>
              <button onClick={saveEdit} disabled={saving}
                style={{flex:2,padding:'10px',background:T.accent,color:'#fff',border:'none',borderRadius:8,fontWeight:700,fontSize:13,cursor:saving?'not-allowed':'pointer',opacity:saving?0.5:1,fontFamily:'inherit'}}>
                {saving ? 'Guardando...' : 'Guardar cambios'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete confirm */}
      {deleting && (
        <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.5)',zIndex:300,display:'flex',alignItems:'center',justifyContent:'center',padding:16}}>
          <div style={{background:'#fff',borderRadius:12,padding:28,width:'100%',maxWidth:360,boxShadow:'0 24px 60px #00000040',textAlign:'center'}}>
            <div style={{fontSize:36,marginBottom:12}}>⚠️</div>
            <div style={{fontSize:15,fontWeight:700,color:T.text,marginBottom:8}}>Eliminar cuenta</div>
            <p style={{fontSize:13,color:T.muted,lineHeight:1.6,marginBottom:24}}>
              Esta accion es permanente. El usuario perdera acceso al portal. Los registros de las jugadoras no se eliminan.
            </p>
            <div style={{display:'flex',gap:10}}>
              <button onClick={()=>setDeleting(null)} style={{flex:1,padding:'10px',background:'#F8FAFC',border:`1px solid ${T.border}`,borderRadius:8,fontWeight:600,fontSize:13,cursor:'pointer',fontFamily:'inherit',color:T.text}}>
                Cancelar
              </button>
              <button onClick={()=>confirmDelete(deleting)} style={{flex:1,padding:'10px',background:'#DC2626',color:'#fff',border:'none',borderRadius:8,fontWeight:700,fontSize:13,cursor:'pointer',fontFamily:'inherit'}}>
                Eliminar
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
window.AdminUsuarios = AdminUsuarios;
