// fichaje.eu — Screen: Inicio (employee dashboard)

const ScreenInicio = ({ onNav }) => {
  const [now, setNow] = React.useState(new Date());
  React.useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);

  // Pretend "today" started 09:02, with 12+45 = 57 min of breaks
  // For display, show 04:43 worked, with a live counter
  const workedH = 4, workedM = 43;
  const greet = now.getHours() < 13 ? 'Buenos días' : now.getHours() < 20 ? 'Buenas tardes' : 'Buenas noches';
  const todayStr = now.toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'long' });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* Hero row: greeting + fichaje widget */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
        <Card style={{ padding: 0, overflow: 'hidden', position: 'relative', background: 'linear-gradient(135deg, #1E3A8A 0%, #1E40AF 50%, #2563EB 100%)', border: 'none', color: '#fff' }}>
          <div style={{
            position: 'absolute', inset: 0, opacity: 0.18,
            backgroundImage: 'radial-gradient(circle at 20% 0%, #fff 0, transparent 40%), radial-gradient(circle at 95% 100%, #fff 0, transparent 35%)',
          }}/>
          <div style={{ position: 'relative', padding: '26px 28px' }}>
            <div style={{ fontSize: 13, fontWeight: 600, opacity: 0.85, textTransform: 'capitalize' }}>{todayStr}</div>
            <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.025em', marginTop: 4 }}>
              {greet}, {ME.name.split(' ')[0]}
            </div>
            <div style={{ fontSize: 14, opacity: 0.85, marginTop: 6, maxWidth: 460 }}>
              Hoy tienes una demo con BBVA Insurance a las 10:00 y una solicitud de vacaciones de Aitor pendiente de aprobar.
            </div>

            <div style={{
              display: 'flex', alignItems: 'center', gap: 18,
              marginTop: 22, paddingTop: 18,
              borderTop: '1px solid rgba(255,255,255,0.18)',
            }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '.08em' }}>Trabajado hoy</div>
                <div className="mono tnum" style={{ fontSize: 30, fontWeight: 700, marginTop: 2, letterSpacing: '-0.02em' }}>
                  {String(workedH).padStart(2,'0')}:{String(workedM).padStart(2,'0')}
                  <span style={{ fontSize: 14, fontWeight: 500, opacity: 0.6, marginLeft: 4 }}>/ 08:00</span>
                </div>
              </div>
              <Divider vertical style={{ background: 'rgba(255,255,255,0.18)' }}/>
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '.08em' }}>Entrada</div>
                <div className="mono" style={{ fontSize: 18, fontWeight: 600, marginTop: 4 }}>09:02</div>
              </div>
              <Divider vertical style={{ background: 'rgba(255,255,255,0.18)' }}/>
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '.08em' }}>Pausas</div>
                <div className="mono" style={{ fontSize: 18, fontWeight: 600, marginTop: 4 }}>57 min</div>
              </div>
              <div style={{ flex: 1 }}/>
              <button onClick={() => onNav('fichaje')} style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '11px 18px',
                background: 'rgba(255,255,255,0.14)',
                border: '1px solid rgba(255,255,255,0.25)',
                color: '#fff',
                borderRadius: 'var(--r-md)',
                fontSize: 14, fontWeight: 600,
                backdropFilter: 'blur(8px)',
              }}>
                <IPause size={15}/> Iniciar pausa
              </button>
              <button onClick={() => onNav('fichaje')} style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '11px 18px',
                background: '#fff', color: 'var(--brand-700)',
                borderRadius: 'var(--r-md)',
                fontSize: 14, fontWeight: 700,
              }}>
                <IStop size={15}/> Fichar salida
              </button>
            </div>
          </div>
        </Card>

        {/* Side cards: vacation + this week */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 12, color: 'var(--slate-500)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.06em' }}>Vacaciones</div>
                <div className="tnum" style={{ fontSize: 26, fontWeight: 700, marginTop: 6, letterSpacing: '-0.02em' }}>
                  {ME.vacationDays.total - ME.vacationDays.used} <span style={{ fontSize: 14, color: 'var(--slate-500)', fontWeight: 500 }}>/ {ME.vacationDays.total} días</span>
                </div>
              </div>
              <Btn variant="soft" size="sm" icon={<IPlus size={14}/>} onClick={() => onNav('ausencias')}>Solicitar</Btn>
            </div>
            <div style={{ marginTop: 14 }}>
              <ProgressBar value={ME.vacationDays.used} max={ME.vacationDays.total} color="var(--brand-600)" height={8}/>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 12, color: 'var(--slate-500)' }}>
                <span>{ME.vacationDays.used} usados</span>
                <span>Próxima: 11 ago — 22 ago</span>
              </div>
            </div>
          </Card>

          <Card>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
              <div style={{ fontSize: 12, color: 'var(--slate-500)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.06em' }}>Esta semana</div>
              <Badge tone="success" dot>+1h 14m de superávit</Badge>
            </div>
            <div style={{ display: 'flex', gap: 6, alignItems: 'flex-end', height: 64 }}>
              {[
                { d: 'L', v: 8.05, ok: true },
                { d: 'M', v: 7.83, ok: true },
                { d: 'X', v: 4.72, today: true },
                { d: 'J', v: 0, future: true },
                { d: 'V', v: 0, future: true },
                { d: 'S', v: 0, future: true, weekend: true },
                { d: 'D', v: 0, future: true, weekend: true },
              ].map((b, i) => {
                const h = Math.max(b.v / 9 * 100, b.future ? 4 : 8);
                const color = b.weekend ? 'var(--slate-150)' :
                              b.future ? 'var(--slate-200)' :
                              b.today ? 'var(--brand-500)' : 'var(--brand-200)';
                return (
                  <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                    <div style={{ width: '100%', height: 44, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
                      <div style={{
                        width: '100%', height: `${h}%`,
                        background: color, borderRadius: 4,
                        position: 'relative',
                      }}>
                        {b.today && (
                          <div style={{
                            position: 'absolute', top: -3, left: 0, right: 0, height: 3,
                            background: 'var(--brand-700)', borderRadius: '2px 2px 0 0',
                          }}/>
                        )}
                      </div>
                    </div>
                    <div style={{ fontSize: 11, fontWeight: b.today ? 700 : 500, color: b.today ? 'var(--brand-700)' : 'var(--slate-500)' }}>{b.d}</div>
                  </div>
                );
              })}
            </div>
          </Card>
        </div>
      </div>

      {/* Middle row: tablón + cumpleaños */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 18 }}>
        <Card>
          <SectionHead
            title="Tablón de anuncios"
            subtitle="Comunicados oficiales de la empresa"
            action={<button style={{ fontSize: 13, fontWeight: 600, color: 'var(--brand-600)' }}>Ver todos →</button>}
          />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[
              { tag: 'Importante', tone: 'danger', title: 'Cambios en el horario de verano', body: 'Del 1 de julio al 31 de agosto, jornada intensiva 8:00–15:00. La pausa de comida queda suspendida durante el periodo estival.', author: 'Núria Castells', time: 'hace 1 día', pinned: true },
              { tag: 'RRHH', tone: 'brand', title: 'Política de teletrabajo 2026 — firma requerida', body: 'Pendiente de tu firma en Mis documentos. Plazo hasta el 25 de mayo.', author: 'Helena Prats', time: 'hace 2 días' },
              { tag: 'Equipo', tone: 'success', title: '¡Damos la bienvenida a Mireia Solé!', body: 'Se incorpora al equipo de Implementación como Customer Success. Su onboarding empieza esta semana.', author: 'People Ops', time: '08 may' },
            ].map((post, i) => (
              <div key={i} style={{
                padding: '14px 16px',
                background: post.pinned ? 'var(--brand-50)' : 'var(--slate-50)',
                border: `1px solid ${post.pinned ? 'var(--brand-100)' : 'var(--slate-150)'}`,
                borderRadius: 'var(--r-md)',
                position: 'relative',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                  <Badge tone={post.tone} dot>{post.tag}</Badge>
                  {post.pinned && <span style={{ fontSize: 11, color: 'var(--brand-600)', fontWeight: 600 }}>📌 Fijado</span>}
                  <div style={{ flex: 1 }}/>
                  <span style={{ fontSize: 12, color: 'var(--slate-500)' }}>{post.time}</span>
                </div>
                <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)', marginBottom: 4 }}>{post.title}</div>
                <div style={{ fontSize: 13.5, color: 'var(--slate-600)', lineHeight: 1.5 }}>{post.body}</div>
                <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Avatar name={post.author} size={22}/>
                  <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--slate-700)' }}>{post.author}</span>
                </div>
              </div>
            ))}
          </div>
        </Card>

        {/* Right column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <Card>
            <SectionHead title="Cumpleaños y aniversarios" subtitle="Próximos 30 días"/>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {[
                { name: 'Sofía Marín',     when: 'Mañana · 14 may', detail: 'Cumple 32', type: 'birthday' },
                { name: 'Laia Boixader',   when: '19 may',          detail: 'Cumple 29', type: 'birthday' },
                { name: 'Pere Aguiló',     when: '26 may',          detail: 'Cumple 41', type: 'birthday' },
                { name: 'Iván Romero',     when: '02 jun',          detail: '2 años en la empresa', type: 'anniversary' },
              ].map((p, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <Avatar name={p.name} size={36}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>{p.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--slate-500)' }}>{p.detail}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: p.type === 'birthday' ? 'var(--pink-500)' : 'var(--brand-600)' }}>
                      {p.type === 'birthday' ? <IGift size={12} style={{ marginRight: 4, verticalAlign: 'middle' }}/> : <IAward size={12} style={{ marginRight: 4, verticalAlign: 'middle' }}/>}
                      {p.when}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          <Card>
            <SectionHead title="¿Quién está hoy?" subtitle={`${TEAM.filter(t => t.status === 'fichado').length} fichados · ${TEAM.filter(t => t.status === 'vacaciones').length} ausentes`}/>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {TEAM.slice(0, 9).map(p => (
                <div key={p.name} title={`${p.name} · ${p.status}`} style={{ position: 'relative' }}>
                  <Avatar name={p.name} size={32}/>
                  <span style={{
                    position: 'absolute', bottom: -1, right: -1,
                    width: 10, height: 10, borderRadius: 999,
                    border: '2px solid var(--white)',
                    background: p.status === 'fichado' ? 'var(--success-500)' :
                                p.status === 'pausa' ? 'var(--warning-500)' :
                                p.status === 'vacaciones' ? 'var(--brand-400)' :
                                'var(--slate-300)',
                  }}/>
                </div>
              ))}
              <div style={{
                width: 32, height: 32, borderRadius: 999,
                background: 'var(--slate-100)', color: 'var(--slate-600)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 11, fontWeight: 700,
              }}>+{TEAM.length - 9}</div>
            </div>
          </Card>
        </div>
      </div>

      {/* Bottom row: shortcuts */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 18 }}>
        {[
          { icon: <ICalendar size={18}/>, label: 'Solicitar ausencia',  tone: 'brand',   nav: 'ausencias' },
          { icon: <IPen size={18}/>,      label: 'Firmar documentos',   tone: 'violet',  nav: 'misdocs', badge: 1 },
          { icon: <ICheckSquare size={18}/>, label: 'Mis tareas',       tone: 'success', nav: 'tareas' },
          { icon: <IUsers size={18}/>,    label: 'Directorio',          tone: 'warning', nav: 'organizacion' },
        ].map((s, i) => (
          <Card key={i} hoverable onClick={() => onNav(s.nav)} style={{ padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{
                width: 38, height: 38, borderRadius: 'var(--r-md)',
                background: `var(--${s.tone === 'violet' ? 'violet-100' : s.tone+'-50'})`,
                color: `var(--${s.tone === 'violet' ? 'violet-500' : s.tone+'-600'})`,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}>{s.icon}</div>
              <div style={{ flex: 1, fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{s.label}</div>
              {s.badge && <Badge tone="danger">{s.badge}</Badge>}
              <IChevronRight size={16} style={{ color: 'var(--slate-400)' }}/>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
};

Object.assign(window, { ScreenInicio });
