'use client';

import { Suspense, useEffect, useState } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import Cookies from 'js-cookie';
import Sidebar from '@/components/Sidebar';
import Header from '@/components/Header';
import { AuthProvider, useAuth } from '@/components/auth-context';
import PublicJobsView from '@/components/careers/PublicJobsView';
import DotLoader from '@/components/DotLoader';

// Paths under /jobs that anonymous visitors may view read-only: the list (/jobs)
// and a single JD (/jobs/<id>). Sub-routes like /jobs/<id>/pipeline stay private.
function isPublicJobsPath(pathname: string): boolean {
  return pathname === '/jobs' || /^\/jobs\/[^/]+$/.test(pathname);
}

// Header titles per route. Layouts persist across navigation, so the Header
// can't receive a per-page prop anymore — the path decides the title instead.
const EXACT_TITLES: Record<string, string> = {
  '/dashboard': 'Dashboard',
  '/jobs': 'Job Descriptions',
  '/candidates': 'Candidate Pipeline',
  '/candidates/add': 'Add Candidate',
  '/clients': 'Client Management',
  '/profile': 'My Profile',
  '/reports': 'Reports',
  '/reports/candidate-reports': 'Candidate Reports',
  '/reports/overall-dashboard': 'Overall ATS Dashboard',
  '/master-skills': 'Master Skills',
  '/admins/users': 'User Management',
  '/admins/recruiters': 'Recruiter Management',
  '/admins/assigned-recruiters': 'Assigned Recruiters Analytics',
  '/admins/roles': 'Groups & Permissions',
  '/admins/menus': 'Menus',
  '/admins/login-history': 'Login History',
  '/admins/password-policy': 'Password Policy',
  '/admins/pipeline-stages': 'Pipeline Stages',
  '/admins/rank-parameters': 'AI Ranking Parameters',
  '/admins/llm-providers': 'AI / LLM Providers',
  '/admins/agents': 'Morning Efficiency Agent',
  '/master-data/city': 'City Master Data',
  '/master-data/state': 'State Master Data',
  '/master-data/country': 'Country Master Data',
  '/master-data/designation': 'Master Designations',
  '/master-data/education': 'Master Education',
  '/master-data/notification-templates': 'Notification Templates',
  '/master-data/company-linkedin': 'Company LinkedIn',
  '/master-data/notice-period': 'Master Notice Period',
  '/master-data/annual-ctc': 'Master Annual CTC',
};

function titleFor(pathname: string): string {
  if (EXACT_TITLES[pathname]) return EXACT_TITLES[pathname];
  if (/^\/jobs\/[^/]+\/pipeline$/.test(pathname)) return 'Job Pipeline';
  if (/^\/jobs\/[^/]+\/ai-screening$/.test(pathname)) return 'AI Candidate Calling Screening';
  if (/^\/jobs\/[^/]+$/.test(pathname)) return 'Job Details';
  if (/^\/candidates\/[^/]+$/.test(pathname)) return 'Candidate Details';
  const roleUsers = pathname.match(/^\/admins\/roles\/([^/]+)\/users$/);
  if (roleUsers) {
    const role = decodeURIComponent(roleUsers[1]);
    return `Roles & Permissions > ${role.charAt(0) + role.slice(1).toLowerCase()}`;
  }
  return 'TA-ATS Portal';
}

function PortalFrame({ children }: { children: React.ReactNode }) {
  const { user } = useAuth();
  const pathname = usePathname();

  // Single gate for the whole portal: shows only on the first app load
  // (client-side navigation never unmounts this layout).
  if (!user) {
    return (
      <div className="min-h-screen bg-[#f3f3f9] dark:bg-slate-950 flex items-center justify-center">
        <DotLoader size={12} />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#f3f3f9] dark:bg-slate-950 text-slate-900 dark:text-slate-100 flex flex-row font-sans transition-colors duration-200">
      <Sidebar />
      <div className="flex-1 flex flex-col overflow-hidden">
        <Header title={titleFor(pathname)} />
        {children}
      </div>
    </div>
  );
}

function PortalLayoutInner({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const searchParams = useSearchParams();
  // Decide only after mount so SSR and the first client render agree (reading a
  // cookie during SSR would cause a hydration mismatch).
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);

  const hasToken = mounted && !!Cookies.get('access_token');
  // A JD-approval email's "View JD" link (/jobs?review=<token>) is a private
  // deep link, not the public jobs browse page — an anonymous visitor must be
  // sent to log in first, never silently shown the public listing instead.
  const reviewToken = pathname === '/jobs' ? searchParams.get('review') : null;

  useEffect(() => {
    if (mounted && !hasToken && reviewToken) {
      router.replace(`/login?review=${encodeURIComponent(reviewToken)}`);
    }
  }, [mounted, hasToken, reviewToken, router]);

  if (!mounted) return null;
  if (!hasToken && reviewToken) return null; // redirecting to /login

  // Anonymous visitor (no token) on a public jobs path → show the read-only
  // public view and DO NOT mount AuthProvider (which would redirect to /login).
  // Logged-in users fall through to the normal protected portal below.
  if (!hasToken && isPublicJobsPath(pathname)) {
    return <PublicJobsView pathname={pathname} />;
  }

  return (
    <AuthProvider>
      <PortalFrame>{children}</PortalFrame>
    </AuthProvider>
  );
}

export default function PortalLayout({ children }: { children: React.ReactNode }) {
  // useSearchParams() requires a Suspense boundary.
  return (
    <Suspense fallback={null}>
      <PortalLayoutInner>{children}</PortalLayoutInner>
    </Suspense>
  );
}
