// fichaje.eu — Screen: Ausencias (vacation/absence request + approvals)

const ScreenAusencias = ({ role }) => {
  const [tab, setTab] = React.useState('mis');
  const [reqOpen, setReqOpen] = React.useState(false);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* Balance summary */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <Stat label="Vacaciones disponibles" value={`${ME.vacationDays.total - ME.vacationDays.used} d`} delta="+0.5 acumulados/mes" tone="brand" icon={<ICalendar size={18}/>}/>
        <Stat label="Vacaciones usadas" value={`${ME.vacationDays.used} d`} tone="violet" icon={<ICheck size={18}/>}/>
        <Stat label="Asuntos propios" value="3 / 4 d" tone="success" icon={<IFlag size={18}/>}/>
        <Stat label="Bajas médicas" value="0.5 d" tone="warning" icon={<IShield size={18}/>}/>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: role === 'admin' ? '1fr 380px' : '1.4fr 1fr', gap: 18 }}>
        <Card>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
            <Tabs tabs={[
              { value: 'mis',   label: 'Mis ausencias' },
              ...(role === 'admin' ? [{ value: 'equipo', label: `Pendientes de aprobar (${TEAM_ABSENCE_REQUESTS.length})` }] : []),
              { value: 'cal',   label: 'Calendario del equipo' },
            ]} value={tab} onChange={setTab}/>
            <Btn variant="primary" size="sm" icon={<IPlus size={14}/>} onClick={() => setReqOpen(true)}>Solicitar ausencia</Btn>
          </div>

          {tab === 'mis' && (
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 80px 1fr 110px 32px', padding: '10px 12px', fontSize: 11.5, fontWeight: 700, color: 'var(--slate-500)', textTransform: 'uppercase', letterSpacing: '.06em', borderBottom: '1px solid var(--slate-150)' }}>
                <div>Tipo</div><div>Periodo</div><div>Días</div><div>Aprobador</div><div>Estado</div><div></div>
              </div>
              {MY_ABSENCES.map(a => (
                <div key={a.id} style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 80px 1fr 110px 32px', padding: '14px 12px', borderBottom: '1px solid var(--slate-100)', alignItems: 'center', fontSize: 14 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{
                      width: 32, height: 32, borderRadius: 'var(--r-sm)',
                      background: a.type === 'Vacaciones' ? 'var(--brand-50)' : a.type === 'Médico' ? 'var(--warning-50)' : 'var(--violet-100)',
                      color: a.type === 'Vacaciones' ? 'var(--brand-600)' : a.type === 'Médico' ? 'var(--warning-600)' : '#6D28D9',
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    }}>{a.type === 'Vacaciones' ? <ICalendar size={15}/> : a.type === 'Médico' ? <IShield size={15}/> : <IFlag size={15}/>}</div>
                    <span style={{ fontWeight: 600 }}>{a.type}</span>
                  </div>
                  <div style={{ color: 'var(--slate-700)' }}>{a.range}</div>
                  <div className="mono tnum" style={{ fontWeight: 600 }}>{a.days}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Avatar name={a.approver} size={22}/>
                    <span style={{ fontSize: 13, color: 'var(--slate-700)' }}>{a.approver.split(' ')[0]}</span>
                  </div>
                  <div><Badge tone={a.status === 'aprobada' ? 'success' : a.status === 'pendiente' ? 'warning' : 'danger'} dot>{a.status}</Badge></div>
                  <button style={{ color: 'var(--slate-400)', padding: 4 }}><IMoreH size={16}/></button>
                </div>
              ))}
            </div>
          )}

          {tab === 'equipo' && role === 'admin' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {TEAM_ABSENCE_REQUESTS.map(r => (
                <div key={r.id} style={{
                  padding: 16, border: '1px solid var(--slate-150)', borderRadius: 'var(--r-md)',
                  display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 14, alignItems: 'center',
                  background: 'var(--paper)',
                }}>
                  <Avatar name={r.name} size={40}/>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>{r.name}</div>
                    <div style={{ fontSize: 13, color: 'var(--slate-600)', marginTop: 2 }}>
                      <Badge tone="brand">{r.type}</Badge> · {r.range} · <span style={{ fontWeight: 600 }}>{r.days} días</span>
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--slate-500)', marginTop: 4 }}>Solicitado {r.requested}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 8 }}>
                    <Btn variant="secondary" size="sm" icon={<IX size={14}/>} onClick={async () => {
                      if (!window.api || !r.id) return;
                      await window.api.decideVacation(r.id, 'rechazado');
                      await window.api.reloadBootstrap();
                      window.location.reload();
                    }}>Rechazar</Btn>
                    <Btn variant="success" size="sm" icon={<ICheck size={14}/>} onClick={async () => {
                      if (!window.api || !r.id) return;
                      await window.api.decideVacation(r.id, 'aprobado');
                      await window.api.reloadBootstrap();
                      window.location.reload();
                    }}>Aprobar</Btn>
                  </div>
                </div>
              ))}
            </div>
          )}

          {tab === 'cal' && (
            <TeamTimeline/>
          )}
        </Card>

        <Card>
          <SectionHead title="¿Quién está fuera?" subtitle="Hoy y próxima semana"/>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[
              { name: 'Aitor Llopis', type: 'Vacaciones', range: 'Hasta el 22 may', tone: 'brand' },
              { name: 'Pere Aguiló',  type: 'Asuntos propios', range: '20 may',     tone: 'violet' },
              { name: 'Berta Folch',  type: 'Vacaciones (pdte)', range: '07 jul → 25 jul', tone: 'warning' },
            ].map((p, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', background: 'var(--slate-50)', borderRadius: 'var(--r-md)' }}>
                <Avatar name={p.name} size={32}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600 }}>{p.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--slate-500)' }}>{p.range}</div>
                </div>
                <Badge tone={p.tone}>{p.type}</Badge>
              </div>
            ))}
          </div>

          <Divider style={{ margin: '18px 0' }}/>

          <SectionHead title="Política de ausencias"/>
          <div style={{ fontSize: 13, color: 'var(--slate-600)', lineHeight: 1.55, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ display: 'flex', gap: 8 }}>
              <span style={{ color: 'var(--brand-600)' }}>•</span>
              <span><strong>23 días</strong> de vacaciones anuales + 4 de asuntos propios.</span>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <span style={{ color: 'var(--brand-600)' }}>•</span>
              <span>Solicitudes con <strong>15 días de antelación</strong> mínimo.</span>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <span style={{ color: 'var(--brand-600)' }}>•</span>
              <span>Aprobación por <strong>manager directo</strong> y RRHH.</span>
            </div>
          </div>
        </Card>
      </div>

      {reqOpen && <RequestAbsenceModal onClose={() => setReqOpen(false)}/>}
    </div>
  );
};

const TeamTimeline = () => {
  const days = Array.from({ length: 21 }, (_, i) => i + 11); // 11–31 May
  const people = [
    { name: 'Marc Vives',    blocks: [] },
    { name: 'Aitor Llopis',  blocks: [{ s: 0, e: 12, type: 'vacation' }] },
    { name: 'Pere Aguiló',   blocks: [{ s: 9, e: 11, type: 'personal' }] },
    { name: 'Berta Folch',   blocks: [] },
    { name: 'Mireia Solé',   blocks: [{ s: 4, e: 5, type: 'medical' }] },
    { name: 'Sofía Marín',   blocks: [] },
    { name: 'Iván Romero',   blocks: [{ s: 16, e: 18, type: 'vacation' }] },
    { name: 'Joel Vidal',    blocks: [] },
  ];
  const colors = {
    vacation: ['var(--brand-100)', 'var(--brand-700)'],
    personal: ['var(--violet-100)', '#6D28D9'],
    medical:  ['var(--warning-100)', 'var(--warning-600)'],
  };
  return (
    <div style={{ overflow: 'auto' }}>
      <div style={{ minWidth: 700 }}>
        <div style={{ display: 'grid', gridTemplateColumns: `140px repeat(${days.length}, 1fr)`, marginBottom: 6 }}>
          <div></div>
          {days.map(d => (
            <div key={d} style={{ textAlign: 'center', fontSize: 10.5, fontWeight: 600, color: d === 13 ? 'var(--brand-600)' : 'var(--slate-500)', padding: '4px 0' }}>{d}</div>
          ))}
        </div>
        {people.map(p => (
          <div key={p.name} style={{ display: 'grid', gridTemplateColumns: `140px repeat(${days.length}, 1fr)`, alignItems: 'center', padding: '6px 0', borderTop: '1px solid var(--slate-100)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, paddingRight: 8 }}>
              <Avatar name={p.name} size={24}/>
              <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--slate-700)' }}>{p.name.split(' ')[0]}</span>
            </div>
            <div style={{ position: 'relative', gridColumn: `2 / span ${days.length}`, height: 22 }}>
              <div style={{ display: 'grid', gridTemplateColumns: `repeat(${days.length}, 1fr)`, position: 'absolute', inset: 0 }}>
                {days.map((d, i) => (
                  <div key={d} style={{ borderLeft: i ? '1px dashed var(--slate-100)' : 'none', background: d === 13 ? 'var(--brand-50)' : 'transparent' }}/>
                ))}
              </div>
              {p.blocks.map((b, i) => (
                <div key={i} style={{
                  position: 'absolute',
                  left: `${(b.s / days.length) * 100}%`,
                  width: `${((b.e - b.s + 1) / days.length) * 100}%`,
                  top: 2, bottom: 2,
                  background: colors[b.type][0], color: colors[b.type][1],
                  borderRadius: 'var(--r-sm)',
                  fontSize: 11, fontWeight: 600,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  border: `1px solid ${colors[b.type][1]}40`,
                }}>{b.type === 'vacation' ? 'Vacaciones' : b.type === 'personal' ? 'Personal' : 'Médico'}</div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

const RequestAbsenceModal = ({ onClose }) => {
  const [type, setType] = React.useState('Vacaciones');
  const [from, setFrom] = React.useState('2026-08-11');
  const [to, setTo] = React.useState('2026-08-22');
  const [reason, setReason] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const submit = async () => {
    if (!window.api) return;
    setBusy(true); setErr('');
    try {
      const kindMap = { 'Vacaciones': 'vacaciones', 'Asuntos propios': 'personal', 'Médico': 'medico', 'Otros': 'otros' };
      const r = await window.api.requestVacation({
        kind: kindMap[type] || 'vacaciones',
        start_date: from, end_date: to, note: reason, days_workdays: businessDays,
      });
      if (r && r.error) { setErr(r.error); setBusy(false); return; }
      await window.api.reloadBootstrap();
      window.location.reload();
    } catch (e) { setErr(String(e)); setBusy(false); }
  };

  // calcular días laborables aproximados (lun-vie)
  const businessDays = (() => {
    try {
      const a = new Date(from), b = new Date(to);
      if (a > b) return 0;
      let d = new Date(a), n = 0;
      while (d <= b) { const w = d.getDay(); if (w !== 0 && w !== 6) n++; d.setDate(d.getDate() + 1); }
      return n;
    } catch { return 0; }
  })();

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 50,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        background: '#fff', borderRadius: 'var(--r-xl)',
        width: 540, padding: 28, boxShadow: 'var(--shadow-lg)',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }}>
          <div>
            <div style={{ fontSize: 19, fontWeight: 700, letterSpacing: '-0.015em' }}>Solicitar ausencia</div>
            <div style={{ fontSize: 13, color: 'var(--slate-500)', marginTop: 2 }}>Tu manager recibirá la solicitud para aprobar.</div>
          </div>
          <button onClick={onClose} style={{ color: 'var(--slate-500)', padding: 6 }}><IX size={18}/></button>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Field label="Tipo de ausencia" required>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
              {[
                { v: 'Vacaciones', i: <ICalendar size={14}/> },
                { v: 'Asuntos propios', i: <IFlag size={14}/> },
                { v: 'Médico', i: <IShield size={14}/> },
                { v: 'Otros', i: <IMoreH size={14}/> },
              ].map(o => (
                <button key={o.v} onClick={() => setType(o.v)} style={{
                  padding: '10px 8px', fontSize: 12.5, fontWeight: 600,
                  border: `1px solid ${type === o.v ? 'var(--brand-500)' : 'var(--slate-200)'}`,
                  background: type === o.v ? 'var(--brand-50)' : 'var(--white)',
                  color: type === o.v ? 'var(--brand-700)' : 'var(--slate-700)',
                  borderRadius: 'var(--r-md)',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                  boxShadow: type === o.v ? 'var(--ring-brand)' : 'none',
                }}>{o.i}<span>{o.v}</span></button>
              ))}
            </div>
          </Field>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label="Desde" required>
              <Input type="date" value={from} onChange={e => setFrom(e.target.value)} icon={<ICalendar size={15}/>}/>
            </Field>
            <Field label="Hasta" required>
              <Input type="date" value={to} onChange={e => setTo(e.target.value)} icon={<ICalendar size={15}/>}/>
            </Field>
          </div>

          <Field label="Motivo (opcional)" hint="Tu manager verá esta información">
            <textarea value={reason} onChange={e => setReason(e.target.value)} placeholder="Vacaciones de verano con la familia…" style={{
              width: '100%', padding: 12, fontSize: 14,
              border: '1px solid var(--slate-200)', borderRadius: 'var(--r-md)',
              minHeight: 80, resize: 'vertical', outline: 'none',
            }}/>
          </Field>

          <div style={{ padding: 14, background: 'var(--brand-50)', borderRadius: 'var(--r-md)', border: '1px solid var(--brand-100)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
              <span style={{ color: 'var(--slate-600)' }}>Días laborables solicitados</span>
              <span className="mono tnum" style={{ fontWeight: 700, color: 'var(--brand-700)' }}>{businessDays} días</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginTop: 6 }}>
              <span style={{ color: 'var(--slate-600)' }}>Saldo tras la solicitud</span>
              <span className="mono tnum" style={{ fontWeight: 700 }}>{ME.vacationDays.total - ME.vacationDays.used - businessDays} de {ME.vacationDays.total}</span>
            </div>
          </div>
          {err && <div style={{ padding: 10, background: '#FEE2E2', color: '#991B1B', borderRadius: 8, fontSize: 13 }}>{err}</div>}
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, marginTop: 22 }}>
          <Btn variant="ghost" onClick={onClose} disabled={busy}>Cancelar</Btn>
          <Btn variant="primary" icon={<ISend size={14}/>} onClick={submit} disabled={busy}>{busy ? 'Enviando…' : 'Enviar solicitud'}</Btn>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ScreenAusencias });
