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

const navGroups = [
  {
    key: "dashboard",
    label: "Dashboard",
    standalone: true,
    items: [{ label: "Dashboard", to: "/" }],
  },
  {
    key: "work",
    label: "Arbeit",
    items: [
      { label: "Vorgänge", to: "/cases" },
      { label: "Fristen", to: "/deadlines" },
      { label: "Sitzungen", to: "/meetings" },
      { label: "TOP-Bestand", to: "/agenda-items" },
      { label: "Beschlüsse", to: "/decisions" },
      { label: "Reports", to: "/reports" },
      { label: "Finanzen", to: "/finance" },
      { label: "Aufgaben", to: "/tasks" },
      { label: "Kalender", to: "/calendar" },
      { label: "Dokumente", to: "/documents" },
      { label: "Kommentare", to: "/comments" },
      { label: "Benachrichtigungen", to: "/notifications" },
    ],
  },
  {
    key: "admin",
    label: "Administration",
    items: [
      { label: "Benutzer", to: "/users" },
      { label: "Ausschüsse", to: "/committees" },
      { label: "Abteilungen", to: "/departments" },
      { label: "Dokumentenkategorien", to: "/document-categories" },
      { label: "Öffentliche Dokumente", to: "/public-documents-admin" },
      { label: "Vorlagen / Formular-Editor", to: "/templates" },
      { label: "Rollen & Rechte", to: "/permissions" },
      { label: "Kummerkasten", to: "/kummerkasten-admin" },
      { label: "MwSt.-Sätze Finanzen", to: "/finance-tax-codes" },
      { 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 (
    <>
      <style>{`
        .app-shell {
          min-height: 100vh;
          display: grid;
          grid-template-columns: 280px minmax(0, 1fr);
          background: var(--app-bg, #f6f8fb);
        }

        .app-sidebar {
          background: var(--panel-bg, #ffffff);
          border-right: 1px solid rgba(15, 23, 42, 0.08);
          padding: 18px 14px;
          display: flex;
          flex-direction: column;
          gap: 14px;
          position: sticky;
          top: 0;
          height: 100vh;
          overflow: auto;
          z-index: 30;
        }

        .app-brand {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 12px;
          padding: 6px 8px 12px;
          border-bottom: 1px solid rgba(15, 23, 42, 0.08);
        }

        .app-brand-main {
          min-width: 0;
          display: flex;
          align-items: center;
          gap: 12px;
        }

        .app-brand-logo {
          width: 58px;
          max-height: 42px;
          flex: 0 0 auto;
          object-fit: contain;
          display: block;
        }

        .app-brand-title {
          font-weight: 800;
          font-size: 1.05rem;
        }

        .app-brand-subtitle {
          font-size: 0.85rem;
          opacity: 0.7;
        }

        .sidebar-groups {
          display: flex;
          flex-direction: column;
          gap: 10px;
        }

        .sidebar-group {
          border: 1px solid rgba(15, 23, 42, 0.07);
          border-radius: 14px;
          overflow: hidden;
          background: rgba(255, 255, 255, 0.8);
        }

        .sidebar-group.standalone {
          padding: 6px;
        }

        .sidebar-group-toggle {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 10px;
          border: 0;
          background: transparent;
          padding: 12px 14px;
          cursor: pointer;
          font-weight: 700;
          font-size: 0.95rem;
          text-align: left;
        }

        .sidebar-group-toggle:hover {
          background: rgba(15, 23, 42, 0.04);
        }

        .sidebar-chevron {
          transition: transform 0.2s ease;
          font-size: 0.9rem;
          opacity: 0.7;
        }

        .sidebar-chevron.open {
          transform: rotate(90deg);
        }

        .sidebar-links {
          display: flex;
          flex-direction: column;
          gap: 4px;
          padding: 0 8px 10px;
        }

        .sidebar-group.standalone .sidebar-links {
          padding: 0;
        }

        .sidebar-link {
          display: flex;
          align-items: center;
          min-height: 40px;
          padding: 9px 12px;
          border-radius: 10px;
          text-decoration: none;
          color: inherit;
          font-weight: 500;
          transition: background 0.15s ease, color 0.15s ease;
        }

        .sidebar-link:hover {
          background: rgba(15, 23, 42, 0.05);
        }

        .sidebar-link.active {
          background: rgba(37, 99, 235, 0.12);
          color: #1d4ed8;
          font-weight: 700;
        }

        .sidebar-footer {
          margin-top: auto;
          padding-top: 12px;
          border-top: 1px solid rgba(15, 23, 42, 0.08);
          display: grid;
          gap: 10px;
        }

        .user-card {
          display: grid;
          gap: 2px;
          padding: 10px 12px;
          border-radius: 12px;
          background: rgba(15, 23, 42, 0.04);
        }

        .app-main {
          min-width: 0;
          display: flex;
          flex-direction: column;
        }

        .app-topbar {
          display: none;
          align-items: center;
          justify-content: space-between;
          gap: 12px;
          padding: 12px 14px;
          background: var(--panel-bg, #fff);
          border-bottom: 1px solid rgba(15, 23, 42, 0.08);
          position: sticky;
          top: 0;
          z-index: 25;
        }

        .app-mobile-brand {
          display: flex;
          align-items: center;
          gap: 10px;
          font-weight: 800;
        }

        .app-mobile-brand-logo {
          width: 32px;
          max-height: 28px;
          object-fit: contain;
          display: block;
        }

        .app-content {
          min-width: 0;
          padding: 18px;
        }

        .menu-btn,
        .sidebar-close-btn {
          border: 1px solid rgba(15, 23, 42, 0.12);
          background: var(--panel-bg, #fff);
          border-radius: 10px;
          padding: 8px 10px;
          cursor: pointer;
          font-weight: 700;
        }

        .sidebar-close-btn {
          display: none;
        }

        .sidebar-backdrop {
          display: none;
        }

        @media (max-width: 980px) {
          .app-shell {
            grid-template-columns: 1fr;
          }

          .app-topbar {
            display: flex;
          }

          .app-sidebar {
            position: fixed;
            inset: 0 auto 0 0;
            width: min(320px, 86vw);
            transform: translateX(-100%);
            transition: transform 0.24s ease;
            box-shadow: 0 18px 50px rgba(0, 0, 0, 0.22);
          }

          .app-sidebar.open {
            transform: translateX(0);
          }

          .sidebar-close-btn {
            display: inline-flex;
          }

          .sidebar-backdrop {
            display: block;
            position: fixed;
            inset: 0;
            background: rgba(15, 23, 42, 0.45);
            z-index: 20;
          }

          .app-content {
            padding: 14px;
          }
        }
      `}</style>

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

        <aside className={`app-sidebar ${mobileOpen ? "open" : ""}`}>
          <div className="app-brand">
            <div className="app-brand-main">
              <img className="app-brand-logo" src={logo} alt="BR-Office Logo" />
              <div>
                <div className="app-brand-title">BR-Office</div>
                <div className="app-brand-subtitle">Navigation</div>
              </div>
            </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 visibleItems = group.items.filter((item) => canViewPath(user, item.to));
              if (!visibleItems.length) return null;
              const visibleGroup = { ...group, items: visibleItems };
              const groupOpen = group.standalone ? true : Boolean(openGroups[group.key]);
              const active = isGroupActive(visibleGroup, 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">
                      {visibleItems.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">
              <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="app-main">
          <div className="app-topbar">
            <button
              className="menu-btn"
              type="button"
              onClick={() => setMobileOpen(true)}
              aria-label="Menü öffnen"
            >
              ☰ Menü
            </button>
            <div className="app-mobile-brand">
              <img className="app-mobile-brand-logo" src={logo} alt="BR-Office Logo" />
              <strong>BR-Office</strong>
            </div>
          </div>

          <div className="app-content">
            {children}
          </div>
        </main>
      </div>
    </>
  );
}
