// Sidebar component
const { useState, useMemo } = React;

function StatusDot({ status, theme, size = 6 }) {
  const color =
    status === "running" ? theme.accent :
    status === "waiting" ? theme.warn :
    status === "error" ? theme.err :
    status === "online" ? theme.accent :
    theme.fg3;
  const pulse = status === "running";
  return React.createElement("span", { style: {
    display: "inline-block", width: size, height: size, borderRadius: 999,
    background: color,
    animation: pulse ? "ac-pulse 1.6s infinite" : "none",
    flexShrink: 0,
  }});
}

function Sidebar({ theme, machines, sessions, activeId, onSelect, view, onNavigate, collapsed, onNewSession }) {
  const t = theme;
  const grouped = useMemo(() => {
    const g = {};
    machines.forEach(m => { g[m.id] = []; });
    sessions.forEach(s => { if (g[s.machine_id]) g[s.machine_id].push(s); });
    return g;
  }, [machines, sessions]);

  return (
    <aside style={{
      width: collapsed ? 60 : 280, transition: "width 0.2s ease",
      background: t.bg2, borderRight: `1px solid ${t.line}`,
      display: "flex", flexDirection: "column",
      fontFamily: t.fontSans, color: t.fg, height: "100%", overflow: "hidden",
    }}>
      {/* Brand */}
      <div style={{ padding: collapsed ? "18px 12px" : "18px 18px 14px", borderBottom: `1px solid ${t.line}`, display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{
          width: 26, height: 26, borderRadius: t.radius / 2 + 2,
          background: t.accent, display: "flex", alignItems: "center", justifyContent: "center",
          color: t.bg, fontWeight: 700, fontSize: 13, fontFamily: t.fontMono, flexShrink: 0,
        }}>/</div>
        {!collapsed && <div style={{ fontFamily: t.fontDisplay, fontWeight: t.weightHeading, fontSize: 15, letterSpacing: 0.2, color: t.fg, flex: 1 }}>agents control</div>}
        {!collapsed && <button onClick={onNewSession} style={iconBtn(t)} title="New session">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>
        </button>}
      </div>

      {/* Nav */}
      <div style={{ padding: collapsed ? "10px 8px 4px" : "10px 10px 4px", display: "flex", flexDirection: "column", gap: 2 }}>
        {[
          { id: "dashboard", label: "Overview", icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg> },
          { id: "agents", label: "Agents", icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="12" cy="7" r="3"/><path d="M4 21v-2a6 6 0 016-6h4a6 6 0 016 6v2"/></svg> },
          { id: "extension", label: "Browser bridge", icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18"/></svg> },
        ].map(item => {
          const act = view === item.id;
          return (
            <button key={item.id} onClick={() => onNavigate(item.id)} style={{
              width: "100%", display: "flex", alignItems: "center", gap: 10,
              padding: collapsed ? "8px" : "8px 10px",
              background: act ? t.panel2 : "transparent",
              border: act ? `1px solid ${t.line2}` : "1px solid transparent",
              borderRadius: t.radius, color: act ? t.fg : t.fg2,
              fontSize: 12.5, fontFamily: t.fontSans, cursor: "pointer",
              textAlign: "left", justifyContent: collapsed ? "center" : "flex-start",
            }}>
              {item.icon}
              {!collapsed && <span>{item.label}</span>}
            </button>
          );
        })}
      </div>

      {/* Machines + sessions */}
      <div style={{ flex: 1, overflowY: "auto", padding: collapsed ? "6px 4px" : "6px 10px" }}>
        {machines.map(m => {
          const mSessions = grouped[m.id] || [];
          return (
            <div key={m.id} style={{ marginBottom: 10 }}>
              {!collapsed && (
                <div style={{
                  display: "flex", alignItems: "center", gap: 8,
                  padding: "10px 10px 6px", fontSize: 10.5,
                  fontFamily: t.fontMono, letterSpacing: 0.8,
                  textTransform: "uppercase", color: t.fg3,
                }}>
                  <StatusDot status={m.status} theme={t} />
                  <span style={{ color: t.fg2, fontWeight: 500 }}>{m.name}</span>
                  <span style={{ color: t.fg3 }}>{m.connector_version || ''}</span>
                </div>
              )}
              {collapsed && (
                <div style={{ padding: "8px 0", textAlign: "center" }}>
                  <div style={{
                    width: 28, height: 28, margin: "0 auto", borderRadius: t.radius,
                    background: t.panel, border: `1px solid ${t.line}`,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 10, fontFamily: t.fontMono, color: t.fg2,
                  }}>{m.name.split(" ").map(w => w[0]).join("").slice(0,2)}</div>
                </div>
              )}
              {!collapsed && mSessions.map(s => (
                <SessionRow key={s.id} s={s} theme={t} active={activeId === s.id} onClick={() => onSelect(s.id)} />
              ))}
              {!collapsed && mSessions.length === 0 && (
                <div style={{ padding: "4px 10px 8px", fontSize: 11.5, color: t.fg3, fontStyle: "italic" }}>No sessions</div>
              )}
            </div>
          );
        })}
      </div>

      {/* Footer */}
      {!collapsed && (
        <div style={{ borderTop: `1px solid ${t.line}`, padding: "10px 14px", display: "flex", alignItems: "center", gap: 10, fontSize: 11.5 }}>
          <div style={{
            width: 24, height: 24, borderRadius: 999,
            background: t.accent, color: t.bg, fontWeight: 600,
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: 10, fontFamily: t.fontMono,
          }}>{window.__AC_USER?.github_login?.[0]?.toUpperCase() || "?"}</div>
          <div style={{ flex: 1, lineHeight: 1.2 }}>
            <div style={{ color: t.fg, fontWeight: 500 }}>{window.__AC_USER?.github_login || "anonymous"}</div>
            <div style={{ color: t.fg3, fontSize: 10, fontFamily: t.fontMono }}>
              <StatusDot status="online" theme={t} size={5} /> connected
            </div>
          </div>
        </div>
      )}
    </aside>
  );
}

function SessionRow({ s, theme, active, onClick }) {
  const t = theme;
  const title = s.name || s.agent_type || "Session";
  return (
    <button onClick={onClick} style={{
      width: "100%", display: "block", textAlign: "left",
      padding: "8px 10px", background: active ? t.panel : "transparent",
      border: active ? `1px solid ${t.line2}` : "1px solid transparent",
      borderRadius: t.radius, color: t.fg, fontFamily: t.fontSans,
      cursor: "pointer", marginBottom: 2,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 2 }}>
        <StatusDot status={s.status} theme={t} />
        <div style={{
          fontSize: 12.5, fontWeight: active ? 600 : 500,
          flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
        }}>{title}</div>
      </div>
      <div style={{ fontSize: 10.5, fontFamily: t.fontMono, color: t.fg3, display: "flex", gap: 8 }}>
        <span>{s.status}</span>
        <span style={{ opacity: 0.6 }}>-</span>
        <span>{timeAgo(s.updated_at || s.created_at)}</span>
      </div>
    </button>
  );
}

function timeAgo(dateStr) {
  if (!dateStr) return "";
  // SQLite datetime('now') returns UTC without 'Z' — force UTC parsing
  const d = String(dateStr);
  const ts = (d.includes('T') || d.includes('Z') || d.includes('+')) ? d : d.replace(' ', 'T') + 'Z';
  const diff = Date.now() - new Date(ts).getTime();
  if (diff < 60000) return "just now";
  if (diff < 3600000) return Math.floor(diff / 60000) + "m ago";
  if (diff < 86400000) return Math.floor(diff / 3600000) + "h ago";
  return Math.floor(diff / 86400000) + "d ago";
}

function iconBtn(t) {
  return {
    width: 24, height: 24, display: "flex", alignItems: "center", justifyContent: "center",
    background: "transparent", border: "none", color: t.fg2, cursor: "pointer", borderRadius: t.radius,
  };
}

window.Sidebar = Sidebar;
window.StatusDot = StatusDot;
window.iconBtn = iconBtn;
window.timeAgo = timeAgo;
