"use client"

import React, { createContext, useContext, useEffect, useMemo, useState } from 'react'

type Locale = 'en' | 'es'

type Dictionary = Record<string, string>

const en: Dictionary = {
  nav_home: 'Home',
  nav_dashboard: 'Dashboard',
  nav_login: 'Login',
  logout: 'Logout',
  language: 'English',
  footer_quick_links: 'Quick Links',
  footer_how_to_play: 'How to Play',
  footer_team: 'Team',
  footer_contact: 'Contact',
  footer_connect_with_us: 'Connect With Us',
  footer_server_ip: 'Server IP',
  footer_discord_server: 'Discord Server',
  connect_now: 'Connect Now',
  join_now: 'Join Now',
  how_title_prefix: 'How can you play',
  how_title_suffix: '?',
  how_tagline: 'Follow these simple steps to join our amazing community and start your adventure',
  step1_title: 'Download GTA San Andreas',
  step1_desc: 'Download GTA San Andreas from anywhere you want.',
  step2_title: 'Install SA-MP',
  step2_desc: "Download the official SA-MP client. It's completely free.",
  step3_title: 'Join the Server',
  step3_desc: "Run the SA-MP client, add the server, click 'Play'... That's it!",
  download: 'Download',
  play_now: 'Play Now',
  meet_team: 'Meet Our Team',
  our_mission: 'Our Mission',
  our_vision: 'Our Vision',
  our_values: 'Our Values',
}

const es: Dictionary = {
  nav_home: 'Inicio',
  nav_dashboard: 'Panel',
  nav_login: 'Iniciar sesión',
  logout: 'Salir',
  language: 'Español',
  footer_quick_links: 'Enlaces',
  footer_how_to_play: 'Cómo jugar',
  footer_team: 'Equipo',
  footer_contact: 'Contacto',
  footer_connect_with_us: 'Conéctate con nosotros',
  footer_server_ip: 'IP del Servidor',
  footer_discord_server: 'Servidor de Discord',
  connect_now: 'Conectar ahora',
  join_now: 'Unirse',
  how_title_prefix: '¿Cómo puedes jugar',
  how_title_suffix: '?',
  how_tagline: 'Sigue estos pasos para unirte y empezar tu aventura',
  step1_title: 'Descargar GTA San Andreas',
  step1_desc: 'Descarga GTA San Andreas desde donde prefieras.',
  step2_title: 'Instalar SA-MP',
  step2_desc: 'Descarga el cliente oficial de SA-MP. Es totalmente gratis.',
  step3_title: 'Entrar al servidor',
  step3_desc: "Abre SA-MP, agrega el servidor y haz clic en 'Jugar'... ¡Listo!",
  download: 'Descargar',
  play_now: 'Jugar ahora',
  meet_team: 'Conoce a nuestro equipo',
  our_mission: 'Nuestra misión',
  our_vision: 'Nuestra visión',
  our_values: 'Nuestros valores',
}

const dictionaries: Record<Locale, Dictionary> = { en, es }

interface I18nContextValue {
  locale: Locale
  setLocale: (l: Locale) => void
  t: (key: string) => string
}

const I18nContext = createContext<I18nContextValue | undefined>(undefined)

export function I18nProvider({ children }: { children: React.ReactNode }) {
  const [locale, setLocale] = useState<Locale>('en')

  useEffect(() => {
    const saved = typeof window !== 'undefined' ? (localStorage.getItem('locale') as Locale | null) : null
    if (saved === 'en' || saved === 'es') setLocale(saved)
    else {
      // Derive from URL prefix /en or /es
      if (typeof window !== 'undefined') {
        const seg = window.location.pathname.split('/')[1]
        if (seg === 'en' || seg === 'es') setLocale(seg)
      }
    }
  }, [])

  useEffect(() => {
    if (typeof window !== 'undefined') localStorage.setItem('locale', locale)
  }, [locale])

  const value = useMemo<I18nContextValue>(() => ({
    locale,
    setLocale,
    t: (key: string) => dictionaries[locale][key] ?? key,
  }), [locale])

  return (
    <I18nContext.Provider value={value}>{children}</I18nContext.Provider>
  )
}

export function useI18n() {
  const ctx = useContext(I18nContext)
  if (!ctx) throw new Error('useI18n must be used within I18nProvider')
  return ctx
}


