import { cookies } from 'next/headers';

export const locales = ['en', 'id'] as const;

export type Locale = (typeof locales)[number];

export const defaultLocale: Locale = 'id';
export const localeCookieName = 'wa_locale';

type Dictionary = {
  common: {
    appName: string;
    openDashboard: string;
    language: string;
    english: string;
    indonesian: string;
    logout: string;
    loading: string;
    save: string;
    search: string;
    adminUser: string;
    superAdmin: string;
    helpCenter: string;
    overview: string;
  };
  home: {
    title: string;
    description: string;
  };
  login: {
    title: string;
    description: string;
    email: string;
    password: string;
    submit: string;
    goToDashboard: string;
    invalidCredentials: string;
    emailLabel: string;
    passwordLabel: string;
    forgotPassword: string;
    rememberMe: string;
    accessVia: string;
    google: string;
    sso: string;
    newToPlatform: string;
    applyAccess: string;
    privacyPolicy: string;
    termsOfService: string;
    helpCenter: string;
    securityPreview: string;
    loginHelp: string;
    twoFactorPreview: string;
    showPassword: string;
    hidePassword: string;
  };
  twoFactor: {
    title: string;
    description: string;
    verify: string;
    backToLogin: string;
    needHelp: string;
    appTitle: string;
    appDescription: string;
    securityTitle: string;
    securityDescription: string;
    placeholderBadge: string;
    placeholderBody: string;
  };
  dashboard: {
    title: string;
    navOverview: string;
    navContacts: string;
    navCampaigns: string;
    navTemplates: string;
    navSettings: string;
    navWebhooks: string;
    navConversations: string;
    navUsers: string;
    navRoles: string;
    navLogs: string;
    totalContacts: string;
    webhookEvents: string;
    deliveredRate: string;
    webhookHealth: string;
    newMessage: string;
  };
  contacts: {
    title: string;
    submit: string;
    empty: string;
    name: string;
    phoneNumber: string;
    email: string;
    company: string;
    notes: string;
    createSuccess: string;
  };
  settings: {
    title: string;
    description: string;
  };
  webhooks: {
    title: string;
    empty: string;
  };
};

const dictionaries: Record<Locale, Dictionary> = {
  en: {
    common: {
      appName: 'BizOne',
      openDashboard: 'Open Dashboard',
      language: 'Language',
      english: 'English',
      indonesian: 'Indonesian',
      logout: 'Log out',
      loading: 'Loading...',
      save: 'Save',
      search: 'Search',
      adminUser: 'Admin User',
      superAdmin: 'Super Admin',
      helpCenter: 'Help Center',
      overview: 'Overview',
    },
    home: {
      title: 'WhatsApp Business Dashboard',
      description: 'Admin dashboard starter for operations, messaging, contacts, and webhook monitoring.',
    },
    login: {
      title: 'Login',
      description: 'Sign in to access the WhatsApp operations dashboard.',
      email: 'Email',
      password: 'Password',
      submit: 'Sign In',
      goToDashboard: 'Go to Dashboard',
      invalidCredentials: 'Invalid email or password.',
      emailLabel: 'Email Address',
      passwordLabel: 'Password',
      forgotPassword: 'Forgot password?',
      rememberMe: 'Remember me on this device',
      accessVia: 'Or access via',
      google: 'Google',
      sso: 'SSO',
      newToPlatform: 'New to WhatsApp Business?',
      applyAccess: 'Apply for API access',
      privacyPolicy: 'Privacy Policy',
      termsOfService: 'Terms of Service',
      helpCenter: 'Help Center',
      securityPreview: 'Enterprise security-first access for messaging operations.',
      loginHelp: 'Need help?',
      twoFactorPreview: '2FA screen preview',
      showPassword: 'Show',
      hidePassword: 'Hide',
    },
    twoFactor: {
      title: 'Two-Factor Authentication',
      description: 'Open your Google Authenticator app and enter the 6-digit verification code below to verify your identity.',
      verify: 'Verify Code',
      backToLogin: 'Back to Login',
      needHelp: 'Need help?',
      appTitle: 'Google Authenticator',
      appDescription: 'Generate secure codes even when your phone is offline.',
      securityTitle: 'Enterprise Security',
      securityDescription: 'Your account is protected by mandatory 2FA protocols.',
      placeholderBadge: 'Coming soon',
      placeholderBody: 'This screen is a placeholder for the future 2FA login step. The backend verification flow has not been enabled yet.',
    },
    dashboard: {
      title: 'Dashboard Overview',
      navOverview: 'Overview',
      navContacts: 'Contacts',
      navCampaigns: 'Campaigns',
      navTemplates: 'Templates',
      navSettings: 'Settings',
      navWebhooks: 'Webhooks',
      navConversations: 'Conversations',
      navUsers: 'Users',
      navRoles: 'Roles',
      navLogs: 'System Logs',
      totalContacts: 'Total Contacts',
      webhookEvents: 'Webhook Events',
      deliveredRate: 'Delivered Rate',
      webhookHealth: 'Webhook Health',
      newMessage: 'New Broadcast',
    },
    contacts: {
      title: 'Contacts',
      submit: 'Create Contact',
      empty: 'No contacts yet.',
      name: 'Name',
      phoneNumber: 'Phone Number',
      email: 'Email',
      company: 'Company',
      notes: 'Notes',
      createSuccess: 'Contact created successfully.',
    },
    settings: {
      title: 'WhatsApp Settings',
      description: 'API token, webhook URL, verify token, signing secret, and sender configuration.',
    },
    webhooks: {
      title: 'Webhook Logs',
      empty: 'No webhook logs yet.',
    },
  },
  id: {
    common: {
      appName: 'BizOne',
      openDashboard: 'Buka Dashboard',
      language: 'Bahasa',
      english: 'Inggris',
      indonesian: 'Indonesia',
      logout: 'Keluar',
      loading: 'Memuat...',
      save: 'Simpan',
      search: 'Cari',
      adminUser: 'Admin',
      superAdmin: 'Super Admin',
      helpCenter: 'Pusat Bantuan',
      overview: 'Ringkasan',
    },
    home: {
      title: 'Dashboard WhatsApp Business',
      description: 'Starter dashboard admin untuk operasional, messaging, kontak, dan monitoring webhook.',
    },
    login: {
      title: 'Masuk',
      description: 'Masuk untuk mengakses dashboard operasional WhatsApp.',
      email: 'Email',
      password: 'Kata Sandi',
      submit: 'Masuk',
      goToDashboard: 'Ke Dashboard',
      invalidCredentials: 'Email atau kata sandi tidak valid.',
      emailLabel: 'Alamat Email',
      passwordLabel: 'Kata Sandi',
      forgotPassword: 'Lupa kata sandi?',
      rememberMe: 'Ingat perangkat ini',
      accessVia: 'Atau akses melalui',
      google: 'Google',
      sso: 'SSO',
      newToPlatform: 'Baru di WhatsApp Business?',
      applyAccess: 'Ajukan akses API',
      privacyPolicy: 'Kebijakan Privasi',
      termsOfService: 'Syarat Layanan',
      helpCenter: 'Pusat Bantuan',
      securityPreview: 'Akses enterprise yang fokus pada keamanan untuk operasional messaging.',
      loginHelp: 'Butuh bantuan?',
      twoFactorPreview: 'Preview layar 2FA',
      showPassword: 'Tampilkan',
      hidePassword: 'Sembunyikan',
    },
    twoFactor: {
      title: 'Autentikasi Dua Faktor',
      description: 'Buka aplikasi Google Authenticator Anda lalu masukkan 6 digit kode verifikasi di bawah untuk memverifikasi identitas Anda.',
      verify: 'Verifikasi Kode',
      backToLogin: 'Kembali ke Login',
      needHelp: 'Butuh bantuan?',
      appTitle: 'Google Authenticator',
      appDescription: 'Hasilkan kode aman bahkan saat ponsel Anda offline.',
      securityTitle: 'Keamanan Enterprise',
      securityDescription: 'Akun Anda akan dilindungi oleh protokol 2FA wajib.',
      placeholderBadge: 'Segera hadir',
      placeholderBody: 'Layar ini masih placeholder untuk langkah login 2FA di masa berikutnya. Flow verifikasi backend belum diaktifkan.',
    },
    dashboard: {
      title: 'Ringkasan Dashboard',
      navOverview: 'Ringkasan',
      navContacts: 'Kontak',
      navCampaigns: 'Kampanye',
      navTemplates: 'Template',
      navSettings: 'Pengaturan',
      navWebhooks: 'Webhook',
      navConversations: 'Percakapan',
      navUsers: 'Pengguna',
      navRoles: 'Peran',
      navLogs: 'Log Sistem',
      totalContacts: 'Total Kontak',
      webhookEvents: 'Event Webhook',
      deliveredRate: 'Rasio Terkirim',
      webhookHealth: 'Status Webhook',
      newMessage: 'Broadcast Baru',
    },
    contacts: {
      title: 'Kontak',
      submit: 'Buat Kontak',
      empty: 'Belum ada kontak.',
      name: 'Nama',
      phoneNumber: 'Nomor Telepon',
      email: 'Email',
      company: 'Perusahaan',
      notes: 'Catatan',
      createSuccess: 'Kontak berhasil dibuat.',
    },
    settings: {
      title: 'Pengaturan WhatsApp',
      description: 'Token API, URL webhook, verify token, signing secret, dan konfigurasi sender.',
    },
    webhooks: {
      title: 'Log Webhook',
      empty: 'Belum ada log webhook.',
    },
  },
};

export async function getLocale(): Promise<Locale> {
  const cookieStore = await cookies();
  const locale = cookieStore.get(localeCookieName)?.value;
  return isLocale(locale) ? locale : defaultLocale;
}

export async function getDictionary() {
  const locale = await getLocale();
  return dictionaries[locale];
}

export function isLocale(value: string | undefined | null): value is Locale {
  return Boolean(value && locales.includes(value as Locale));
}
