import { useEffect, useMemo, useState } from "react";
import { NavLink, useLocation } from "react-router-dom";
import logo from "../assets/br-office-logo.png";

const navGroups = [
  {
    key: "dashboard",
    label: "Dashboard",
    standalone: true,
    items: [{ label: "Dashboard", to: "/" }],
  },
  {
    key: "work",
    label: "Arbeit",
    items: [
      { label: "Vorgänge", to: "/cases" },
      { label: "Sitzungen", to: "/meetings" },
      { label: "TOP-Bestand", to: "/agenda-items" },
      { label: "Beschlüsse", to: "/decisions" },
      { label: "Dokumente", to: "/documents" },
      { label: "Reports", to: "/reports" },
      { label: "Kalender", to: "/calendar" },
      { label: "Benachrichtigungen", to: "/notifications" },
    ],
  },
  {
    key: "admin",
    label: "Administration",
    items: [
      { label: "Benutzer", to: "/users" },
      { label: "Ausschüsse", to: "/committees" },
      { label: "Vorlagen / Formular-Editor", to: "/templates" },
      { label: "Sicherheit", to: "/security" },
      { label: "Audit", to: "/audit" },
    ],
  },
];

function isGroupActive(group, pathname) {
  return group.items.some((item) => {
    if (item.to === "/") return pathname === "/";
    return pathname === item.to || pathname.startsWith(`${item.to}/`);
  });
}

export default function Layout({ user, onLogout, children }) {
  const location = useLocation();
  const [mobileOpen, setMobileOpen] = useState(false);

  const initialOpenGroups = useMemo(() => {
    const next = {};
    for (const group of navGroups) {
      next[group.key] = group.standalone ? true : isGroupActive(group, location.pathname);
    }
    return next;
  }, [location.pathname]);

  const [openGroups, setOpenGroups] = useState(initialOpenGroups);

  useEffect(() => {
    setOpenGroups((prev) => {
      const next = { ...prev };
      for (const group of navGroups) {
        if (group.standalone) {
          next[group.key] = true;
        } else if (isGroupActive(group, location.pathname)) {
          next[group.key] = true;
        }
      }
      return next;
    });
    setMobileOpen(false);
  }, [location.pathname]);

  function toggleGroup(key) {
    setOpenGroups((prev) => ({ ...prev, [key]: !prev[key] }));
  }

  return (
    <div className="app-shell app-shell-modern">
      {mobileOpen ? <div className="sidebar-backdrop" onClick={() => setMobileOpen(false)} /> : null}

      <aside className={`sidebar glass sidebar-modern ${mobileOpen ? "open" : ""}`}>
        <div className="brand brand-modern">
          <img className="brand-logo" src={logo} alt="BR-Office Logo" />
          <div className="brand-copy">
            <h1>BR-Office</h1>
            <p>Navigation</p>
          </div>
          <button
            className="sidebar-close-btn"
            type="button"
            onClick={() => setMobileOpen(false)}
            aria-label="Menü schließen"
          >
            ×
          </button>
        </div>

        <nav className="sidebar-groups">
          {navGroups.map((group) => {
            const groupOpen = group.standalone ? true : Boolean(openGroups[group.key]);
            const active = isGroupActive(group, location.pathname);

            return (
              <div
                key={group.key}
                className={`sidebar-group ${group.standalone ? "standalone" : ""} ${active ? "active" : ""}`}
              >
                {!group.standalone ? (
                  <button
                    className="sidebar-group-toggle"
                    type="button"
                    onClick={() => toggleGroup(group.key)}
                  >
                    <span>{group.label}</span>
                    <span className={`sidebar-chevron ${groupOpen ? "open" : ""}`}>⌃</span>
                  </button>
                ) : null}

                {groupOpen ? (
                  <div className="sidebar-links">
                    {group.items.map((item) => (
                      <NavLink
                        key={item.to}
                        to={item.to}
                        end={item.to === "/"}
                        className={({ isActive }) => `sidebar-link ${isActive ? "active" : ""}`}
                      >
                        {item.label}
                      </NavLink>
                    ))}
                  </div>
                ) : null}
              </div>
            );
          })}
        </nav>

        <div className="sidebar-footer">
          <div className="user-card user-card-modern">
            <strong>{user?.full_name || user?.email || "Benutzer"}</strong>
            <span>{user?.role || ""}</span>
          </div>
          <button className="btn secondary" type="button" onClick={onLogout}>
            Abmelden
          </button>
        </div>
      </aside>

      <main className="content content-modern">
        <div className="app-topbar">
          <button
            className="menu-btn"
            type="button"
            onClick={() => setMobileOpen(true)}
            aria-label="Menü öffnen"
          >
            ☰ Menü
          </button>
          <div className="mobile-brand-inline">
            <img className="mobile-brand-logo" src={logo} alt="BR-Office Logo" />
            <strong>BR-Office</strong>
          </div>
        </div>

        {children}
      </main>
    </div>
  );
}
