import { useEffect } from 'react';
import { useLocation } from 'react-router';
import { useGlobal } from 'hooks/useGlobal';

type TitleRule = { match: (p: string) => boolean; title: string };

// Default page title per route — most specific first.
const RULES: TitleRule[] = [
  { match: (p) => p === '/', title: 'Home' },
  { match: (p) => p.startsWith('/settings/ai'), title: 'AI Settings' },
  { match: (p) => p.startsWith('/settings/profile'), title: 'Profile' },
  { match: (p) => p.startsWith('/settings/integrations'), title: 'Integrations' },
  { match: (p) => p.startsWith('/settings/apps'), title: 'App Settings' },
  { match: (p) => p.startsWith('/settings'), title: 'Settings' },
  { match: (p) => p.startsWith('/chat'), title: 'Chat' },
  { match: (p) => p.startsWith('/email'), title: 'Email' },
  { match: (p) => p.startsWith('/files'), title: 'Files' },
  { match: (p) => p.startsWith('/music'), title: 'Music' },
  { match: (p) => p.startsWith('/soulseek'), title: 'Soulseek' },
  { match: (p) => p.startsWith('/system-monitor'), title: 'System Monitor' },
  { match: (p) => p.startsWith('/code-editor'), title: 'Code Editor' },
  { match: (p) => p.startsWith('/projects'), title: 'Projects' },
  { match: (p) => p.startsWith('/task-logs'), title: 'Task Logs' },
  { match: (p) => p.startsWith('/tasks'), title: 'Tasks' },
  { match: (p) => p.startsWith('/jobs'), title: 'Jobs' },
  { match: (p) => p.startsWith('/skills'), title: 'Skills' },
  { match: (p) => p.startsWith('/processes'), title: 'Processes' },
  { match: (p) => p.startsWith('/dashboards'), title: 'Dashboards' },
  { match: (p) => p.startsWith('/terminal'), title: 'Terminal' },
  { match: (p) => p.startsWith('/browser'), title: 'Browser' },
  { match: (p) => p.startsWith('/desktop'), title: 'Desktop' },
  { match: (p) => p.startsWith('/plans'), title: 'Plans' },
];

export function titleForPath(pathname: string): string {
  return RULES.find((r) => r.match(pathname))?.title ?? 'Officer';
}

/** The current page title — shared (header ↔ tab), editable, per-tab (not persisted). */
export const usePageTitle = () => useGlobal<string>('PAGE_TITLE', 'Officer');

/**
 * Mount once in the dashboard layout: reset the title to the route default on navigation, and mirror
 * whatever the title is into the browser tab. Editing the title in the header just sets this value,
 * so the tab updates live; navigating away resets it (no persistence, by design).
 */
export function usePageTitleSync(): void {
  const { pathname } = useLocation();
  const [title, setTitle] = usePageTitle();

  // Route default — depends only on the path, so an in-place header edit is never clobbered.
  useEffect(() => {
    setTitle(titleForPath(pathname));
  }, [pathname]);

  useEffect(() => {
    document.title = title || 'Officer';
  }, [title]);
}
