'use client';

import { useMemo } from 'react';
import { usePathname } from 'next/navigation';
import ProfileDashboardPage from '@/app/components/profile/ProfileDashboardPage';
import type { ProfileDashboardTab } from '@/app/profile/hooks/useProfileDashboardTabs';

type ResolvedProfileRoute = {
  tab: ProfileDashboardTab;
  selectedLinkStatsId: string | null;
};

function resolveProfileRoute(pathname: string): ResolvedProfileRoute {
  if (pathname === '/profile' || pathname === '/profile/') {
    return { tab: 'overview', selectedLinkStatsId: null };
  }

  if (pathname === '/profile/analytics' || pathname.startsWith('/profile/analytics/')) {
    return { tab: 'analytics', selectedLinkStatsId: null };
  }

  if (pathname === '/profile/pricing' || pathname.startsWith('/profile/pricing/')) {
    return { tab: 'pricing', selectedLinkStatsId: null };
  }

  if (pathname === '/profile/notebook' || pathname.startsWith('/profile/notebook/')) {
    return { tab: 'notebook', selectedLinkStatsId: null };
  }

  if (pathname === '/profile/links' || pathname === '/profile/links/') {
    return { tab: 'links', selectedLinkStatsId: null };
  }

  if (pathname.startsWith('/profile/links/')) {
    const rawLinkId = pathname.slice('/profile/links/'.length).split('/')[0]?.trim() || '';
    if (rawLinkId) {
      return {
        tab: 'links',
        selectedLinkStatsId: decodeURIComponent(rawLinkId),
      };
    }
    return { tab: 'links', selectedLinkStatsId: null };
  }

  return { tab: 'overview', selectedLinkStatsId: null };
}

export default function ProfileLayout() {
  const pathname = usePathname();

  const route = useMemo(() => resolveProfileRoute(pathname || '/profile'), [pathname]);

  return (
    <ProfileDashboardPage
      currentTab={route.tab}
      selectedLinkStatsId={route.selectedLinkStatsId}
    />
  );
}
