// Pro Tareas: Home exercise assignment system
function ProTareas() {
  const { players } = window.TData;
  const { tasks, completions, taskCategories } = window.TDataExt;
  const [view, setView] = React.useState("overview"); // overview | assign | player
  const [selectedPlayer, setSelectedPlayer] = React.useState(null);
  const [localComp, setLocalComp] = React.useState(completions);
  const [showForm, setShowForm] = React.useState(false);
  const [newTask, setNewTask] = React.useState({ title:"", category:"Técnica", desc:"", freq:"Diario", due:"", points:10 });
  const [localTasks, setLocalTasks] = React.useState(tasks);
  const [filterCat, setFilterCat] = React.useState("Todas");

  const getCatColor = cat => ({
    "Técnica":"#2563eb","Físico":"#dc2626","Táctica":"#7c3aed","Recuperación":"#16a34a"
  }[cat]||T.accent);

  const getCompletion = (pid, tid) => localComp[pid]?.[tid] || false;
  const toggleComp = (pid, tid) => setLocalComp(prev=>({...prev,[pid]:{...prev[pid],[tid]:!prev[pid][tid]}}));

  const playerTaskPct = pid => {
    const done = localTasks.filter(t=>localComp[pid]?.[t.id]).length;
    return localTasks.length ? Math.round(done/localTasks.length*100) : 0;
  };

  const taskCompPct = tid => {
    const done = players.filter(p=>localComp[p.id]?.[tid]).length;
    return Math.round(done/players.length*100);
  };

  const addTask = () => {
    if (!newTask.title.trim()) return;
    const t = { ...newTask, id: Date.now(), assigned: new Date().toISOString().split("T")[0] };
    setLocalTasks(prev=>[...prev, t]);
    setLocalComp(prev=>{
      const n={...prev};
      players.forEach(p=>{ n[p.id]={...n[p.id],[t.id]:false}; });
      return n;
    });
    setNewTask({ title:"", category:"Técnica", desc:"", freq:"Diario", due:"", points:10 });
    setShowForm(false);
  };

  const teamAvgPct = Math.round(players.reduce((s,p)=>s+playerTaskPct(p.id),0)/players.length);
  const filteredTasks = filterCat==="Todas" ? localTasks : localTasks.filter(t=>t.category===filterCat);

  if (selectedPlayer) {
    const p = selectedPlayer;
    const pct = playerTaskPct(p.id);
    const pctColor = pct>=80?T.green:pct>=60?T.yellow:T.red;
    return (
      <div>
        <PBackBtn onClick={()=>setSelectedPlayer(null)} label="Tareas" />
        <div style={{display:"flex",alignItems:"center",gap:14,marginBottom:24}}>
          <PAvatar initials={p.initials} color={posColorsP[p.pos]||T.accent} size={44} />
          <div>
            <div style={{fontWeight:700,fontSize:18,color:T.text}}>#{p.num} {p.name}</div>
            <div style={{fontSize:12,color:T.muted,marginTop:2}}>
              <PBadge text={p.pos} color={posColorsP[p.pos]} variant="pill" />
              <span style={{marginLeft:10,fontWeight:600,color:pctColor}}>{pct}% de tareas completadas</span>
            </div>
          </div>
        </div>
        <PCard padding="0">
          {localTasks.map((t,i)=>{
            const done = getCompletion(p.id, t.id);
            return (
              <div key={t.id} style={{
                display:"flex",alignItems:"flex-start",gap:16,
                padding:"16px 24px",
                borderBottom: i<localTasks.length-1?`1px solid ${T.border}`:"none",
                background: done?"#f0fdf420":"#fff"
              }}>
                <div onClick={()=>toggleComp(p.id,t.id)} style={{
                  width:22,height:22,borderRadius:4,flexShrink:0,marginTop:1,
                  border:`2px solid ${done?T.green:T.border}`,
                  background:done?T.green:"#fff",
                  display:"flex",alignItems:"center",justifyContent:"center",
                  cursor:"pointer",color:"#fff",fontWeight:700,fontSize:13,
                  transition:"all 0.15s"
                }}>{done?"✓":""}</div>
                <div style={{flex:1}}>
                  <div style={{display:"flex",alignItems:"center",gap:10,marginBottom:3}}>
                    <span style={{fontWeight:600,fontSize:14,color:done?T.muted:T.text,
                      textDecoration:done?"line-through":"none"}}>{t.title}</span>
                    <PBadge text={t.category} color={getCatColor(t.category)} variant="pill" />
                    <span style={{fontSize:11,color:T.subtle}}>{t.freq}</span>
                  </div>
                  <div style={{fontSize:12,color:T.muted}}>{t.desc}</div>
                  {t.due && <div style={{fontSize:11,color:T.subtle,marginTop:4}}>Entrega: {t.due}</div>}
                </div>
                <div style={{
                  fontSize:12,fontWeight:700,
                  color:done?T.green:T.muted,
                  minWidth:40,textAlign:"right"
                }}>{done?`+${t.points} pts`:`${t.points} pts`}</div>
              </div>
            );
          })}
        </PCard>
      </div>
    );
  }

  return (
    <div>
      <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",marginBottom:24}}>
        <div>
          <h2 style={{margin:0,fontSize:20,fontWeight:700,color:T.text,letterSpacing:"-0.02em"}}>Tareas en Casa</h2>
          <p style={{margin:"4px 0 0",fontSize:13,color:T.muted}}>Ejercicios y actividades asignadas fuera del entrenamiento</p>
        </div>
        <button onClick={()=>setShowForm(true)} style={{
          padding:"9px 18px",background:T.accent,color:"#fff",border:"none",
          borderRadius:6,fontWeight:600,fontSize:13,cursor:"pointer",fontFamily:"inherit"
        }}>+ Nueva tarea</button>
      </div>

      {/* Team summary */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:12,marginBottom:20}}>
        <PKPICard label="Cumplimiento equipo" value={`${teamAvgPct}%`} color={teamAvgPct>=75?T.green:teamAvgPct>=50?T.yellow:T.red} />
        <PKPICard label="Tareas activas" value={localTasks.length} color={T.text} />
        <PKPICard label="100% completadas" value={players.filter(p=>playerTaskPct(p.id)===100).length} sub="jugadoras" color={T.green} />
        <PKPICard label="Necesitan atención" value={players.filter(p=>playerTaskPct(p.id)<50).length} sub="menos del 50%" color={T.red} />
      </div>

      {/* New task form */}
      {showForm && (
        <PCard style={{marginBottom:20,border:`1px solid ${T.accentMd}`,background:T.accentLt}}>
          <PLabel>Nueva tarea</PLabel>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:12}}>
            <div>
              <label style={{fontSize:11,fontWeight:600,color:T.muted,display:"block",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"}}>Título</label>
              <input value={newTask.title} onChange={e=>setNewTask(p=>({...p,title:e.target.value}))}
                placeholder="Ej: 30 tiros de media distancia"
                style={{width:"100%",padding:"8px 12px",border:`1px solid ${T.border}`,borderRadius:6,fontSize:13,color:T.text,outline:"none",fontFamily:"inherit",boxSizing:"border-box",background:"#fff"}} />
            </div>
            <div>
              <label style={{fontSize:11,fontWeight:600,color:T.muted,display:"block",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"}}>Categoría</label>
              <select value={newTask.category} onChange={e=>setNewTask(p=>({...p,category:e.target.value}))}
                style={{width:"100%",padding:"8px 12px",border:`1px solid ${T.border}`,borderRadius:6,fontSize:13,color:T.text,outline:"none",fontFamily:"inherit",background:"#fff"}}>
                {taskCategories.map(c=><option key={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label style={{fontSize:11,fontWeight:600,color:T.muted,display:"block",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"}}>Frecuencia</label>
              <select value={newTask.freq} onChange={e=>setNewTask(p=>({...p,freq:e.target.value}))}
                style={{width:"100%",padding:"8px 12px",border:`1px solid ${T.border}`,borderRadius:6,fontSize:13,color:T.text,outline:"none",fontFamily:"inherit",background:"#fff"}}>
                {["Diario","3x semana","Días hábiles","Una vez","Semanal"].map(f=><option key={f}>{f}</option>)}
              </select>
            </div>
            <div>
              <label style={{fontSize:11,fontWeight:600,color:T.muted,display:"block",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"}}>Fecha límite</label>
              <input type="date" value={newTask.due} onChange={e=>setNewTask(p=>({...p,due:e.target.value}))}
                style={{width:"100%",padding:"8px 12px",border:`1px solid ${T.border}`,borderRadius:6,fontSize:13,color:T.text,outline:"none",fontFamily:"inherit",background:"#fff"}} />
            </div>
          </div>
          <div style={{marginBottom:12}}>
            <label style={{fontSize:11,fontWeight:600,color:T.muted,display:"block",marginBottom:4,textTransform:"uppercase",letterSpacing:"0.05em"}}>Descripción / instrucciones</label>
            <textarea value={newTask.desc} onChange={e=>setNewTask(p=>({...p,desc:e.target.value}))} rows={2}
              placeholder="Instrucciones detalladas para la jugadora..."
              style={{width:"100%",padding:"8px 12px",border:`1px solid ${T.border}`,borderRadius:6,fontSize:13,color:T.text,outline:"none",fontFamily:"inherit",resize:"vertical",boxSizing:"border-box",background:"#fff"}} />
          </div>
          <div style={{display:"flex",gap:8}}>
            <button onClick={addTask} style={{padding:"8px 18px",background:T.accent,color:"#fff",border:"none",borderRadius:6,fontWeight:600,fontSize:13,cursor:"pointer",fontFamily:"inherit"}}>Asignar a todo el equipo</button>
            <button onClick={()=>setShowForm(false)} style={{padding:"8px 14px",background:"#fff",border:`1px solid ${T.border}`,borderRadius:6,fontWeight:500,fontSize:13,cursor:"pointer",color:T.muted,fontFamily:"inherit"}}>Cancelar</button>
          </div>
        </PCard>
      )}

      <div style={{display:"grid",gridTemplateColumns:"1fr 320px",gap:20,alignItems:"start"}}>

        {/* Tasks list */}
        <div>
          {/* Category filter */}
          <div style={{display:"flex",gap:6,marginBottom:14}}>
            {["Todas",...taskCategories].map(cat=>(
              <button key={cat} onClick={()=>setFilterCat(cat)} style={{
                padding:"5px 14px",borderRadius:4,
                border:`1px solid ${filterCat===cat?(getCatColor(cat)||T.accent):T.border}`,
                background:filterCat===cat?((getCatColor(cat)||T.accent)+"14"):"#fff",
                color:filterCat===cat?(getCatColor(cat)||T.accent):T.muted,
                fontWeight:filterCat===cat?600:400,fontSize:12,
                cursor:"pointer",fontFamily:"inherit",transition:"all 0.12s"
              }}>{cat}</button>
            ))}
          </div>

          <div style={{display:"flex",flexDirection:"column",gap:10}}>
            {filteredTasks.map(t=>{
              const pct = taskCompPct(t.id);
              const catColor = getCatColor(t.category);
              return (
                <PCard key={t.id}>
                  <div style={{display:"flex",gap:16,alignItems:"flex-start"}}>
                    <div style={{
                      width:4,alignSelf:"stretch",borderRadius:4,flexShrink:0,
                      background:catColor,minHeight:60
                    }} />
                    <div style={{flex:1}}>
                      <div style={{display:"flex",alignItems:"center",gap:10,marginBottom:4}}>
                        <span style={{fontWeight:600,fontSize:14,color:T.text}}>{t.title}</span>
                        <PBadge text={t.category} color={catColor} variant="pill" />
                        <PBadge text={t.freq} />
                        {t.due && <span style={{fontSize:11,color:T.muted}}>Vence: {t.due}</span>}
                      </div>
                      <div style={{fontSize:12,color:T.muted,marginBottom:10}}>{t.desc}</div>
                      <div>
                        <div style={{display:"flex",justifyContent:"space-between",marginBottom:5}}>
                          <span style={{fontSize:11,fontWeight:600,color:T.muted,textTransform:"uppercase",letterSpacing:"0.05em"}}>Cumplimiento del equipo</span>
                          <span style={{fontSize:11,fontWeight:700,color:pct>=75?T.green:pct>=50?T.yellow:T.red}}>{pct}%</span>
                        </div>
                        <PProgress value={pct} max={100} color={pct>=75?T.green:pct>=50?T.yellow:T.red} height={5} />
                      </div>
                    </div>
                    <div style={{fontSize:11,fontWeight:700,color:catColor,background:`${catColor}12`,
                      borderRadius:4,padding:"4px 10px",flexShrink:0}}>{t.points} pts</div>
                  </div>
                </PCard>
              );
            })}
          </div>
        </div>

        {/* Player compliance panel */}
        <PCard>
          <PSectionHeader title="Cumplimiento por jugadora" />
          <div style={{display:"flex",flexDirection:"column",gap:6}}>
            {[...players].sort((a,b)=>playerTaskPct(b.id)-playerTaskPct(a.id)).map(p=>{
              const pct = playerTaskPct(p.id);
              const pctColor = pct>=80?T.green:pct>=60?T.yellow:T.red;
              return (
                <div key={p.id} onClick={()=>setSelectedPlayer(p)} style={{
                  display:"flex",alignItems:"center",gap:10,padding:"8px 10px",
                  borderRadius:6,cursor:"pointer",transition:"background 0.1s"
                }}
                onMouseEnter={e=>e.currentTarget.style.background=T.stripe}
                onMouseLeave={e=>e.currentTarget.style.background=""}
                >
                  <PAvatar initials={p.initials} color={posColorsP[p.pos]||T.accent} size={26} />
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:12,fontWeight:500,color:T.text,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>
                      #{p.num} {p.name}
                    </div>
                    <PProgress value={pct} max={100} color={pctColor} height={3} />
                  </div>
                  <span style={{fontSize:11,fontWeight:700,color:pctColor,minWidth:32,textAlign:"right"}}>{pct}%</span>
                </div>
              );
            })}
          </div>
        </PCard>
      </div>
    </div>
  );
}

window.ProTareas = ProTareas;
