const { useEffect, useMemo, useRef, useState } = React;

const SIDEBAR_STATE_KEY = "katalyst_sidebar_collapsed";
const THEME_MODE_KEY = "katalyst_theme_mode";

const MENU_GROUPS = [
  {
    title: "Home Concepts",
    items: [
      { id: "admin-center", label: "Admin Control Center", icon: "🏠" },
      { id: "workspace-setup", label: "Workspace Setup", icon: "✨" },
      { id: "activity-hub", label: "Activity Hub", icon: "📊" },
    ],
  },
  {
    title: "Dashboards",
    items: [
      { id: "ecommerce", label: "E-commerce", icon: "🛒" },
      { id: "projects", label: "Projects", icon: "📁" },
      { id: "sales-orders", label: "Sales / Orders", icon: "🧾" },
      { id: "executive", label: "Executive", icon: "📈" },
    ],
  },
  {
    title: "Solutions",
    items: [
      { id: "crm", label: "CRM", icon: "👥" },
      { id: "education", label: "Education", icon: "🎓" },
      { id: "support", label: "Support Center", icon: "💬" },
    ],
  },
];

function getStoredSidebarState() {
  try {
    return localStorage.getItem(SIDEBAR_STATE_KEY) === "1";
  } catch {
    return false;
  }
}

function getStoredThemeMode() {
  try {
    const saved = localStorage.getItem(THEME_MODE_KEY);
    if (saved === "light" || saved === "dark" || saved === "system") {
      return saved;
    }
  } catch {
    // Ignore storage errors and fall back to system mode.
  }
  return "system";
}

function getSystemTheme() {
  if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) {
    return "dark";
  }
  return "light";
}

function applyTheme(themeMode) {
  const resolvedTheme = themeMode === "system" ? getSystemTheme() : themeMode;
  document.body.setAttribute("data-theme", resolvedTheme);
}

function App() {
  const profileRef = useRef(null);
  const [isCollapsed, setIsCollapsed] = useState(getStoredSidebarState);
  const [activeMenu, setActiveMenu] = useState("admin-center");
  const [isProfileOpen, setIsProfileOpen] = useState(false);
  const [themeMode, setThemeMode] = useState(getStoredThemeMode);

  useEffect(() => {
    applyTheme(themeMode);

    try {
      localStorage.setItem(THEME_MODE_KEY, themeMode);
    } catch {
      // Ignore write errors.
    }

    const media = window.matchMedia("(prefers-color-scheme: dark)");
    const onThemeChange = () => {
      if (themeMode === "system") {
        applyTheme("system");
      }
    };

    media.addEventListener("change", onThemeChange);
    return () => media.removeEventListener("change", onThemeChange);
  }, [themeMode]);

  useEffect(() => {
    try {
      localStorage.setItem(SIDEBAR_STATE_KEY, isCollapsed ? "1" : "0");
    } catch {
      // Ignore write errors.
    }
  }, [isCollapsed]);

  useEffect(() => {
    const onClickOutside = (event) => {
      if (profileRef.current && !profileRef.current.contains(event.target)) {
        setIsProfileOpen(false);
      }
    };
    document.addEventListener("click", onClickOutside);
    return () => document.removeEventListener("click", onClickOutside);
  }, []);

  const activeLabel = useMemo(() => {
    for (const group of MENU_GROUPS) {
      const found = group.items.find((item) => item.id === activeMenu);
      if (found) return found.label;
    }
    return "Admin Control Center";
  }, [activeMenu]);

  return (
    <div className="k-shell">
      <header className="k-header">
        <div className="k-header-left">
          <button
            type="button"
            className="k-collapse-btn"
            onClick={() => setIsCollapsed((prev) => !prev)}
            title="Expand/Collapse sidebar"
          >
            {isCollapsed ? "→" : "←"}
          </button>

          <div className="k-brand">
            <span className="k-logo" aria-hidden="true"></span>
            <span className="k-brand-name">Katalyst</span>
          </div>
        </div>

        <input
          className="k-search"
          type="search"
          placeholder="Search or type a command..."
          aria-label="Search"
        />

        <div className="k-header-right" ref={profileRef}>
          <button
            type="button"
            className="k-profile-btn"
            onClick={() => setIsProfileOpen((prev) => !prev)}
          >
            <span className="k-avatar">AD</span>
            <span>Admin User</span>
          </button>

          {isProfileOpen && (
            <div className="k-profile-menu">
              <p className="k-menu-email">admin@example.com</p>
              <p className="k-mode-title">Appearance</p>
              <div className="k-mode-row">
                <button
                  type="button"
                  className={`k-mode-btn ${themeMode === "light" ? "active" : ""}`}
                  onClick={() => setThemeMode("light")}
                >
                  Light
                </button>
                <button
                  type="button"
                  className={`k-mode-btn ${themeMode === "dark" ? "active" : ""}`}
                  onClick={() => setThemeMode("dark")}
                >
                  Dark
                </button>
                <button
                  type="button"
                  className={`k-mode-btn ${themeMode === "system" ? "active" : ""}`}
                  onClick={() => setThemeMode("system")}
                >
                  System
                </button>
              </div>
            </div>
          )}
        </div>
      </header>

      <div className="k-layout" style={{ "--sidebar-w": isCollapsed ? "76px" : "250px" }}>
        <aside className={`k-sidebar ${isCollapsed ? "collapsed" : ""}`}>
          {MENU_GROUPS.map((group) => (
            <section key={group.title}>
              <h3 className="k-group-title">{group.title}</h3>
              {group.items.map((item) => (
                <button
                  key={item.id}
                  type="button"
                  className={`k-nav-btn ${activeMenu === item.id ? "active" : ""}`}
                  onClick={() => setActiveMenu(item.id)}
                  title={isCollapsed ? item.label : ""}
                >
                  <span className="k-nav-icon">{item.icon}</span>
                  <span className="k-nav-label">{item.label}</span>
                </button>
              ))}
            </section>
          ))}
        </aside>

        <main className="k-main">
          <section className="k-hero">
            <h1>{activeLabel}</h1>
            <p>
              React layout shell ready with sticky header, collapsible sidebar, and profile theme switch
              using Light / Dark / System modes.
            </p>
          </section>
        </main>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
