/* Bonyan ERP — dark side navigation rail */
const BNY_NAV = [
  { id: "dashboard", label: "الرئيسية", labelLong: "الرئيسية", icon: "dashboard", perm: "dashboard" },
  { id: "pos", label: "فاتورة", labelLong: "فاتورة جديدة", icon: "invoice", perm: "pos" },
  { id: "invoices", label: "الفواتير", labelLong: "الفواتير", icon: "invoice", perm: "invoices_view" },
  { id: "customers", label: "العملاء", labelLong: "العملاء", icon: "users", perm: "customers" },
  { id: "suppliers", label: "الموردون", labelLong: "الموردون", icon: "supplier", perm: "suppliers" },
  { id: "accounts", label: "الحسابات", labelLong: "الحسابات", icon: "wallet", perm: "customers" },
  { id: "inventory", label: "المواد", labelLong: "المواد", icon: "inventory", perm: "inventory_view" },
  { id: "warehouses", label: "المخازن", labelLong: "إدارة المخازن", icon: "building", perm: "inventory_edit" },
  { id: "pricing", label: "التسعير", labelLong: "التسعير", icon: "card", perm: "pricing" },
  { id: "reports", label: "التقارير", labelLong: "التقارير", icon: "chart", perm: "reports" },
  // مجموعة الإعدادات: قائمة منسدلة تضم إعدادات الفاتورة والصلاحيات والحركات
  { id: "settings-group", label: "الإعدادات", labelLong: "الإعدادات", icon: "settings", children: [
    { id: "settings", label: "الفاتورة", labelLong: "إعدادات الفاتورة", icon: "printer", perm: "invoice_settings" },
    { id: "users", label: "الصلاحيات", labelLong: "صلاحيات المستخدمين", icon: "users", perm: "users_manage" },
    { id: "activity", label: "الحركات", labelLong: "الحركات", icon: "history", perm: "activity" },
  ]},
];
/* قائمة مسطّحة (للجوال) — تفرد عناصر المجموعات */
function bnyAllowedNav(user) {
  const out = [];
  BNY_NAV.forEach((n) => {
    if (n.children) n.children.forEach((c) => { if (window.BnyCan(user, c.perm)) out.push(c); });
    else if (window.BnyCan(user, n.perm)) out.push(n);
  });
  return out;
}

function Rail({ active, onNav, user, onLogout }) {
  const I = window.BnyIcon;
  const D = window.BnyData;
  // عناصر المستوى الأول: عادية مسموحة + مجموعات فيها عنصر مسموح واحد على الأقل
  const topNav = BNY_NAV.map((n) => {
    if (!n.children) return window.BnyCan(user, n.perm) ? n : null;
    const kids = n.children.filter((c) => window.BnyCan(user, c.perm));
    return kids.length ? { ...n, children: kids } : null;
  }).filter(Boolean);
  const groupOfActive = (n) => n.children && n.children.some((c) => c.id === active);
  const [openGroups, setOpenGroups] = React.useState(() => {
    const o = {}; topNav.forEach((n) => { if (groupOfActive(n)) o[n.id] = true; }); return o;
  });
  React.useEffect(() => { // افتح المجموعة تلقائيًا عند تفعيل أحد عناصرها
    topNav.forEach((n) => { if (groupOfActive(n)) setOpenGroups((s) => ({ ...s, [n.id]: true })); });
  }, [active]); // eslint-disable-line
  const roleName = (user && (D.roles.find((r) => r.id === user.role) || {}).name) || "";
  const initials = (user ? user.name : "").split(/[\s—-]+/).filter(Boolean).slice(0, 2).map((w) => w[0]).join("");
  const wrap = {
    width: "var(--rail-width)", flex: "none", background: "var(--bg-rail)",
    color: "#fff", display: "flex", flexDirection: "column",
    padding: "var(--space-6) var(--space-5)", gap: "var(--space-2)",
  };
  const item = (on) => ({
    display: "flex", alignItems: "center", gap: "var(--space-4)",
    padding: "var(--space-4) var(--space-5)", borderRadius: "var(--radius-md)",
    color: on ? "#fff" : "rgba(255,255,255,0.62)",
    background: on ? "rgba(255,255,255,0.10)" : "transparent",
    fontSize: "var(--text-sm)", fontWeight: on ? 600 : 500,
    cursor: "pointer", transition: "var(--transition-control)",
    borderInlineStart: on ? "3px solid var(--amber-500)" : "3px solid transparent",
  });
  return (
    <div style={wrap}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "4px 8px 20px" }}>
        <img src="../../assets/logo/bonyan-mark.svg" alt="" style={{ width: 34, height: 34 }} />
        <div style={{ display: "flex", flexDirection: "column", lineHeight: 1 }}>
          <span style={{ fontWeight: 700, fontSize: 22, color: "#fff" }}>بُن<span style={{ color: "var(--amber-400)" }}>يان</span></span>
          <span style={{ fontSize: 10, color: "rgba(255,255,255,0.5)", marginTop: 3 }}>نظام محاسبي متكامل</span>
        </div>
      </div>
      {topNav.map((n) => {
        const Icon = I[n.icon];
        if (!n.children) {
          return (
            <div key={n.id} style={item(active === n.id)} onClick={() => onNav(n.id)}>
              <Icon size={19} />
              <span>{n.labelLong}</span>
            </div>
          );
        }
        const open = !!openGroups[n.id];
        const hasActive = groupOfActive(n);
        return (
          <div key={n.id}>
            <div style={{ ...item(hasActive && !open), justifyContent: "flex-start" }}
              onClick={() => setOpenGroups((s) => ({ ...s, [n.id]: !s[n.id] }))} role="button" aria-expanded={open}>
              <Icon size={19} />
              <span style={{ flex: 1 }}>{n.labelLong}</span>
              <span style={{ display: "inline-flex", transition: "transform var(--dur-fast,160ms) ease", transform: open ? "rotate(-90deg)" : "rotate(0deg)" }}><I.chevron size={15} /></span>
            </div>
            {open && n.children.map((c) => {
              const CIcon = I[c.icon];
              return (
                <div key={c.id} style={{ ...item(active === c.id), marginInlineStart: 14, padding: "9px 14px", fontSize: "var(--text-xs)" }} onClick={() => onNav(c.id)}>
                  <CIcon size={16} />
                  <span>{c.labelLong}</span>
                </div>
              );
            })}
          </div>
        );
      })}
      <div style={{ marginTop: "auto", display: "flex", flexDirection: "column", gap: "var(--space-4)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 11px", background: "rgba(30,158,90,0.16)", borderRadius: "var(--radius-md)", fontSize: 12, color: "#7fe0ac" }}>
          <I.cloud size={16} /><span>تمت المزامنة · متصل</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 6px", borderTop: "1px solid rgba(255,255,255,0.1)", paddingTop: 14 }}>
          <div className="bny-avatar" style={{ background: "var(--amber-500)", color: "#1A1814" }}>{initials || "؟"}</div>
          <div style={{ lineHeight: 1.3, minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: "#fff", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 120 }}>{user ? user.name : ""}</div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)" }}>{roleName}</div>
          </div>
          <button onClick={onLogout} title="تسجيل الخروج" aria-label="تسجيل الخروج" style={{ border: 0, background: "rgba(255,255,255,0.08)", color: "rgba(255,255,255,0.75)", borderRadius: "var(--radius-md)", padding: "6px 10px", cursor: "pointer", fontSize: 12, fontFamily: "var(--font-body)", flex: "none" }}>خروج</button>
        </div>
      </div>
    </div>
  );
}
window.Rail = Rail;

/* Bonyan ERP — mobile side drawer (fires from the ☰ button, slides from the right in RTL) */
function MobileDrawer({ open, active, onNav, user, onLogout, onClose }) {
  const I = window.BnyIcon;
  const D = window.BnyData;
  // نفس بنية Rail: عناصر مسموحة + مجموعات فيها عنصر مسموح
  const topNav = BNY_NAV.map((n) => {
    if (!n.children) return window.BnyCan(user, n.perm) ? n : null;
    const kids = n.children.filter((c) => window.BnyCan(user, c.perm));
    return kids.length ? { ...n, children: kids } : null;
  }).filter(Boolean);
  const groupOfActive = (n) => n.children && n.children.some((c) => c.id === active);
  const [openGroups, setOpenGroups] = React.useState({});
  React.useEffect(() => {
    if (open) { const o = {}; topNav.forEach((n) => { if (groupOfActive(n)) o[n.id] = true; }); setOpenGroups(o); }
  }, [open, active]); // eslint-disable-line
  // امنع تمرير الخلفية أثناء فتح الدرج
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow; document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prev; };
  }, [open]);

  const roleName = (user && (D.roles.find((r) => r.id === user.role) || {}).name) || "";
  const initials = (user ? user.name : "").split(/[\s—-]+/).filter(Boolean).slice(0, 2).map((w) => w[0]).join("");
  const go = (id) => { onNav(id); onClose(); };
  const item = (on) => ({
    display: "flex", alignItems: "center", gap: 14, width: "100%", boxSizing: "border-box",
    padding: "13px 16px", borderRadius: "var(--radius-md)", border: 0, textAlign: "start",
    color: on ? "#fff" : "rgba(255,255,255,0.66)", background: on ? "rgba(255,255,255,0.10)" : "transparent",
    fontSize: 15, fontWeight: on ? 600 : 500, cursor: "pointer", fontFamily: "var(--font-body)",
    borderInlineStart: on ? "3px solid var(--amber-500)" : "3px solid transparent",
  });

  return (
    <div aria-hidden={!open} style={{ position: "fixed", inset: 0, zIndex: 1100, pointerEvents: open ? "auto" : "none" }}>
      {/* الخلفية المعتّمة */}
      <div onClick={onClose} style={{
        position: "absolute", inset: 0, background: "rgba(0,0,0,0.5)",
        opacity: open ? 1 : 0, transition: "opacity .25s ease",
      }} />
      {/* اللوحة المنزلقة من اليمين */}
      <div style={{
        position: "absolute", insetInlineStart: 0, top: 0, height: "100%",
        width: "min(84vw, 320px)", background: "var(--bg-rail)", color: "#fff",
        display: "flex", flexDirection: "column", boxShadow: "var(--shadow-xl)",
        transform: open ? "translateX(0)" : "translateX(100%)",
        transition: "transform .28s cubic-bezier(.4,0,.2,1)",
        paddingBottom: "env(safe-area-inset-bottom)",
      }}>
        {/* الرأس: الشعار + إغلاق */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 16px 14px", borderBottom: "1px solid rgba(255,255,255,0.1)" }}>
          <img src="../../assets/logo/bonyan-mark.svg" alt="" style={{ width: 32, height: 32 }} />
          <div style={{ display: "flex", flexDirection: "column", lineHeight: 1, flex: 1 }}>
            <span style={{ fontWeight: 700, fontSize: 20, color: "#fff" }}>بُن<span style={{ color: "var(--amber-400)" }}>يان</span></span>
            <span style={{ fontSize: 10, color: "rgba(255,255,255,0.5)", marginTop: 3 }}>نظام محاسبي متكامل</span>
          </div>
          <button onClick={onClose} aria-label="إغلاق القائمة" style={{ border: 0, background: "rgba(255,255,255,0.08)", color: "#fff", borderRadius: "var(--radius-md)", width: 36, height: 36, display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flex: "none" }}>
            <I.x size={20} />
          </button>
        </div>

        {/* الأقسام (قابلة للطي) */}
        <div style={{ flex: 1, overflowY: "auto", WebkitOverflowScrolling: "touch", padding: "10px 12px", display: "flex", flexDirection: "column", gap: 3 }}>
          {topNav.map((n) => {
            const Icon = I[n.icon];
            if (!n.children) {
              return (
                <button key={n.id} style={item(active === n.id)} onClick={() => go(n.id)}>
                  <Icon size={20} /><span>{n.labelLong}</span>
                </button>
              );
            }
            const isOpen = !!openGroups[n.id];
            const hasActive = groupOfActive(n);
            return (
              <div key={n.id}>
                <button style={item(hasActive && !isOpen)} aria-expanded={isOpen}
                  onClick={() => setOpenGroups((s) => ({ ...s, [n.id]: !s[n.id] }))}>
                  <Icon size={20} /><span style={{ flex: 1 }}>{n.labelLong}</span>
                  <span style={{ display: "inline-flex", transition: "transform .2s ease", transform: isOpen ? "rotate(-90deg)" : "rotate(0deg)" }}><I.chevron size={16} /></span>
                </button>
                {isOpen && n.children.map((c) => {
                  const CIcon = I[c.icon];
                  return (
                    <button key={c.id} style={{ ...item(active === c.id), marginInlineStart: 16, padding: "11px 14px", fontSize: 14 }} onClick={() => go(c.id)}>
                      <CIcon size={17} /><span>{c.labelLong}</span>
                    </button>
                  );
                })}
              </div>
            );
          })}
        </div>

        {/* التذييل: المستخدم + خروج */}
        <div style={{ padding: "12px 16px", borderTop: "1px solid rgba(255,255,255,0.1)", display: "flex", alignItems: "center", gap: 10 }}>
          <div className="bny-avatar" style={{ background: "var(--amber-500)", color: "#1A1814", flex: "none" }}>{initials || "؟"}</div>
          <div style={{ lineHeight: 1.3, minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: "#fff", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{user ? user.name : ""}</div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)" }}>{roleName}</div>
          </div>
          <button onClick={() => { onClose(); onLogout(); }} style={{ border: 0, background: "rgba(255,255,255,0.08)", color: "rgba(255,255,255,0.85)", borderRadius: "var(--radius-md)", padding: "9px 16px", cursor: "pointer", fontSize: 13, fontWeight: 600, fontFamily: "var(--font-body)", flex: "none" }}>خروج</button>
        </div>
      </div>
    </div>
  );
}
window.MobileDrawer = MobileDrawer;

/* توافق خلفي: MobileNav لم يعد يُعرض (استُبدل بالدرج الجانبي) */
window.MobileNav = function () { return null; };
