// Shared marketing-page allowlist for analytics/marketing pixels (GA4, LinkedIn).
//
// PRIVACY / HIPAA: MBHS collects behavioral-health data. Trackers MUST NOT load
// or fire on any page that shows screening questions, answers, scores, or
// reports. We enforce this with a default-deny allowlist: trackers load ONLY on
// the marketing/funnel pages listed below. Anything not explicitly allowed — and
// every clinical route — is denied.

import { locales } from '@/i18n/routing';

// Marketing / funnel pages where trackers are allowed (locale-stripped paths).
const ALLOWED_MARKETING_PATHS = [
  '/', // home / landing (Pricing is a section on this page)
  '/signup', // signup start + inline success ("thank-you")
  '/login',
  '/forgot-password',
  '/contact',
  '/terms',
  '/privacy-policy',
  '/cookie-policy',
  '/disclaimer',
  '/safety',
  '/refund',
] as const;

// Clinical / health-data routes where trackers must NEVER load, even if the path
// somehow matched the allowlist. Belt-and-suspenders for the privacy rule.
const FORBIDDEN_CLINICAL_PATHS = [
  '/assessment',
  '/individual',
  '/practitioner',
  '/practice-manager',
  '/admin',
  '/sample-report',
] as const;

/**
 * Strip a leading locale segment (e.g. `/en/signup` -> `/signup`).
 * `usePathname` from `next/navigation` returns the locale-prefixed path
 * (basePath is already removed by Next.js).
 */
function stripLocale(pathname: string): string {
  const segments = pathname.split('/'); // ['', 'en', 'signup']
  if (segments.length > 1 && (locales as readonly string[]).includes(segments[1])) {
    const rest = '/' + segments.slice(2).join('/');
    return rest === '/' ? '/' : rest.replace(/\/$/, '');
  }
  return pathname.replace(/\/$/, '') || '/';
}

function matchesPrefix(path: string, prefix: string): boolean {
  if (prefix === '/') return path === '/';
  return path === prefix || path.startsWith(prefix + '/');
}

/**
 * True only for marketing/funnel pages. Default-deny: clinical routes and any
 * unlisted route return false so trackers never load there.
 */
export function isMarketingPath(pathname: string | null): boolean {
  if (!pathname) return false;
  const path = stripLocale(pathname);

  if (FORBIDDEN_CLINICAL_PATHS.some((p) => matchesPrefix(path, p))) return false;

  return ALLOWED_MARKETING_PATHS.some((p) => matchesPrefix(path, p));
}
