// CoordinatorMain — mobilny widok koordynatora (rola 'pracownik').
// Dostęp tylko do dwóch rzeczy: „Aktywni kierowcy" (podgląd) oraz „Urlopy"
// (kalendarz + zatwierdzanie/odrzucanie wniosków; bez usuwania).
// Wszystkie identyfikatory top-level mają prefiks Coord/co — globalny scope
// Babel Standalone jest współdzielony między plikami, więc nazwy muszą być unikalne.

function CoordinatorMain({ width, height, user, onLogout }) {
  const [tab,   setTab]   = React.useState('active'); // active | leave
  const [toast, setToast] = React.useState(null);
  const showToast = (m) => { setToast(m); setTimeout(() => setToast(null), 2500); };

  return (
    <div style={{ width, height, position: 'relative', overflow: 'hidden', background: '#0c0a09', fontFamily: '"Manrope", system-ui, sans-serif', display: 'flex', flexDirection: 'column' }}>
      {/* Nagłówek */}
      <div style={{ background: '#0c0a09', color: '#fafaf9', padding: '44px 18px 14px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <BrandMark size={32} />
            <div>
              <div style={{ fontSize: 15, fontWeight: 800 }}>{user.name.split(' ')[0]}</div>
              <div style={{ fontSize: 10, color: '#71717a', letterSpacing: 1, textTransform: 'uppercase' }}>Koordynator</div>
            </div>
          </div>
          <button onClick={onLogout} title="Wyloguj" style={{ background: '#18181b', border: '1px solid #27272a', color: '#a1a1aa', padding: 8, borderRadius: 8, cursor: 'pointer' }}><Icon name="logout" size={16} /></button>
        </div>
        {/* Segmentowany przełącznik zakładek */}
        <div style={{ display: 'flex', gap: 6, background: '#18181b', padding: 4, borderRadius: 10 }}>
          {[['active', 'Aktywni kierowcy'], ['leave', 'Urlopy']].map(([v, l]) => {
            const sel = tab === v;
            return (
              <button key={v} onClick={() => setTab(v)} style={{ flex: 1, padding: '10px 8px', border: 'none', borderRadius: 7, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 13, background: sel ? '#f59e0b' : 'transparent', color: sel ? '#0c0a09' : '#a1a1aa', transition: 'all .12s' }}>{l}</button>
            );
          })}
        </div>
      </div>

      {/* Treść */}
      <div style={{ flex: 1, overflow: 'auto', background: '#fafaf9', padding: '16px 14px 28px' }}>
        {tab === 'active' ? <CoordActiveDrivers /> : <CoordLeave onToast={showToast} />}
      </div>

      <PhoneNavBar />

      {toast && (
        <div style={{ position: 'absolute', bottom: 40, left: 16, right: 16, background: '#166534', color: '#fff', padding: '13px 16px', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.35)', fontSize: 14, fontWeight: 600, zIndex: 20, animation: 'tf-slide-up .25s ease-out' }}>
          <div style={{ width: 26, height: 26, borderRadius: 13, background: '#22c55e', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={15} color="#fff" /></div>
          {toast}
        </div>
      )}
    </div>
  );
}

// ── Aktywni kierowcy (tylko podgląd) ─────────────────────────────
function CoordActiveDrivers() {
  const coToday = (() => { const d = new Date(); const p = (x) => String(x).padStart(2, '0'); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`; })();
  const [date,    setDate]    = React.useState(coToday);
  const [drivers, setDrivers] = React.useState([]);
  const [starts,  setStarts]  = React.useState([]);
  const [marks,   setMarks]   = React.useState({});
  const [leaveSet, setLeaveSet] = React.useState(new Set());
  const [loading, setLoading] = React.useState(true);
  const [errMsg,  setErrMsg]  = React.useState(null);

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      // Urlop zgłaszany na dzień dostaw (D+1), „Wolne" pokazujemy na dzień zbiórki (D) — jak w panelu.
      const next = new Date(date + 'T12:00:00'); next.setDate(next.getDate() + 1);
      const pp = (x) => String(x).padStart(2, '0');
      const leaveDay = `${next.getFullYear()}-${pp(next.getMonth() + 1)}-${pp(next.getDate())}`;
      const [d, a, m, lv] = await Promise.all([
        api.getDrivers(), api.getAttendance(date), api.getAttendanceMarks(date),
        api.getLeaves({ from: leaveDay, to: leaveDay, status: 'approved' }),
      ]);
      setDrivers(d);
      setStarts(Array.isArray(a) ? a : []);
      const mm = {};
      (Array.isArray(m) ? m : []).forEach(x => { if (x.userId != null) mm[x.userId] = x.mark; });
      setMarks(mm);
      setLeaveSet(new Set((Array.isArray(lv) ? lv : []).map(x => x.userId)));
      setErrMsg(null);
    } catch (e) {
      if (e.status === 401) { api.logout(); window.location.reload(); return; }
      setErrMsg(e.message);
    } finally { setLoading(false); }
  }, [date]);
  React.useEffect(() => { load(); }, [load]);

  const startMap = React.useMemo(() => {
    const m = {};
    starts.forEach(s => { if (s.userId != null && !m[s.userId]) m[s.userId] = s.startedAt; });
    return m;
  }, [starts]);

  const fleet = drivers.filter(d => d.role === 'kierowca' && d.active);
  const rows = fleet.map(d => {
    const checkedIn = !!startMap[d.id];
    const fromLeave = !checkedIn && leaveSet.has(d.id);
    const status = checkedIn ? 'na_magazynie' : ((fromLeave || marks[d.id] === 'wolne') ? 'wolne' : 'poza');
    return { id: d.id, name: d.name, time: startMap[d.id] || null, status, fromLeave };
  }).sort((a, b) => a.name.localeCompare(b.name, 'pl'));

  const naMagazynie   = rows.filter(r => r.status === 'na_magazynie').length;
  const pozaMagazynem = rows.length - naMagazynie;

  return (
    <div>
      <div style={{ marginBottom: 14 }}>
        <DatePicker value={date} onChange={setDate} style={{ width: '100%' }} />
      </div>

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

      {/* Podsumowanie */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
        <div style={{ background: '#dcfce7', border: '1px solid #bbf7d0', borderRadius: 12, padding: '12px 14px' }}>
          <div style={{ fontSize: 10, color: '#166534', letterSpacing: 0.5, textTransform: 'uppercase', fontWeight: 700 }}>Odbici</div>
          <div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'JetBrains Mono, monospace', color: '#166534', marginTop: 2 }}>{naMagazynie}</div>
        </div>
        <div style={{ background: '#fff', border: '1px solid #e7e5e4', borderRadius: 12, padding: '12px 14px' }}>
          <div style={{ fontSize: 10, color: '#71717a', letterSpacing: 0.5, textTransform: 'uppercase', fontWeight: 700 }}>Nieodbici</div>
          <div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'JetBrains Mono, monospace', color: '#18181b', marginTop: 2 }}>{pozaMagazynem}</div>
        </div>
      </div>

      {/* Lista */}
      <div style={{ background: '#fff', borderRadius: 12, border: '1px solid #e7e5e4', overflow: 'hidden' }}>
        <div style={{ padding: '12px 14px', borderBottom: '1px solid #f4f4f5', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontSize: 13, fontWeight: 800, color: '#18181b' }}>Kierowcy ({rows.length})</div>
          <div style={{ fontSize: 11, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>{fmtDate(date + 'T00:00:00')}</div>
        </div>
        {rows.length === 0 ? (
          <div style={{ padding: 30, textAlign: 'center', color: '#a1a1aa', fontSize: 13 }}>{loading ? 'Ładowanie…' : 'Brak aktywnych kierowców'}</div>
        ) : rows.map((r, i) => (
          <div key={r.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 14px', borderTop: i === 0 ? 'none' : '1px solid #f4f4f5' }}>
            <Avatar name={r.name} size={30} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: '#18181b', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.name}</div>
              {r.time && <div style={{ fontSize: 11, color: '#71717a', fontFamily: 'JetBrains Mono, monospace', marginTop: 1 }}>{fmtTime(r.time)}</div>}
            </div>
            <CoordStatusChip status={r.status} fromLeave={r.fromLeave} />
          </div>
        ))}
      </div>
    </div>
  );
}

function CoordStatusChip({ status, fromLeave }) {
  if (status === 'na_magazynie') return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px 4px 8px', borderRadius: 999, background: '#dcfce7', color: '#166534', fontSize: 12, fontWeight: 700, whiteSpace: 'nowrap' }}>
      <span style={{ width: 6, height: 6, borderRadius: 3, background: '#22c55e' }} />Na magazynie
    </span>
  );
  if (status === 'wolne') return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px 4px 8px', borderRadius: 999, background: '#dbeafe', color: '#1e40af', fontSize: 12, fontWeight: 700, whiteSpace: 'nowrap' }}>
      <span style={{ width: 6, height: 6, borderRadius: 3, background: '#3b82f6' }} />{fromLeave ? 'Wolne · urlop' : 'Wolne'}
    </span>
  );
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px 4px 8px', borderRadius: 999, background: '#f4f4f5', color: '#52525b', fontSize: 12, fontWeight: 700, whiteSpace: 'nowrap' }}>
      <span style={{ width: 6, height: 6, borderRadius: 3, background: '#a1a1aa' }} />Poza
    </span>
  );
}

// ── Urlopy (kalendarz + zatwierdzanie, bez usuwania) ─────────────
function CoordLeave({ onToast }) {
  const [view, setView] = React.useState('month'); // month | week | day
  const [anchor, setAnchor] = React.useState(() => leaveYmd(new Date()));
  const [rangeLeaves, setRangeLeaves] = React.useState([]);
  const [pending, setPending] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [errMsg, setErrMsg] = React.useState(null);
  const [busyId, setBusyId] = React.useState(null);

  const range = React.useMemo(() => {
    const a = new Date(anchor + 'T12:00:00');
    if (view === 'day') return { from: anchor, to: anchor };
    if (view === 'week') {
      const dow = (a.getDay() + 6) % 7;
      const mon = new Date(a); mon.setDate(a.getDate() - dow);
      const sun = new Date(mon); sun.setDate(mon.getDate() + 6);
      return { from: leaveYmd(mon), to: leaveYmd(sun) };
    }
    const first = new Date(a.getFullYear(), a.getMonth(), 1);
    const last = new Date(a.getFullYear(), a.getMonth() + 1, 0);
    return { from: leaveYmd(first), to: leaveYmd(last) };
  }, [anchor, view]);

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const [rl, pl] = await Promise.all([
        api.getLeaves({ from: range.from, to: range.to }),
        api.getLeaves({ status: 'pending' }),
      ]);
      setRangeLeaves(Array.isArray(rl) ? rl : []);
      setPending(Array.isArray(pl) ? pl : []);
      setErrMsg(null);
    } catch (e) {
      if (e.status === 401) { api.logout(); window.location.reload(); return; }
      setErrMsg(e.message);
    } finally { setLoading(false); }
  }, [range.from, range.to]);
  React.useEffect(() => { load(); }, [load]);

  const decide = async (id, status) => {
    setBusyId(id);
    try {
      await api.updateLeave(id, status);
      await load();
      onToast && onToast(status === 'approved' ? 'Wniosek zatwierdzony ✓' : 'Wniosek odrzucony');
    } catch (e) { alert('Błąd: ' + e.message); }
    finally { setBusyId(null); }
  };

  const leavesOn = (dayStr) => rangeLeaves.filter(l => l.dateFrom <= dayStr && l.dateTo >= dayStr);
  const shift = (dir) => {
    const a = new Date(anchor + 'T12:00:00');
    if (view === 'day') a.setDate(a.getDate() + dir);
    else if (view === 'week') a.setDate(a.getDate() + dir * 7);
    else a.setMonth(a.getMonth() + dir);
    setAnchor(leaveYmd(a));
  };
  const todayStr = leaveYmd(new Date());
  const a = new Date(anchor + 'T12:00:00');

  const headerLabel = () => {
    if (view === 'day') return fmtDate(anchor + 'T00:00:00');
    if (view === 'week') return `${fmtDate(range.from + 'T00:00:00')} – ${fmtDate(range.to + 'T00:00:00')}`;
    return `${LEAVE_MONTHS[a.getMonth()]} ${a.getFullYear()}`;
  };

  // Miesiąc — siatka z paskami
  const cells = (() => {
    const from = new Date(range.from + 'T12:00:00');
    const to = new Date(range.to + 'T12:00:00');
    const arr = [];
    const lead = (from.getDay() + 6) % 7;
    for (let i = 0; i < lead; i++) arr.push(null);
    const d = new Date(from);
    while (d <= to) { arr.push(leaveYmd(d)); d.setDate(d.getDate() + 1); }
    return arr;
  })();

  // Tydzień/Dzień — kolejne dni od góry do dołu (z nazwiskami)
  const dayRows = (() => {
    if (view === 'day') return [anchor];
    const from = new Date(range.from + 'T12:00:00');
    const arr = [];
    for (let i = 0; i < 7; i++) { const d = new Date(from); d.setDate(from.getDate() + i); arr.push(leaveYmd(d)); }
    return arr;
  })();

  const fmtRange = (l) => l.dateFrom === l.dateTo
    ? fmtDate(l.dateFrom + 'T00:00:00')
    : `${fmtDate(l.dateFrom + 'T00:00:00')} – ${fmtDate(l.dateTo + 'T00:00:00')}`;

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

      {/* Przełącznik widoku */}
      <div style={{ display: 'flex', gap: 6, background: '#f4f4f5', padding: 4, borderRadius: 10, marginBottom: 10 }}>
        {[['month', 'Miesiąc'], ['week', 'Tydzień'], ['day', 'Dzień']].map(([v, l]) => {
          const sel = view === v;
          return <button key={v} onClick={() => setView(v)} style={{ flex: 1, padding: '8px 6px', border: 'none', borderRadius: 7, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 13, background: sel ? '#fff' : 'transparent', color: sel ? '#18181b' : '#71717a', boxShadow: sel ? '0 1px 3px rgba(0,0,0,0.12)' : 'none' }}>{l}</button>;
        })}
      </div>

      {/* Nawigacja */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 10 }}>
        <button onClick={() => shift(-1)} style={coNavBtn}>‹</button>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 14, fontWeight: 800, color: '#18181b' }}>{headerLabel()}</div>
        <button onClick={() => setAnchor(todayStr)} style={{ ...coNavBtn, width: 'auto', padding: '0 12px', fontSize: 13, fontWeight: 700 }}>Dziś</button>
        <button onClick={() => shift(1)} style={coNavBtn}>›</button>
      </div>

      {view === 'month' ? (
        /* Kalendarz miesięczny — paski wg statusu */
        <div style={{ background: '#fff', border: '1px solid #e7e5e4', borderRadius: 12, padding: 8, marginBottom: 16 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 3, marginBottom: 4 }}>
            {LEAVE_DOW.map(w => <div key={w} style={{ textAlign: 'center', fontSize: 10, fontWeight: 700, color: '#a1a1aa' }}>{w}</div>)}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 3 }}>
            {cells.map((day, i) => {
              if (day === null) return <div key={`e${i}`} />;
              const items = leavesOn(day);
              const dd = new Date(day + 'T12:00:00');
              return (
                <div key={day} onClick={() => { setAnchor(day); setView('day'); }} style={{ minHeight: 52, border: '1px solid #f4f4f5', borderRadius: 6, padding: 3, background: day === todayStr ? '#fffbeb' : '#fff', cursor: 'pointer' }}>
                  <div style={{ fontSize: 10, fontWeight: 700, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>{dd.getDate()}</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 2, marginTop: 2 }}>
                    {items.slice(0, 3).map(l => {
                      const s = LEAVE_STATUS[l.status] || LEAVE_STATUS.pending;
                      return <div key={l.id} title={`${l.driverName} • ${s.l}`} style={{ width: '100%', height: 5, borderRadius: 3, background: s.fg }} />;
                    })}
                    {items.length > 3 && <div style={{ fontSize: 9, color: '#a1a1aa', fontWeight: 700 }}>+{items.length - 3}</div>}
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ display: 'flex', gap: 12, marginTop: 8, paddingTop: 8, borderTop: '1px solid #f4f4f5', flexWrap: 'wrap' }}>
            {Object.entries(LEAVE_STATUS).map(([k, s]) => (
              <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: '#52525b' }}>
                <span style={{ width: 10, height: 6, borderRadius: 3, background: s.fg }} />{s.l}
              </div>
            ))}
          </div>
          <div style={{ fontSize: 11, color: '#a1a1aa', marginTop: 6, textAlign: 'center' }}>Dotknij dnia, aby zobaczyć nazwiska</div>
        </div>
      ) : (
        /* Tydzień/Dzień — dni od góry do dołu z nazwiskami */
        <div style={{ background: '#fff', border: '1px solid #e7e5e4', borderRadius: 12, overflow: 'hidden', marginBottom: 16 }}>
          {dayRows.map((day, i) => {
            const items = leavesOn(day);
            const dd = new Date(day + 'T12:00:00');
            const dowLabel = LEAVE_DOW[(dd.getDay() + 6) % 7];
            return (
              <div key={day} style={{ display: 'flex', gap: 10, padding: view === 'day' ? '14px' : '10px 12px', borderTop: i === 0 ? 'none' : '1px solid #f4f4f5', background: day === todayStr ? '#fffbeb' : '#fff' }}>
                <div style={{ width: view === 'day' ? 'auto' : 52, flexShrink: 0 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#a1a1aa', textTransform: 'uppercase' }}>{dowLabel}</div>
                  <div style={{ fontSize: 13, fontWeight: 800, color: '#18181b', fontFamily: 'JetBrains Mono, monospace' }}>{dd.getDate()}.{String(dd.getMonth() + 1).padStart(2, '0')}</div>
                </div>
                <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {items.length === 0 ? (
                    <div style={{ fontSize: 13, color: '#cbd5e1' }}>—</div>
                  ) : items.map(l => {
                    const s = LEAVE_STATUS[l.status] || LEAVE_STATUS.pending;
                    return (
                      <div key={l.id} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Avatar name={l.driverName} size={26} />
                        <span style={{ flex: 1, minWidth: 0, fontSize: 14, fontWeight: 600, color: '#18181b', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{l.driverName}</span>
                        <span style={{ padding: '2px 9px', borderRadius: 999, background: s.bg, color: s.fg, fontSize: 11, fontWeight: 700, whiteSpace: 'nowrap' }}>{s.l}</span>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Oczekujące wnioski */}
      <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8 }}>Oczekujące wnioski ({pending.length})</div>
      {pending.length === 0 ? (
        <div style={{ padding: 24, textAlign: 'center', color: '#a1a1aa', fontSize: 13 }}>{loading ? 'Ładowanie…' : 'Brak oczekujących wniosków'}</div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {pending.map(l => (
            <div key={l.id} style={{ background: '#fff', border: '1px solid #e7e5e4', borderRadius: 12, padding: 12 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <Avatar name={l.driverName} size={32} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: '#18181b' }}>{l.driverName}</div>
                  <div style={{ fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>{fmtRange(l)}</div>
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                <button onClick={() => decide(l.id, 'approved')} disabled={busyId === l.id} style={{ padding: '11px', borderRadius: 9, border: 'none', background: '#166534', color: '#fff', fontFamily: 'inherit', fontWeight: 800, fontSize: 13, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, opacity: busyId === l.id ? 0.6 : 1 }}>
                  <Icon name="check" size={15} color="#fff" strokeWidth={2.4} />Zatwierdź
                </button>
                <button onClick={() => decide(l.id, 'rejected')} disabled={busyId === l.id} style={{ padding: '11px', borderRadius: 9, border: '1px solid #fecaca', background: '#fff', color: '#dc2626', fontFamily: 'inherit', fontWeight: 800, fontSize: 13, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, opacity: busyId === l.id ? 0.6 : 1 }}>
                  <Icon name="x" size={15} color="#dc2626" strokeWidth={2.4} />Odrzuć
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

const coNavBtn = { width: 38, height: 38, border: '1px solid #e7e5e4', background: '#fff', borderRadius: 8, cursor: 'pointer', fontSize: 20, color: '#52525b', fontFamily: 'inherit' };

Object.assign(window, { CoordinatorMain, CoordActiveDrivers, CoordStatusChip, CoordLeave });
