const { useState, useEffect } = React;

const Sidebar = ({ current, onChange, user, onLogout }) => {
  const I = window.Icons;
  const sb = window.supabaseClient;
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [promoPending, setPromoPending] = useState(0);
  const [verifPending, setVerifPending] = useState(0);

  useEffect(() => {
    if (!sb) return;
    const fetchCounts = async () => {
      const [promoRes, kycRes, driverRes] = await Promise.all([
        sb.from("ad_campaigns").select("*", { count: "exact", head: true }).eq("status", "pending_review"),
        sb.from("kyc_submissions").select("*", { count: "exact", head: true }).eq("status", "pending"),
        sb.from("delivery_partners").select("*", { count: "exact", head: true }).eq("status", "pending_approval"),
      ]);
      setPromoPending(promoRes.count ?? 0);
      setVerifPending((kycRes.count ?? 0) + (driverRes.count ?? 0));
    };
    fetchCounts();
    const interval = setInterval(fetchCounts, 60000);
    return () => clearInterval(interval);
  }, []);

  const sections = [
    { label: "Operations", items: [
      { id: "overview",       name: "Overview",       icon: I.pulse },
      { id: "dispatch",       name: "Delivery",       icon: I.truck },
      { id: "orders",         name: "Orders",         icon: I.cart },
      { id: "promotions",     name: "Promotions",     icon: I.ticket,  badgeAlert: promoPending > 0 ? String(promoPending) : null },
      { id: "verifications",  name: "Verifications",  icon: I.shield,  badgeAlert: verifPending > 0 ? String(verifPending) : null },
      { id: "notifications",  name: "Notifications",  icon: I.bell },
    ]},
    { label: "Catalog", items: [
      { id: "stores",      name: "Stores",      icon: I.store },
      { id: "products",    name: "Products",    icon: I.package },
      { id: "discovery",   name: "Discovery",   icon: I.layers },
      { id: "categories",  name: "Categories",  icon: I.compass },
    ]},
    { label: "People", items: [
      { id: "users",     name: "Users",     icon: I.users },
      { id: "drivers",   name: "Drivers",   icon: I.bike },
      { id: "emails",    name: "Emails",    icon: I.message },
      { id: "referrals", name: "Referrals", icon: I.users },
    ]},
    { label: "Money & Insight", items: [
      { id: "finance",    name: "Finance",    icon: I.coin },
      { id: "analytics",  name: "Analytics",  icon: I.bar },
      { id: "logs",       name: "Logs",       icon: I.list },
      { id: "config",     name: "Config",     icon: I.cog },
    ]},
  ];

  const bottomTabs = [
    { id: "orders",        name: "Orders",        icon: I.cart },
    { id: "dispatch",      name: "Delivery",      icon: I.truck },
    { id: "verifications", name: "Verif.",         icon: I.shield,  badgeAlert: verifPending > 0 ? String(verifPending) : null },
    { id: "promotions",    name: "Promotions",    icon: I.ticket,  badgeAlert: promoPending > 0 ? String(promoPending) : null },
  ];

  const handleNav = (id) => {
    onChange(id);
    setDrawerOpen(false);
  };

  return (
    <>
      {/* Desktop sidebar */}
      <aside className="sidebar" data-screen-label="Sidebar">
        <div className="brand">
          <div className="brand-mark">P</div>
          <div className="brand-name">Pipal</div>
          <div className="brand-env">prod</div>
        </div>

        {sections.map((sec) => (
          <div className="nav-section" key={sec.label}>
            <div className="nav-label">{sec.label}</div>
            {sec.items.map((it) => (
              <div
                key={it.id}
                className={"nav-item" + (current === it.id ? " active" : "")}
                onClick={() => onChange(it.id)}
              >
                <it.icon className="nav-icon"/>
                <span>{it.name}</span>
                {it.badge && <span className="nav-badge">{it.badge}</span>}
                {it.badgeAlert && <span className="nav-badge alert">{it.badgeAlert}</span>}
              </div>
            ))}
          </div>
        ))}

        <div className="sidebar-foot">
          <div className="avatar">{(user?.email?.[0] ?? "?").toUpperCase()}</div>
          <div className="user-meta">
            <div className="n">{user?.email ?? ""}</div>
            <div className="r">admin</div>
          </div>
          <div style={{cursor:"pointer", color:"var(--ink-3)", display:"grid", placeItems:"center"}} title="Sign out" onClick={onLogout}>
            <I.arrowR size={14}/>
          </div>
        </div>
      </aside>

      {/* Mobile bottom tab bar */}
      <nav className="bottom-nav">
        {bottomTabs.map((tab) => (
          <button
            key={tab.id}
            className={"bottom-tab" + (current === tab.id ? " active" : "")}
            onClick={() => handleNav(tab.id)}
          >
            <span
              className={tab.badgeAlert ? "bottom-tab-dot" : ""}
              data-badge={tab.badgeAlert || undefined}
            >
              <tab.icon size={20}/>
            </span>
            <span>{tab.name}</span>
          </button>
        ))}
        <button
          className={"bottom-tab" + (drawerOpen ? " active" : "")}
          onClick={() => setDrawerOpen(v => !v)}
        >
          <I.list size={20}/>
          <span>All</span>
        </button>
      </nav>

      {/* Mobile drawer */}
      {drawerOpen && (
        <>
          <div className="mobile-drawer-overlay" onClick={() => setDrawerOpen(false)}/>
          <div className="mobile-drawer">
            <div className="drawer-handle"/>
            <div style={{ padding: "4px 0 12px" }}>
              {sections.map((sec) => (
                <div key={sec.label} style={{ padding: "0 8px" }}>
                  <div className="nav-label">{sec.label}</div>
                  {sec.items.map((it) => (
                    <div
                      key={it.id}
                      className={"nav-item" + (current === it.id ? " active" : "")}
                      onClick={() => handleNav(it.id)}
                    >
                      <it.icon className="nav-icon"/>
                      <span>{it.name}</span>
                      {it.badge && <span className="nav-badge">{it.badge}</span>}
                      {it.badgeAlert && <span className="nav-badge alert">{it.badgeAlert}</span>}
                    </div>
                  ))}
                </div>
              ))}
              <div style={{ padding: "12px 16px 4px", borderTop: "1px solid var(--hairline)", marginTop: 8, display: "flex", alignItems: "center", gap: 10 }}>
                <div className="avatar">{(user?.email?.[0] ?? "?").toUpperCase()}</div>
                <div className="user-meta">
                  <div className="n">{user?.email ?? ""}</div>
                  <div className="r">admin</div>
                </div>
              </div>
            </div>
          </div>
        </>
      )}
    </>
  );
};

window.Sidebar = Sidebar;
