// Sidebar + Topbar shell layout for Seeding Hub dashboard.
// Sidebar: 3 nav groups (Operate/Configure/System), collapsible.
// Topbar: breadcrumbs + user. List search lives next to All/Telegram/Zalo chips.

const Sidebar = ({ active, onNavigate, collapsed, onToggleCollapsed, currentUser }) => {
  const isAdmin = currentUser?.role === "admin";

  const groups = [
    {
      label: "Operate",
      items: [
        { id: "dashboard", label: "Dashboard", icon: I.Home },
        { id: "sessions", label: "Active Sessions", icon: I.Radio },
        { id: "events", label: "Event Stream", icon: I.Activity },
      ],
    },
    {
      label: "Configure",
      items: [
        { id: "bots", label: "Bots", icon: I.Bot },
        { id: "configs", label: "Bot Configs", icon: I.Workflow },
        { id: "sources", label: "Source", icon: I.Radio },
        { id: "targets", label: "Target", icon: I.MessagesSquare },
        { id: "react-campaigns", label: "Auto React", icon: I.Activity },
        { id: "ai", label: "AI Rewrite", icon: I.Sparkles },
        { id: "ocr-image", label: "OCR Image", icon: I.Image },
      ],
    },
    {
      label: "System",
      items: [
        { id: "auth", label: "Auth & 2FA", icon: I.Key },
        // Admin-only nav items
        ...(isAdmin ? [{ id: "users", label: "Users", icon: I.Users }] : []),
        { id: "proxies", label: "Proxies", icon: I.Server },
        { id: "settings", label: "Settings", icon: I.Settings },
      ],
    },
  ];

  return (
    <aside className={`sidebar ${collapsed ? "collapsed" : ""}`}>
      <div className="sidebar-head">
        <div className="brand-mark">S</div>
        <div className="brand-text">Seeding Hub</div>
      </div>

      <div className="nav">
        {groups.map((g) => (
          <div className="nav-group" key={g.label}>
            <div className="nav-section-label">{g.label}</div>
            {g.items.map((it) => {
              const Ic = it.icon;
              return (
                <button
                  key={it.id}
                  className={`nav-item ${active === it.id ? "active" : ""}`}
                  onClick={() => onNavigate(it.id)}
                  title={collapsed ? it.label : undefined}
                >
                  <Ic className="icon" />
                  <span className="nav-item-label">{it.label}</span>
                </button>
              );
            })}
          </div>
        ))}
      </div>

      <div className="sidebar-foot">
        <button
          className="nav-item"
          onClick={onToggleCollapsed}
          title={collapsed ? "Expand" : "Collapse"}
        >
          {collapsed ? <I.ChevronsRight className="icon" /> : <I.ChevronsLeft className="icon" />}
          <span className="nav-item-label">Collapse</span>
        </button>
      </div>
    </aside>
  );
};

const RestartButton = ({ currentUser }) => {
  const confirm = useConfirm();
  const toast = useToast();
  const [loading, setLoading] = React.useState(false);
  const allowedEmail = 'aetradingforex@gmail.com';

  const canRestart = currentUser && (
    currentUser.role === 'admin' || 
    String(currentUser.email || '').toLowerCase() === allowedEmail
  );

  const handleRestart = async () => {
    const ok = await confirm('Restart seeding-bot', 'This takes ~10 seconds. Continue?');
    if (!ok) return;

    setLoading(true);
    try {
      await SystemApi.restart();
      toast.success('Restarting seeding-bot...');
      setTimeout(() => window.location.reload(), 3000);
    } catch (e) {
      toast.error(e.message || 'Restart failed');
      setLoading(false);
    }
  };

  if (!canRestart) return null;
  return (
    <button
      className="btn ghost sm"
      onClick={handleRestart}
      disabled={loading}
      title="Restart seeding-bot"
      style={{ fontSize: 12, opacity: loading ? 0.6 : 1 }}
    >
      <I.Refresh size={14} />
      {loading ? ' Restarting...' : ' Restart'}
    </button>
  );
};

const Topbar = ({
  crumbs = [],
  currentUser,
  onLogout,
}) => (
  <header className="topbar">
    <div className="crumbs">
      {crumbs.map((c, i) => (
        <React.Fragment key={i}>
          {i > 0 && <I.ChevronRight className="sep" size={12} />}
          <span className={i === crumbs.length - 1 ? "current" : ""}>{c}</span>
        </React.Fragment>
      ))}
    </div>
    <div className="topbar-actions">
      {currentUser && (
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <RestartButton currentUser={currentUser} />
          <span style={{ fontSize: 12, color: "var(--fg-3)" }}>{currentUser.name}</span>
          {currentUser.role === "admin" && (
            <span className="badge" style={{ fontSize: 10, padding: "2px 6px" }}>Admin</span>
          )}
          <button
            className="btn ghost sm"
            onClick={onLogout}
            title="Sign out"
            style={{ fontSize: 12 }}
          >
            Sign out
          </button>
        </div>
      )}
    </div>
  </header>
);

Object.assign(window, { Sidebar, Topbar });
