// Dashboard — przegląd stanu bota + ostatnie rezerwacje + recent events
const { useState: uSD, useEffect: uED, useMemo: uMD } = React;

function StatCard({ label, value, sub, tone }) {
  return (
    <div className="card" style={{ padding: 14, minWidth: 160, flex: "1 1 180px" }}>
      <div style={{ fontSize: 11, color: "var(--fg-muted)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 6 }}>{label}</div>
      <div className="mono" style={{ fontSize: 22, fontWeight: 600, color: tone === "hit" ? "var(--hit)" : "var(--fg)" }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: "var(--fg-muted)", marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

function DashboardView({ status, toast }) {
  const [reservations, setReservations] = uSD([]);
  const [events, setEvents] = uSD([]);
  const [busy, setBusy] = uSD("");

  uED(() => {
    const load = () => {
      window.ZlapApi.listReservations(10).then(setReservations).catch(()=>{});
      window.ZlapApi.getEvents({ limit: 30 }).then(rs => setEvents(rs.map(window.ZlapApi.adapters.event))).catch(()=>{});
    };
    load();
    const iv = setInterval(load, 5000);
    return () => clearInterval(iv);
  }, []);

  const botCtl = async (action) => {
    setBusy(action);
    try {
      const fn = { start: "botStart", pause: "botPause", resume: "botResume", restart: "botRestart" }[action];
      const res = await window.ZlapApi[fn]();
      toast(`Bot ${action}: ${res.ok ? "OK" : "błąd"}`, res.ok ? "ok" : "err");
    } catch (e) {
      toast(`${action}: ${e.message}`, "err");
    } finally {
      setBusy("");
    }
  };

  const st = status || {};

  return (
    <div style={{ padding: "18px 22px 80px" }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 14, flexWrap: "wrap", gap: 10 }}>
        <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.01em" }}>Dashboard</div>
        <div style={{ display: "flex", gap: 6 }}>
          <button className="btn ghost" disabled={!!busy} onClick={() => botCtl("pause")}><Icon name="pause" size={12}/> Pauza</button>
          <button className="btn ghost" disabled={!!busy} onClick={() => botCtl("resume")}><Icon name="play" size={12}/> Wznów</button>
          <button className="btn ghost" disabled={!!busy} onClick={() => botCtl("restart")}><Icon name="restart" size={12}/> Restart</button>
        </div>
      </div>

      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 16 }}>
        <StatCard label="Stan bota" value={st.state || "—"} sub={st.pid ? `pid ${st.pid}` : null} />
        <StatCard label="Aktywne auto-taski" value={st.active_auto_tasks ?? 0} />
        <StatCard label="Dzisiaj znalezionych" value={st.today_found_slots ?? 0} tone="hit" />
        <StatCard label="Dzisiaj rezerwacji" value={st.today_reservations ?? 0} />
      </div>

      {st.last_error && (
        <div className="card" style={{ padding: 12, marginBottom: 14, borderLeft: "3px solid var(--err)" }}>
          <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>Ostatni błąd</div>
          <div className="mono" style={{ fontSize: 12, marginTop: 4 }}>{st.last_error}</div>
        </div>
      )}

      <div style={{ display: "grid", gap: 14, gridTemplateColumns: "1fr 1fr" }} className="dash-grid">
        <div className="card" style={{ padding: 16 }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 10 }}>Ostatnie rezerwacje</div>
          {reservations.length === 0 && <div style={{color:"var(--fg-muted)", fontSize: 12}}>Brak rezerwacji</div>}
          {reservations.slice(0, 6).map(r => (
            <div key={r.id} style={{ padding: "8px 0", borderBottom: "1px solid var(--border)", fontSize: 12.5, display: "flex", justifyContent: "space-between", gap: 8 }}>
              <div>
                <span className={cls("badge", {reserved:"ok", pending:"info", failed:"err", expired:"muted"}[r.status] || "muted")}>{r.status}</span>
                {" "}<span className="mono">{r.slot_date} {r.slot_time}</span> · {r.word_name}
              </div>
              {r.payment_url && (
                <a className="btn primary" href={r.payment_url} target="_blank" rel="noopener noreferrer" style={{ padding: "3px 8px" }}>
                  Opłać
                </a>
              )}
            </div>
          ))}
        </div>
        <div className="card" style={{ padding: 16, maxHeight: 360, overflow: "auto" }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 10 }}>Ostatnie zdarzenia</div>
          {events.length === 0 && <div style={{color:"var(--fg-muted)", fontSize: 12}}>Brak zdarzeń</div>}
          {events.slice(0, 30).map(e => (
            <div key={e.id} style={{ padding: "6px 0", borderBottom: "1px solid var(--border)", fontSize: 12.5, display: "flex", gap: 8 }}>
              <LevelBadge level={e.level} />
              <span className="mono" style={{ color: "var(--fg-dim)", flexShrink: 0 }}><RelTime date={e.at}/></span>
              <span style={{ flex: 1, minWidth: 0 }}>{e.msg}</span>
            </div>
          ))}
        </div>
      </div>

      <style>{`@media (max-width: 760px) { .dash-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}
window.DashboardView = DashboardView;
