// ===== Asistencia / Reloj de empleados =====
function Asistencia({ attendance, setAttendance, currentUser, users }){
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(()=>{ const id = setInterval(()=>setNow(Date.now()), 1000); return ()=>clearInterval(id); }, []);

  // open session = record with no out
  const openByUser = (uid) => attendance.find(r => r.userId===uid && !r.out);
  const myOpen = openByUser(currentUser.techId);

  function clockIn(uid){
    if(openByUser(uid)) return;
    setAttendance(prev => [{ id:"at_"+Date.now(), userId:uid, in:new Date().toISOString(), out:null }, ...prev]);
  }
  function clockOut(uid){
    setAttendance(prev => prev.map(r => (r.userId===uid && !r.out) ? { ...r, out:new Date().toISOString() } : r));
  }

  const today = new Date();
  const isAdmin = currentUser.roleId === "admin";
  const staff = users.filter(u=>u.active);
  const myUser = users.find(u=>u.id===currentUser.techId) || { id:currentUser.techId, name:currentUser.name, initials:currentUser.initials, hue:currentUser.hue||256 };

  // today's hours per active session for live ticking
  const t = new Date(now);
  const clockStr = t.toLocaleTimeString("es-ES",{ hour:"2-digit", minute:"2-digit", second:"2-digit" });
  const dateStr = t.toLocaleDateString("es-ES",{ weekday:"long", day:"numeric", month:"long" });

  // week summary per employee
  const weekStart = new Date(); weekStart.setDate(weekStart.getDate()-6); weekStart.setHours(0,0,0,0);
  const weekRecords = attendance.filter(r => new Date(r.in) >= weekStart);
  const presentToday = staff.filter(u => attendance.some(r => r.userId===u.id && sameDay(r.in, today)));

  // Privacidad: empleados solo ven SUS datos; el admin ve a todo el personal.
  const visibleStaff = isAdmin ? staff : staff.filter(u => u.id===currentUser.techId);
  const myTodayHours = attendance.filter(r=>r.userId===currentUser.techId && sameDay(r.in, today)).reduce((s,r)=>s+attHours(r),0);
  const baseLog = isAdmin ? attendance : attendance.filter(r => r.userId===currentUser.techId);
  const recentLog = [...baseLog].sort((a,b)=> new Date(b.in)-new Date(a.in)).slice(0, 12);

  return (
    <div style={{ display:"flex", flexDirection:"column", gap:16, animation:"fadeUp .35s ease" }}>
      {/* clock hero + my punch */}
      <div style={{ display:"grid", gridTemplateColumns:"1.1fr 1fr", gap:16 }}>
        <Card style={{ display:"flex", flexDirection:"column", justifyContent:"center", background:"linear-gradient(135deg, var(--accent-soft), var(--surface))", borderColor:"oklch(0.85 0.06 256)" }}>
          <div style={{ fontSize:13, fontWeight:600, color:"var(--accent-ink)", textTransform:"capitalize" }}>{dateStr}</div>
          <div className="mono" style={{ fontSize:52, fontWeight:800, letterSpacing:"-0.02em", lineHeight:1.1, color:"var(--ink)" }}>{clockStr}</div>
          <div style={{ display:"flex", alignItems:"center", gap:8, marginTop:8, fontSize:13.5, color:"var(--muted)" }}>
            <Icon name="clock" size={16} /> {isAdmin
              ? `${presentToday.length} de ${staff.length} empleados presentes hoy`
              : `Tu tiempo de hoy: ${fmtHours(myTodayHours)}`}
          </div>
        </Card>

        <Card style={{ display:"flex", flexDirection:"column", justifyContent:"center" }}>
          <div style={{ display:"flex", alignItems:"center", gap:12, marginBottom:16 }}>
            <Avatar name={currentUser.name} initials={currentUser.initials} hue={currentUser.hue||256} size={46} />
            <div>
              <div style={{ fontSize:15, fontWeight:700 }}>{currentUser.name}</div>
              <div style={{ fontSize:12.5, color:"var(--muted)" }}>{myOpen ? `Entrada ${fmtClock(myOpen.in)} · ${fmtHours(attHours(myOpen))} trabajadas` : "Sin fichar hoy"}</div>
            </div>
          </div>
          {myOpen ? (
            <Btn variant="danger" size="lg" icon="logout" style={{ width:"100%" }} onClick={()=>clockOut(currentUser.techId)}>Marcar salida</Btn>
          ) : (
            <Btn size="lg" icon="clock" style={{ width:"100%" }} onClick={()=>clockIn(currentUser.techId)}>Marcar entrada</Btn>
          )}
        </Card>
      </div>

      {/* staff status grid — solo el administrador ve a todo el personal */}
      {isAdmin && (
      <Card pad={0}>
        <div style={{ padding:"16px 20px", borderBottom:"1px solid var(--line)" }}>
          <h3 style={{ fontSize:15.5, fontWeight:700, margin:0 }}>Estado del personal</h3>
          <p style={{ fontSize:12.5, color:"var(--muted)", margin:"3px 0 0" }}>Ficha la entrada/salida de cualquier empleado</p>
        </div>
        <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(280px, 1fr))", gap:12, padding:16 }}>
          {visibleStaff.map(u=>{
            const open = openByUser(u.id);
            const todayRec = attendance.filter(r=>r.userId===u.id && sameDay(r.in, today));
            const todayHours = todayRec.reduce((s,r)=>s+attHours(r),0);
            return (
              <div key={u.id} style={{ border:"1px solid var(--line)", borderRadius:12, padding:14, background: open?"var(--st-listo-soft)":"var(--surface)" }}>
                <div style={{ display:"flex", alignItems:"center", gap:11, marginBottom:12 }}>
                  <div style={{ position:"relative" }}>
                    <Avatar name={u.name} initials={u.initials} hue={u.hue} size={40} />
                    <span style={{ position:"absolute", bottom:-1, right:-1, width:12, height:12, borderRadius:"50%", background: open?"var(--st-listo)":"var(--faint)", border:"2px solid var(--surface)" }} />
                  </div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:14, fontWeight:700, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>{u.name}</div>
                    <div style={{ fontSize:12, fontWeight:600, color: open?"var(--st-listo)":"var(--muted)" }}>
                      {open ? `En turno · ${fmtHours(attHours(open))}` : todayHours>0 ? `Hoy: ${fmtHours(todayHours)}` : "Fuera"}
                    </div>
                  </div>
                </div>
                {open ? (
                  <Btn variant="secondary" size="sm" icon="logout" style={{ width:"100%" }} onClick={()=>clockOut(u.id)}>Salida {fmtClock(open.in)} →</Btn>
                ) : (
                  <Btn variant="soft" size="sm" icon="clock" style={{ width:"100%" }} onClick={()=>clockIn(u.id)}>Marcar entrada</Btn>
                )}
              </div>
            );
          })}
        </div>
      </Card>
      )}

      <div style={{ display:"grid", gridTemplateColumns:"1fr 1.3fr", gap:16, alignItems:"start" }}>
        {/* week hours */}
        <Card>
          <h3 style={{ fontSize:15.5, fontWeight:700, margin:"0 0 4px" }}>{isAdmin ? "Horas esta semana" : "Mis horas esta semana"}</h3>
          <p style={{ fontSize:12.5, color:"var(--muted)", margin:"0 0 16px" }}>Últimos 7 días</p>
          <div style={{ display:"flex", flexDirection:"column", gap:13 }}>
            {visibleStaff.map(u=>{
              const h = weekRecords.filter(r=>r.userId===u.id).reduce((s,r)=>s+attHours(r),0);
              const pct = Math.min(100, (h/40)*100);
              return (
                <div key={u.id} style={{ display:"flex", alignItems:"center", gap:11 }}>
                  <Avatar name={u.name} initials={u.initials} hue={u.hue} size={30} />
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ display:"flex", justifyContent:"space-between", fontSize:12.5, marginBottom:4 }}>
                      <span style={{ fontWeight:600 }}>{u.name.split(" ")[0]} {u.name.split(" ")[1]?.[0]}.</span>
                      <span className="mono" style={{ fontWeight:700, color:"var(--ink-2)" }}>{fmtHours(h)}</span>
                    </div>
                    <div style={{ height:6, borderRadius:99, background:"var(--line-2)", overflow:"hidden" }}>
                      <div style={{ width:`${pct}%`, height:"100%", borderRadius:99, background:`oklch(0.6 0.12 ${u.hue})` }} />
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>

        {/* recent punches */}
        <Card pad={0}>
          <div style={{ padding:"16px 20px", borderBottom:"1px solid var(--line)" }}>
            <h3 style={{ fontSize:15.5, fontWeight:700, margin:0 }}>{isAdmin ? "Registro de marcas" : "Mis marcas"}</h3>
          </div>
          <div>
            {recentLog.map((r,i)=>{
              const u = users.find(x=>x.id===r.userId) || getTech(r.userId) || { name:"—", initials:"?", hue:256 };
              return (
                <div key={r.id} style={{ display:"flex", alignItems:"center", gap:12, padding:"11px 20px", borderBottom: i<recentLog.length-1?"1px solid var(--line-2)":"none" }}>
                  <Avatar name={u.name} initials={u.initials} hue={u.hue} size={32} />
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:13.5, fontWeight:600 }}>{u.name}</div>
                    <div style={{ fontSize:12, color:"var(--muted)" }}>{sameDay(r.in)?"Hoy":fmtDate(r.in)}</div>
                  </div>
                  <div style={{ display:"flex", alignItems:"center", gap:10, fontSize:12.5 }}>
                    <span style={{ display:"inline-flex", alignItems:"center", gap:5, color:"var(--st-listo)", fontWeight:600 }}><Icon name="arrowRight" size={13} style={{ transform:"rotate(-45deg)" }} /> {fmtClock(r.in)}</span>
                    {r.out
                      ? <span style={{ display:"inline-flex", alignItems:"center", gap:5, color:"var(--danger)", fontWeight:600 }}><Icon name="arrowRight" size={13} style={{ transform:"rotate(135deg)" }} /> {fmtClock(r.out)}</span>
                      : <span style={{ padding:"2px 9px", borderRadius:99, background:"var(--st-listo-soft)", color:"var(--st-listo)", fontWeight:700, fontSize:11.5 }}>En turno</span>}
                    <span className="mono" style={{ width:56, textAlign:"right", fontWeight:700, color:"var(--ink-2)" }}>{fmtHours(attHours(r))}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { Asistencia });
