// fichaje.eu — Screen: Protocolos (admin dashboards with charts)

const ScreenProtocolos = () => {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 13, color: 'var(--slate-500)' }}>Mayo 2026 · IABusiness.es</div>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', marginTop: 2 }}>Cuadro de mando</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Tabs tabs={[{value:'mes',label:'Mes'},{value:'tri',label:'Trimestre'},{value:'año',label:'Año'}]} value="mes" onChange={()=>{}}/>
          <Btn variant="secondary" size="sm" icon={<IDownload size={14}/>}>Exportar informe</Btn>
        </div>
      </div>

      {/* Top KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <Stat label="Horas totales" value="3.847" delta="+8.2% vs abr" tone="brand" icon={<IClock size={18}/>}/>
        <Stat label="Tasa de absentismo" value="2.1%" delta="-0.4 pp" tone="success" icon={<ITrending size={18}/>}/>
        <Stat label="Horas extra" value="42h" delta="+12h vs abr" tone="warning" icon={<IZap size={18}/>}/>
        <Stat label="Productividad media" value="98.3%" delta="vs jornada prevista" tone="violet" icon={<ICheck size={18}/>}/>
      </div>

      {/* Chart row 1: hours over time + breakdown by team */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.7fr 1fr', gap: 18 }}>
        <Card>
          <SectionHead title="Horas trabajadas por día" subtitle="Últimas 4 semanas · todas las personas" action={<Badge tone="success" dot>+8.2% vs mes anterior</Badge>}/>
          <LineChart/>
        </Card>
        <Card>
          <SectionHead title="Distribución por equipo" subtitle="Mayo 2026"/>
          <DonutChart/>
          <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 9 }}>
            {[
              { l: 'Plataforma',     v: '1.140h', p: 29.6, c: 'var(--brand-600)' },
              { l: 'Implementación', v: '980h',   p: 25.5, c: 'var(--brand-400)' },
              { l: 'Comercial',      v: '720h',   p: 18.7, c: 'var(--violet-500)' },
              { l: 'Marketing',      v: '512h',   p: 13.3, c: 'var(--success-500)' },
              { l: 'RRHH y Dirección', v: '495h', p: 12.9, c: 'var(--warning-500)' },
            ].map((t, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13 }}>
                <span style={{ width: 10, height: 10, borderRadius: 3, background: t.c }}/>
                <span style={{ flex: 1, color: 'var(--slate-700)' }}>{t.l}</span>
                <span className="mono tnum" style={{ fontWeight: 600, color: 'var(--ink)' }}>{t.v}</span>
                <span style={{ color: 'var(--slate-500)', width: 44, textAlign: 'right' }}>{t.p}%</span>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Chart row 2: absences pie + heatmap */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.5fr', gap: 18 }}>
        <Card>
          <SectionHead title="Causas de ausencia" subtitle="Últimos 30 días"/>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {[
              { l: 'Vacaciones', v: 38, p: 64,  c: 'var(--brand-500)' },
              { l: 'Asuntos propios', v: 9, p: 15, c: 'var(--violet-500)' },
              { l: 'Médico', v: 7, p: 12,        c: 'var(--warning-500)' },
              { l: 'Formación', v: 4, p: 7,      c: 'var(--success-500)' },
              { l: 'Otros', v: 1, p: 2,          c: 'var(--slate-400)' },
            ].map((row, i) => (
              <div key={i}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 5 }}>
                  <span style={{ fontSize: 13, color: 'var(--slate-700)', fontWeight: 600 }}>{row.l}</span>
                  <span style={{ fontSize: 12, color: 'var(--slate-500)' }} className="mono tnum"><strong style={{ color: 'var(--ink)' }}>{row.v}</strong> días · {row.p}%</span>
                </div>
                <ProgressBar value={row.p} color={row.c} height={8}/>
              </div>
            ))}
          </div>
        </Card>

        <Card>
          <SectionHead title="Patrón de fichaje" subtitle="Concentración de entradas y salidas por hora"/>
          <Heatmap/>
        </Card>
      </div>

      {/* Bottom: protocols & alerts */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 18 }}>
        <Card>
          <SectionHead title="Protocolos vigentes" subtitle="Documentos clave de funcionamiento interno" action={<Btn variant="secondary" size="sm" icon={<IPlus size={13}/>}>Nuevo protocolo</Btn>}/>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
            {[
              { t: 'Protocolo de fichaje', d: 'Reglas de pausas, comida y horario flexible.', sig: 24, due: '—', v: 'v3.1' },
              { t: 'Política de teletrabajo 2026', d: 'Días de remoto, gastos, equipo informático.', sig: 23, due: '1 pendiente', v: 'v2.1' },
              { t: 'Onboarding nuevo empleado', d: 'Checklist completo de primeras 2 semanas.', sig: 24, due: '—', v: 'v4.0' },
              { t: 'Prevención de riesgos laborales', d: 'Evaluación anual obligatoria de PRL.', sig: 22, due: '2 pendientes', v: 'v1.2' },
              { t: 'GDPR y tratamiento de datos', d: 'Política de privacidad y compliance.', sig: 24, due: '—', v: 'v2.0' },
              { t: 'Uso responsable de IA', d: 'Política interna para empleados.', sig: 18, due: '6 pendientes', v: 'v1.0' },
            ].map((p, i) => (
              <div key={i} style={{ padding: 14, border: '1px solid var(--slate-150)', borderRadius: 'var(--r-md)', background: 'var(--paper)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 700 }}>{p.t}</div>
                  <Badge tone="slate" style={{ fontSize: 10.5 }}>{p.v}</Badge>
                </div>
                <div style={{ fontSize: 12, color: 'var(--slate-600)', lineHeight: 1.5, marginBottom: 10, minHeight: 32 }}>{p.d}</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12 }}>
                  <span style={{ color: 'var(--slate-500)' }}>{p.sig}/24 firmados</span>
                  {p.due !== '—' ? <Badge tone="warning" dot>{p.due}</Badge> : <Badge tone="success" dot>Completo</Badge>}
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Card>
          <SectionHead title="Alertas y avisos" action={<Badge tone="warning" dot>3 activas</Badge>}/>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              { t: 'Dani Esteve · 47h trabajadas esta semana', s: 'Por encima del límite (45h)', tone: 'danger', i: <IFlag size={14}/> },
              { t: '6 personas no han firmado "Uso responsable de IA"', s: 'Plazo vence el 25 may', tone: 'warning', i: <IPen size={14}/> },
              { t: 'Berta Folch · vacaciones solapan con cierre Q2', s: 'Revisar antes de aprobar', tone: 'warning', i: <ICalendar size={14}/> },
            ].map((a, i) => (
              <div key={i} style={{ padding: 12, background: a.tone === 'danger' ? 'var(--danger-50)' : 'var(--warning-50)', border: `1px solid ${a.tone === 'danger' ? 'var(--danger-100)' : 'var(--warning-100)'}`, borderRadius: 'var(--r-md)' }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
                  <div style={{ color: a.tone === 'danger' ? 'var(--danger-600)' : 'var(--warning-600)', marginTop: 1 }}>{a.i}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{a.t}</div>
                    <div style={{ fontSize: 12, color: 'var(--slate-600)', marginTop: 2 }}>{a.s}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
};

// Line chart: 28 days of total hours
const LineChart = () => {
  // Generate plausible data
  const data = [];
  for (let i = 0; i < 28; i++) {
    const dow = i % 7;
    const isWeekend = dow >= 5;
    const base = isWeekend ? 12 : 175;
    const v = base + (Math.sin(i * 0.6) * 15) + (Math.cos(i * 1.1) * 8);
    data.push({ x: i, v: Math.max(0, v), weekend: isWeekend });
  }
  const max = Math.max(...data.map(d => d.v));
  const W = 600, H = 200;
  const pts = data.map((d, i) => `${(i / (data.length - 1)) * W},${H - (d.v / max) * H}`).join(' ');
  return (
    <div style={{ position: 'relative', width: '100%', overflow: 'hidden' }}>
      <svg viewBox={`0 0 ${W} ${H + 40}`} width="100%" style={{ display: 'block' }}>
        {/* Grid */}
        {[0, 0.25, 0.5, 0.75, 1].map(g => (
          <line key={g} x1="0" x2={W} y1={H - g * H} y2={H - g * H} stroke="var(--slate-100)" strokeDasharray="3,3"/>
        ))}
        {/* Weekend bands */}
        {data.map((d, i) => d.weekend && (
          <rect key={i} x={(i / (data.length - 1)) * W - (W/data.length/2)} y={0} width={W / data.length} height={H} fill="var(--slate-50)" opacity="0.6"/>
        ))}
        {/* Area */}
        <defs>
          <linearGradient id="area" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#1E40AF" stopOpacity="0.22"/>
            <stop offset="100%" stopColor="#1E40AF" stopOpacity="0"/>
          </linearGradient>
        </defs>
        <polygon fill="url(#area)" points={`0,${H} ${pts} ${W},${H}`}/>
        {/* Line */}
        <polyline points={pts} fill="none" stroke="#1E40AF" strokeWidth="2"/>
        {/* Dots — every 7th day */}
        {data.filter((_, i) => i % 7 === 3).map((d, i) => {
          const idx = data.indexOf(d);
          const x = (idx / (data.length - 1)) * W;
          const y = H - (d.v / max) * H;
          return <circle key={i} cx={x} cy={y} r="3.5" fill="#1E40AF" stroke="#fff" strokeWidth="2"/>;
        })}
        {/* X labels — weeks */}
        {['Sem 17', 'Sem 18', 'Sem 19', 'Sem 20'].map((l, i) => (
          <text key={i} x={(i * 7 + 3.5) / (data.length - 1) * W} y={H + 24} fill="var(--slate-500)" fontSize="11" fontWeight="600" textAnchor="middle" fontFamily="var(--font-sans)">{l}</text>
        ))}
      </svg>
    </div>
  );
};

const DonutChart = () => {
  const data = [
    { v: 29.6, c: '#1E40AF' },
    { v: 25.5, c: '#3B82F6' },
    { v: 18.7, c: '#8B5CF6' },
    { v: 13.3, c: '#10B981' },
    { v: 12.9, c: '#F59E0B' },
  ];
  let acc = 0;
  const segs = data.map(d => {
    const s = acc; acc += d.v;
    return { s, e: acc, c: d.c };
  });
  const R = 70, r = 44, cx = 90, cy = 90;
  const toXY = (p) => {
    const a = (p / 100) * 2 * Math.PI - Math.PI / 2;
    return [cx + Math.cos(a) * R, cy + Math.sin(a) * R];
  };
  const innerXY = (p) => {
    const a = (p / 100) * 2 * Math.PI - Math.PI / 2;
    return [cx + Math.cos(a) * r, cy + Math.sin(a) * r];
  };
  return (
    <div style={{ display: 'flex', justifyContent: 'center' }}>
      <svg width="180" height="180" viewBox="0 0 180 180">
        {segs.map((s, i) => {
          const [x1, y1] = toXY(s.s);
          const [x2, y2] = toXY(s.e);
          const [ix2, iy2] = innerXY(s.e);
          const [ix1, iy1] = innerXY(s.s);
          const large = s.e - s.s > 50 ? 1 : 0;
          return (
            <path key={i} d={`M ${x1} ${y1} A ${R} ${R} 0 ${large} 1 ${x2} ${y2} L ${ix2} ${iy2} A ${r} ${r} 0 ${large} 0 ${ix1} ${iy1} Z`}
              fill={s.c} stroke="#fff" strokeWidth="2"/>
          );
        })}
        <text x={cx} y={cy - 4} textAnchor="middle" fontSize="22" fontWeight="700" fill="var(--ink)" fontFamily="var(--font-sans)">3.847</text>
        <text x={cx} y={cy + 14} textAnchor="middle" fontSize="11" fill="var(--slate-500)" fontFamily="var(--font-sans)">horas totales</text>
      </svg>
    </div>
  );
};

const Heatmap = () => {
  const hours = ['07','08','09','10','11','12','13','14','15','16','17','18','19','20'];
  const days = ['L','M','X','J','V'];
  // Intensity pattern: peaks around 9 entry and 13/14 break and 17/18 exit
  const intensity = (d, h) => {
    let v = 0.1;
    if (h === 8) v = 0.5;
    if (h === 9) v = 1.0;
    if (h === 10) v = 0.4;
    if (h === 11) v = 0.2;
    if (h === 12) v = 0.3;
    if (h === 13) v = 0.7;
    if (h === 14) v = 0.55;
    if (h === 15) v = 0.2;
    if (h === 16) v = 0.3;
    if (h === 17) v = 0.65;
    if (h === 18) v = 0.85;
    if (h === 19) v = 0.3;
    if (h === 20) v = 0.08;
    if (d === 4 && h >= 17) v *= 0.7; // Friday earlier exits
    return v;
  };
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: `28px repeat(${hours.length}, 1fr)`, gap: 4 }}>
        <div></div>
        {hours.map(h => (
          <div key={h} style={{ fontSize: 10.5, color: 'var(--slate-500)', textAlign: 'center', fontWeight: 600 }}>{h}</div>
        ))}
        {days.map((d, di) => (
          <React.Fragment key={d}>
            <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--slate-600)', display: 'flex', alignItems: 'center' }}>{d}</div>
            {hours.map((h, hi) => {
              const v = intensity(di, parseInt(h));
              return (
                <div key={hi} style={{
                  aspectRatio: '1',
                  background: `rgba(30,64,175,${v})`,
                  borderRadius: 4,
                }}/>
              );
            })}
          </React.Fragment>
        ))}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 12, fontSize: 11, color: 'var(--slate-500)' }}>
        Menor
        <div style={{ display: 'flex', gap: 2 }}>
          {[0.1, 0.3, 0.5, 0.7, 0.9].map(v => (
            <div key={v} style={{ width: 14, height: 14, borderRadius: 3, background: `rgba(30,64,175,${v})` }}/>
          ))}
        </div>
        Mayor
      </div>
    </div>
  );
};

Object.assign(window, { ScreenProtocolos });
