function AttendanceTab() {
  const [date, setDate] = React.useState(fmtDateInput(new Date().toISOString()));
  const [starts, setStarts] = React.useState([]);
  const [attempts, setAttempts] = React.useState([]);
  const [alerts, setAlerts] = React.useState([]);
  const [filter, setFilter] = React.useState('all');
  const [loading, setLoading] = React.useState(false);
  const [errMsg, setErrMsg] = React.useState('');

  const load = React.useCallback(async () => {
    setLoading(true);
    setErrMsg('');
    try {
      const [s, a, al] = await Promise.all([
        api.getAttendance(date),
        api.getAttendanceAttempts(date, filter),
        api.getAttendanceAlerts(date),
      ]);
      setStarts(s);
      setAttempts(a);
      setAlerts(al);
    } catch (e) {
      setErrMsg(e.message);
    } finally {
      setLoading(false);
    }
  }, [date, filter]);

  React.useEffect(() => { load(); }, [load]);

  const accepted = attempts.filter(a => a.attendanceStatus === 'ACCEPTED');
  const rejected = attempts.filter(a => a.attendanceStatus && a.attendanceStatus.startsWith('REJECTED_'));
  const startsPager = usePagination(starts, [date]);
  const attemptsPager = usePagination(attempts, [date, filter]);

  return (
    <>
      <PageHeader
        title="Obecność"
        subtitle="Start pracy, historia prób i alerty urządzeń"
        action={<Btn variant="secondary" icon="history" onClick={load}>{loading ? 'Odświeżanie…' : 'Odśwież'}</Btn>}
      />
      <div style={{ padding: 32, overflow: 'auto', flex: 1 }}>
        <div style={{ ...cardStyle, padding: '16px 20px', marginBottom: 16, display: 'flex', gap: 16, alignItems: 'flex-end', flexWrap: 'wrap' }}>
          <div style={{ minWidth: 180 }}>
            <Field label="Data robocza">
              <Input type="date" value={date} onChange={e => setDate(e.target.value)} />
            </Field>
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {[
              ['all', 'Wszystkie'],
              ['accepted', 'Zaakceptowane'],
              ['rejected', 'Odrzucone'],
              ['suspected', 'Podejrzane urządzenia'],
            ].map(([id, label]) => (
              <button key={id} onClick={() => setFilter(id)} style={{
                padding: '9px 13px', border: `1px solid ${filter === id ? '#f59e0b' : '#e4e4e7'}`,
                background: filter === id ? '#fef3c7' : '#fff', color: filter === id ? '#854d0e' : '#52525b',
                fontWeight: filter === id ? 800 : 600, fontSize: 13, borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit',
              }}>{label}</button>
            ))}
          </div>
        </div>

        {errMsg && <div style={{ marginBottom: 16, padding: 12, background: '#fee2e2', color: '#991b1b', borderRadius: 8, fontSize: 13 }}>Błąd: {errMsg}</div>}

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 16 }}>
          <AttendanceStat label="Starty pracy" value={starts.length} />
          <AttendanceStat label="Udane odbicia" value={accepted.length} tone="green" />
          <AttendanceStat label="Odrzucone próby" value={rejected.length} tone="red" />
          <AttendanceStat label="Alerty" value={alerts.length} tone="amber" />
        </div>

        {alerts.length > 0 && (
          <div style={{ ...cardStyle, marginBottom: 16 }}>
            <div style={cardHeaderStyle}><div style={{ fontSize: 14, fontWeight: 800 }}>Alerty podejrzanych zachowań</div></div>
            <div style={{ padding: 16, display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
              {alerts.map((a, idx) => (
                <div key={idx} style={{ border: '1px solid #facc15', background: '#fefce8', borderRadius: 8, padding: 14 }}>
                  <div style={{ fontSize: 14, fontWeight: 900, color: '#854d0e', marginBottom: 8 }}>⚠ {a.title}</div>
                  {a.type === 'SHARED_DEVICE' ? (
                    <>
                      <div style={{ fontSize: 13, color: '#3f3f46', marginBottom: 4 }}>Telefon: <strong>{phoneLabel(a)}</strong></div>
                      <div style={{ fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace', marginBottom: 10 }}>Device ID: {a.deviceId}</div>
                      <div style={{ fontSize: 12, fontWeight: 800, color: '#52525b', marginBottom: 4 }}>Użytkownicy</div>
                      {a.users.map(u => <div key={u.userId} style={{ fontSize: 13 }}>- {u.driverName} — {fmtTime(u.attemptedAt)}</div>)}
                    </>
                  ) : (
                    <>
                      <div style={{ fontSize: 13, color: '#3f3f46', marginBottom: 8 }}><strong>{a.driverName}</strong> używał wielu telefonów.</div>
                      {a.devices.map(d => (
                        <div key={d.deviceId} style={{ marginBottom: 6 }}>
                          <div style={{ fontSize: 13 }}>{phoneLabel(d)}</div>
                          <div style={{ fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>Device ID: {d.deviceId}</div>
                        </div>
                      ))}
                    </>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.35fr', gap: 16 }}>
          <div style={cardStyle}>
            <div style={cardHeaderStyle}>
              <div style={{ fontSize: 14, fontWeight: 800 }}>Starty pracy ({starts.length})</div>
              <div style={{ fontSize: 12, color: '#71717a' }}>{date}</div>
            </div>
            <div style={{ padding: 12 }}>
              {startsPager.pageItems.map(s => (
                <div key={s.id} style={{ padding: 12, borderBottom: '1px solid #f4f4f5', display: 'flex', gap: 10 }}>
                  <Avatar name={s.driverName} size={30} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 800 }}>{s.driverName}</div>
                    <div style={{ fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>{fmtTime(s.startedAt)} • {coords(s)}</div>
                    <div style={{ fontSize: 12, color: '#52525b', marginTop: 4 }}>{phoneLabel(s)}</div>
                    <div style={{ fontSize: 11, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>{s.deviceId || 'brak device_id'}</div>
                  </div>
                  <div style={{ fontSize: 12, fontWeight: 800, color: '#166534', whiteSpace: 'nowrap' }}>{Math.round(s.distanceMeters)} m</div>
                </div>
              ))}
              {starts.length === 0 && <EmptyAttendance>Brak zapisanych startów pracy dla wybranego dnia.</EmptyAttendance>}
            </div>
            <PaginationBar
              total={starts.length}
              page={startsPager.page}
              pageSize={startsPager.pageSize}
              totalPages={startsPager.totalPages}
              onPage={startsPager.setPage}
              onPageSize={startsPager.setPageSize}
            />
          </div>

          <div style={cardStyle}>
            <div style={cardHeaderStyle}><div style={{ fontSize: 14, fontWeight: 800 }}>Historia prób ({attempts.length})</div></div>
            <div style={{ maxHeight: 620, overflow: 'auto' }}>
              {attemptsPager.pageItems.map(a => (
                <div key={a.id} style={{ padding: '14px 16px', borderBottom: '1px solid #f4f4f5', display: 'grid', gridTemplateColumns: '1fr auto', gap: 12 }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                      <Avatar name={a.driverName} size={26} />
                      <div style={{ fontSize: 14, fontWeight: 800 }}>{a.driverName}</div>
                      <AttendanceStatus status={a.attendanceStatus} />
                    </div>
                    <div style={{ fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>{fmtTime(a.attemptedAt)} • {coords(a)}</div>
                    <div style={{ fontSize: 13, color: '#3f3f46', marginTop: 5 }}>{phoneLabel(a)}</div>
                    <div style={{ fontSize: 11, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>Device ID: {a.deviceId || 'brak'}</div>
                    {a.rejectionReason && (
                      <div style={{ marginTop: 8, padding: 10, borderRadius: 6, background: '#fafaf9', color: '#52525b', fontSize: 12, lineHeight: 1.45 }}>
                        <strong>Powód:</strong> {a.rejectionReason}
                      </div>
                    )}
                  </div>
                  <div style={{ textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontSize: 12, color: a.distanceMeters > 100 ? '#991b1b' : '#166534', fontWeight: 800 }}>
                    {a.distanceMeters == null ? '—' : `${Math.round(a.distanceMeters)} m`}
                  </div>
                </div>
              ))}
              {attempts.length === 0 && <EmptyAttendance>Brak prób dla wybranego filtra.</EmptyAttendance>}
            </div>
            <PaginationBar
              total={attempts.length}
              page={attemptsPager.page}
              pageSize={attemptsPager.pageSize}
              totalPages={attemptsPager.totalPages}
              onPage={attemptsPager.setPage}
              onPageSize={attemptsPager.setPageSize}
            />
          </div>
        </div>
      </div>
    </>
  );
}

function AttendanceStat({ label, value, tone }) {
  const colors = { green: ['#dcfce7', '#166534'], red: ['#fee2e2', '#991b1b'], amber: ['#fef3c7', '#854d0e'] }[tone] || ['#f4f4f5', '#18181b'];
  return (
    <div style={{ ...cardStyle, padding: 16 }}>
      <div style={{ fontSize: 11, color: '#71717a', textTransform: 'uppercase', letterSpacing: 0.8, fontWeight: 800 }}>{label}</div>
      <div style={{ display: 'inline-flex', marginTop: 8, padding: '4px 10px', borderRadius: 6, background: colors[0], color: colors[1], fontSize: 24, fontWeight: 900, fontFamily: 'JetBrains Mono, monospace' }}>{value}</div>
    </div>
  );
}

function AttendanceStatus({ status }) {
  const ok = status === 'ACCEPTED';
  return <span style={{ background: ok ? '#dcfce7' : '#fee2e2', color: ok ? '#166534' : '#991b1b', borderRadius: 999, padding: '2px 8px', fontSize: 10, fontWeight: 900, fontFamily: 'JetBrains Mono, monospace' }}>{status}</span>;
}

function phoneLabel(x) {
  return [x.deviceManufacturer, x.deviceModel].filter(Boolean).join(' ') || x.deviceModel || 'Nieznany telefon';
}

function coords(x) {
  if (x.latitude == null || x.longitude == null) return 'brak lokalizacji';
  return `${Number(x.latitude).toFixed(5)}, ${Number(x.longitude).toFixed(5)}`;
}

function EmptyAttendance({ children }) {
  return <div style={{ padding: 28, textAlign: 'center', color: '#a1a1aa', fontSize: 13 }}>{children}</div>;
}

Object.assign(window, { AttendanceTab });
