"use client";

// ============================================================
// Dashboard shell — premium dark theme. Keeps the sidebar +
// header and swaps the inner content. Profile / Support / Rules
// render real views; other workspace modules show a placeholder.
// ============================================================

import { useEffect, useState } from "react";
import { Sidebar, NAV_ITEMS } from "./sidebar";
import { Topbar } from "./topbar";
import { ToastProvider, PageHead, Btn, Icon } from "./ui";
import { Profile } from "./profile";
import { Support } from "./support";
import { Rules } from "./rules";
import { AiAssistant } from "./ai-assistant";
import { TeamManagement } from "./team-management";
import { MessengerSdk } from "./messenger-sdk";
import { InboxSdk } from "./inbox-sdk";
import { Settings } from "./settings";
import { Projects } from "./projects";
import { NotificationCenter } from "./notification-center";
import { RealtimeProvider } from "@/lib/realtime";
import { SmartGallery } from "./smart-gallery";
import { Leads } from "./leads";
import { Verify } from "./verify";
import "../../app/dashboard/dashboard.css";

export function Dashboard() {
  const [theme, setTheme] = useState<"dark" | "light">("dark");
  const [active, setActive] = useState("dashboard");
  // Deep link from global search: which conversation to focus once we switch tabs.
  const [deepLink, setDeepLink] = useState<{ surface: "messenger" | "inbox"; threadId: string } | null>(null);

  function navigateToConversation(surface: "messenger" | "inbox", threadId: string) {
    setActive(surface);
    setDeepLink({ surface, threadId });
  }

  useEffect(() => {
    // Sync the persisted theme from localStorage (an external system) on mount.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    try { const t = localStorage.getItem("lup_dash_theme"); if (t === "light" || t === "dark") setTheme(t); } catch {}
  }, []);

  // Deep-link from a clicked push notification. Two paths from the service worker:
  //  - a tab was already open → it postMessages { type: 'notif-click', threadId } to focus here
  //  - no tab was open → it opens /dashboard?thread=<id>, which we read once on mount
  useEffect(() => {
    try {
      const t = new URLSearchParams(window.location.search).get("thread");
      if (t) {
        navigateToConversation("messenger", t);
        window.history.replaceState({}, "", window.location.pathname);
      }
    } catch {}
    if (!("serviceWorker" in navigator)) return;
    const onMessage = (e: MessageEvent) => {
      if (e.data?.type === "notif-click" && e.data.threadId) navigateToConversation("messenger", e.data.threadId);
    };
    navigator.serviceWorker.addEventListener("message", onMessage);
    return () => navigator.serviceWorker.removeEventListener("message", onMessage);
  }, []);
  function toggle() {
    setTheme((t) => { const n = t === "dark" ? "light" : "dark"; try { localStorage.setItem("lup_dash_theme", n); } catch {} return n; });
  }

  const item = NAV_ITEMS.find((i) => i.key === active);
  const title = item?.label ?? "Dashboard";
  const subtitle = item?.subtitle ?? "Workspace module";

  return (
    <div className="dash-root" data-theme={theme}>
      <RealtimeProvider>
      <Sidebar active={active} onSelect={setActive} />
      <div className="dash-main">
        <Topbar theme={theme} onToggle={toggle} title={title} subtitle={subtitle} onNavigate={navigateToConversation} />
        <div className="dash-content">
          <ToastProvider>
            <NotificationCenter active={active} onNavigate={navigateToConversation} />
            {active === "profile" ? <Profile />
              : active === "support" ? <Support />
              : active === "rules" ? <Rules />
              : active === "ai" ? <AiAssistant />
              : active === "messenger" ? <MessengerSdk focusThreadId={deepLink?.surface === "messenger" ? deepLink.threadId : null} />
              : active === "inbox" ? <InboxSdk focusThreadId={deepLink?.surface === "inbox" ? deepLink.threadId : null} />
              : active === "settings" ? <Settings />
              : active === "gallery" ? <SmartGallery theme={theme} />
              : active === "leads" ? <Leads />
              : active === "verify" ? <Verify />
              : active === "team" ? <TeamManagement />
              : active === "projects" ? <Projects />
              : <ComingSoon title={title} icon={item?.icon ?? "dashboard"} onGo={setActive} />}
          </ToastProvider>
        </div>
      </div>
      </RealtimeProvider>
    </div>
  );
}

// Placeholder for workspace modules that don't have a view yet — keeps the
// full navigation coherent and points users to the live sections.
function ComingSoon({ title, icon, onGo }: { title: string; icon: string; onGo: (k: string) => void }) {
  return (
    <div className="view">
      <PageHead eyebrow="Workspace" title={title} subtitle="This module is part of the LynkedUp Pro workspace." icon={icon} />
      <div className="card coming-soon">
        <span className="coming-soon-ic"><Icon name={icon} size={34} /></span>
        <h3>{title} is coming soon</h3>
        <p>This area is reserved for the {title} module. In the meantime, the account experience is fully built out.</p>
        <div className="coming-soon-actions">
          <Btn icon="user" onClick={() => onGo("profile")}>Open Profile</Btn>
          <Btn variant="outline" icon="chat" onClick={() => onGo("support")}>Support Center</Btn>
          <Btn variant="ghost" icon="check-circle" onClick={() => onGo("rules")}>Rules</Btn>
        </div>
      </div>
    </div>
  );
}
