/* Sidebar + MobileNav + TopBar — role-aware */
const { useState: useStateSidebar } = React;

const CLIENT_NAV = [
  { id: "overview",  icon: "home",    label: "Overview" },
  { id: "machines",  icon: "grid",    label: "Mesin Saya" },
  { id: "profile",   icon: "user",    label: "Profil" },
];

const ADMIN_NAV = [
  { id: "overview",          icon: "home",      label: "Overview",       group: "main" },
  { id: "admin-clients",     icon: "users",     label: "Daftar Client",  group: "main" },
  { id: "admin-machines",    icon: "grid",      label: "Status Mesin",   group: "main" },
  { id: "admin-billing",     icon: "wallet",    label: "Billing",        group: "finance" },
  { id: "admin-invoices",    icon: "receipt",   label: "Invoice",        group: "finance" },
  { id: "admin-telemetron",  icon: "cpu",       label: "Telemetron",     group: "account" },
  { id: "admin-settings",    icon: "settings",  label: "Pengaturan",     group: "account" },
  { id: "profile",           icon: "user",      label: "Profil & Akun",  group: "account" },
];

function Sidebar() {
  const { route, navigate, logout, isAdmin, user } = useApp();

  const items = isAdmin ? ADMIN_NAV : CLIENT_NAV;
  const groups = isAdmin
    ? [
        { id: "main",    label: "Operasional" },
        { id: "finance", label: "Keuangan" },
        { id: "account", label: "Akun" },
      ]
    : [{ id: null }];

  const isActive = (id) =>
    route.name === id ||
    (id === "machines" && route.name.startsWith("machine"));

  const initial = user?.name?.charAt(0) || "?";

  return (
    <aside className="hidden md:flex flex-col w-64 bg-[#1A1A1A] text-stone-200 sticky top-0 h-screen p-5 overflow-y-auto">
      {/* Logo */}
      <div className="flex items-center gap-3 py-2 px-2">
        <img src="../assets/yappari-logo.png" className="w-10 h-10 rounded-full bg-white p-0.5" alt="" />
        <div className="leading-tight">
          <div className="font-jp text-[10px] font-bold text-[#FF2D55]">やっぱり！</div>
          <div className="font-display text-lg uppercase text-white">Yappari!</div>
        </div>
      </div>
      <div className="px-2 mt-1 mb-5 text-[10px] font-bold uppercase tracking-[0.22em] text-stone-500">
        {isAdmin ? "Admin Panel" : "Client Dashboard"}
      </div>

      {/* Admin badge */}
      {isAdmin && (
        <div className="mx-2 mb-4 px-3 py-2 rounded-xl bg-[#FF2D55]/15 border border-[#FF2D55]/30 flex items-center gap-2">
          <Icon name="shield" size={14} className="text-[#FF2D55]" />
          <span className="text-xs font-bold text-[#FF2D55] uppercase tracking-wider">Admin</span>
        </div>
      )}

      {/* Navigation */}
      <nav className="flex-1 flex flex-col gap-4">
        {groups.map(g => (
          <div key={g.id || "solo"}>
            {g.label && (
              <div className="text-[9px] font-bold uppercase tracking-[0.22em] text-stone-600 px-3 mb-1.5">{g.label}</div>
            )}
            <div className="flex flex-col gap-0.5">
              {items.filter(it => g.id === null || it.group === g.id).map(it => {
                const active = isActive(it.id);
                return (
                  <button
                    key={it.id}
                    onClick={() => navigate({ name: it.id })}
                    className={`group flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all ${
                      active
                        ? "bg-[#FF2D55] text-white shadow-[inset_0_0_0_1px_rgba(255,255,255,0.05)]"
                        : "text-stone-400 hover:text-white hover:bg-white/5"
                    }`}
                  >
                    <Icon name={it.icon} size={17} />
                    {it.label}
                    {active && <Icon name="chevronR" size={13} className="ml-auto" />}
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </nav>

      {/* Bottom */}
      <div className="mt-auto space-y-3 pt-4 border-t border-white/5">
        {!isAdmin && (
          <div className="bg-white/5 rounded-xl p-4 border border-white/10">
            <div className="text-[10px] uppercase tracking-widest text-stone-500 font-bold mb-1">Butuh bantuan?</div>
            <div className="text-sm text-white font-semibold">Hubungi Ines</div>
            <a href="https://wa.me/628976046500" target="_blank" rel="noopener"
               className="text-xs text-[#FF2D55] font-semibold hover:underline mt-1 inline-block">
              0897 604 6500 →
            </a>
          </div>
        )}
        <button
          onClick={logout}
          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-stone-400 hover:text-white hover:bg-white/5"
        >
          <Icon name="logout" size={17} /> Keluar
        </button>
        <div className="text-[10px] text-stone-600 px-2">© 2026 · INDIE Group</div>
      </div>
    </aside>
  );
}

function MobileNav() {
  const { route, navigate, isAdmin } = useApp();

  const items = isAdmin
    ? [
        { id: "overview",       icon: "home",    label: "Home" },
        { id: "admin-clients",  icon: "users",   label: "Client" },
        { id: "admin-machines", icon: "grid",    label: "Mesin" },
        { id: "admin-billing",  icon: "wallet",  label: "Billing" },
        { id: "profile",        icon: "user",    label: "Profil" },
      ]
    : [
        { id: "overview", icon: "home",  label: "Home" },
        { id: "machines", icon: "grid",  label: "Mesin" },
        { id: "profile",  icon: "user",  label: "Profil" },
      ];

  const isActive = (id) =>
    route.name === id || (id === "machines" && route.name.startsWith("machine"));

  return (
    <nav className="md:hidden fixed bottom-0 left-0 right-0 bg-white border-t border-stone-200 px-1 pb-[env(safe-area-inset-bottom)] z-40">
      <div className="flex justify-around">
        {items.map(it => {
          const active = isActive(it.id);
          return (
            <button
              key={it.id}
              onClick={() => navigate({ name: it.id })}
              className={`flex-1 py-2.5 flex flex-col items-center gap-0.5 ${active ? "text-[#FF2D55]" : "text-stone-500"}`}
            >
              <Icon name={it.icon} size={19} />
              <span className="text-[9px] font-bold uppercase tracking-wider">{it.label}</span>
            </button>
          );
        })}
      </div>
    </nav>
  );
}

function TopBar() {
  const { route, user, isAdmin, navigate, toast, machines } = useApp();

  const PAGE_TITLES = {
    overview:        "Overview",
    machines:        "Mesin Saya",
    profile:         "Profil & Akun",
    "machine-detail":   "Detail Mesin",
    "machine-renew":    "Perpanjang Kontrak",
    "payment-success":  "Pembayaran Berhasil",
    "payment-failed":   "Pembayaran Gagal",
    "admin-clients":    "Daftar Client",
    "admin-machines":   "Status Mesin",
    "admin-billing":    "Billing",
    "admin-invoices":   "Invoice",
    "admin-telemetron": "Telemetron",
    "admin-settings":   "Pengaturan Perusahaan",
  };

  const expiring = machines.filter(m => statusForMachine(m).tone === "warning").length;

  return (
    <header className="sticky top-0 z-30 bg-white/85 backdrop-blur border-b border-stone-200 px-5 md:px-8 py-3 flex items-center gap-4">
      <div className="md:hidden flex items-center gap-2">
        <img src="../assets/yappari-logo.png" className="w-8 h-8 rounded-full" alt="" />
        <span className="font-display text-base uppercase text-[#1A1A1A]">Yappari!</span>
      </div>
      <div className="hidden md:block">
        <div className="text-[10px] font-bold uppercase tracking-[0.18em] text-stone-500">
          {isAdmin ? "Admin Panel" : "Dashboard"}
        </div>
        <div className="font-semibold text-[#1A1A1A] text-sm">{PAGE_TITLES[route.name] || "Dashboard"}</div>
      </div>
      <div className="flex-1" />

      {/* Notification bell */}
      <button
        onClick={() => expiring > 0
          ? toast(`${expiring} mesin mendekati expired. Cek halaman Status Mesin.`, "warning")
          : toast("Tidak ada notifikasi baru.", "info")
        }
        className="relative p-2.5 rounded-full text-stone-600 hover:bg-stone-100"
      >
        <Icon name="bell" size={18} />
        {expiring > 0 && (
          <span className="absolute top-1.5 right-1.5 w-2 h-2 bg-[#FF2D55] rounded-full ring-2 ring-white" />
        )}
      </button>

      {/* User chip */}
      <div className="hidden sm:flex items-center gap-2.5 pl-3 border-l border-stone-200">
        <div className={`w-9 h-9 rounded-full flex items-center justify-center font-jp font-bold text-white ${isAdmin ? "bg-[#1A1A1A]" : "bg-[#FF2D55]"}`}>
          {user?.name?.charAt(0) || "?"}
        </div>
        <div className="leading-tight">
          <div className="text-sm font-semibold text-[#1A1A1A] flex items-center gap-1.5">
            {user?.name}
            {isAdmin && <Badge tone="danger" className="text-[9px] py-0.5 px-1.5">Admin</Badge>}
          </div>
          <div className="text-[11px] text-stone-500">{user?.email}</div>
        </div>
      </div>
    </header>
  );
}

// expose Icon name "users" if not in shared
const _usersIcon = <><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></>;

Object.assign(window, { Sidebar, MobileNav, TopBar });
