import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
import type { Lang } from "./catalog";

const STRINGS = {
  pt: {
    tagline: "Compra e vende em todo o Angola",
    searchPlaceholder: "Procura carros, telemóveis, casas…",
    search: "Pesquisar",
    sell: "Vender",
    help: "Ajuda",
    home: "Início",
    account: "Perfil",
    cart: "Carrinho",
    signIn: "Entrar",
    signOut: "Sair",
    filters: "Filtros",
    clear: "Limpar",
    province: "Província",
    price: "Preço (Kz)",
    min: "Mín.",
    max: "Máx.",
    category: "Categoria",
    condition: "Estado",
    all: "Tudo",
    apply: "Aplicar",
    marketTitle: "Mercado de Angola",
    resultsCount: "anúncios",
    updatedToday: "actualizado hoje",
    featured: "Destaque",
    verifiedSeller: "Vendedor verificado",
    instantBuy: "Compra instantânea",
    buyNow: "Comprar agora",
    addToCart: "Adicionar ao carrinho",
    inCart: "No carrinho",
    contactSeller: "Contactar vendedor",
    securePayment: "Pagamento seguro",
    published: "Publicado",
    noResults: "Sem anúncios para estes filtros.",
    loading: "A carregar…",
    yourCart: "O teu carrinho",
    emptyCart: "O carrinho está vazio.",
    keepShopping: "Continuar a comprar",
    summary: "Resumo",
    subtotal: "Subtotal",
    delivery: "Entrega",
    total: "Total",
    checkout: "Finalizar compra",
    escrowNote: "Pagamento via Escrow — só libertas o dinheiro ao receberes.",
    checkoutTitle: "Dados de entrega",
    fullName: "Nome completo",
    phone: "Telefone",
    address: "Endereço de entrega",
    paymentMethod: "Forma de pagamento",
    placeOrder: "Confirmar encomenda",
    orderPlaced: "Encomenda confirmada!",
    orderPlacedNote: "O vendedor foi notificado. Acompanha o estado no teu perfil.",
    myOrders: "As minhas encomendas",
    myListings: "Os meus anúncios",
    favorites: "Guardados",
    noFavorites: "Ainda não guardaste nada.",
    noOrders: "Ainda não tens encomendas.",
    noListings: "Ainda não publicaste anúncios.",
    newListing: "Novo anúncio",
    title: "Título",
    description: "Descrição",
    photoUrl: "Link da foto",
    photoUrlHint: "Cola o link de uma foto do produto (podes juntar até 3, separados por vírgula).",
    municipality: "Zona / município",
    stock: "Quantidade disponível",
    allowInstantBuy: "Permitir compra instantânea (carrinho e checkout)",
    publish: "Publicar anúncio",
    publishing: "A publicar…",
    listingPublished: "Anúncio publicado!",
    delete: "Remover",
    signInTitle: "Entrar na KUYA",
    signUpTitle: "Criar conta KUYA",
    email: "Email",
    password: "Palavra-passe",
    createAccount: "Criar conta",
    haveAccount: "Já tenho conta",
    noAccount: "Ainda não tenho conta",
    orGoogle: "Continuar com Google",
    signInToContinue: "Entra para continuares.",
    views: "visualizações",
    sortRecent: "Mais recentes",
    sortCheap: "Menor preço",
    sortExpensive: "Maior preço",
    sortViewed: "Mais vistos",
    sortBy: "Ordenar",
    back: "Voltar",
    notFound: "Anúncio não encontrado.",
    seller: "Vendedor",
    remove: "Remover",
    savedListings: "Guardados",
    profile: "Perfil",
    displayName: "Nome público",
    save: "Guardar",
    saved: "Guardado",
    quantity: "Qtd",
  },
  en: {
    tagline: "Buy and sell across Angola",
    searchPlaceholder: "Search cars, phones, homes…",
    search: "Search",
    sell: "Sell",
    help: "Help",
    home: "Home",
    account: "Account",
    cart: "Cart",
    signIn: "Sign in",
    signOut: "Sign out",
    filters: "Filters",
    clear: "Clear",
    province: "Province",
    price: "Price (Kz)",
    min: "Min.",
    max: "Max.",
    category: "Category",
    condition: "Condition",
    all: "All",
    apply: "Apply",
    marketTitle: "Angola marketplace",
    resultsCount: "listings",
    updatedToday: "updated today",
    featured: "Featured",
    verifiedSeller: "Verified seller",
    instantBuy: "Instant buy",
    buyNow: "Buy now",
    addToCart: "Add to cart",
    inCart: "In cart",
    contactSeller: "Contact seller",
    securePayment: "Secure payment",
    published: "Published",
    noResults: "No listings match these filters.",
    loading: "Loading…",
    yourCart: "Your cart",
    emptyCart: "Your cart is empty.",
    keepShopping: "Keep shopping",
    summary: "Summary",
    subtotal: "Subtotal",
    delivery: "Delivery",
    total: "Total",
    checkout: "Checkout",
    escrowNote: "Paid through Escrow — money is released when you receive the item.",
    checkoutTitle: "Delivery details",
    fullName: "Full name",
    phone: "Phone",
    address: "Delivery address",
    paymentMethod: "Payment method",
    placeOrder: "Place order",
    orderPlaced: "Order confirmed!",
    orderPlacedNote: "The seller has been notified. Track it from your account.",
    myOrders: "My orders",
    myListings: "My listings",
    favorites: "Saved",
    noFavorites: "You haven't saved anything yet.",
    noOrders: "No orders yet.",
    noListings: "You haven't posted any listings yet.",
    newListing: "New listing",
    title: "Title",
    description: "Description",
    photoUrl: "Photo link",
    photoUrlHint: "Paste a link to a product photo (up to 3, separated by commas).",
    municipality: "Area / municipality",
    stock: "Available quantity",
    allowInstantBuy: "Allow instant buy (cart and checkout)",
    publish: "Publish listing",
    publishing: "Publishing…",
    listingPublished: "Listing published!",
    delete: "Remove",
    signInTitle: "Sign in to KUYA",
    signUpTitle: "Create your KUYA account",
    email: "Email",
    password: "Password",
    createAccount: "Create account",
    haveAccount: "I already have an account",
    noAccount: "I don't have an account",
    orGoogle: "Continue with Google",
    signInToContinue: "Sign in to continue.",
    views: "views",
    sortRecent: "Newest",
    sortCheap: "Lowest price",
    sortExpensive: "Highest price",
    sortViewed: "Most viewed",
    sortBy: "Sort",
    back: "Back",
    notFound: "Listing not found.",
    seller: "Seller",
    remove: "Remove",
    savedListings: "Saved",
    profile: "Profile",
    displayName: "Public name",
    save: "Save",
    saved: "Saved",
    quantity: "Qty",
  },
} as const;

export type TKey = keyof typeof STRINGS.pt;

type I18nValue = {
  lang: Lang;
  setLang: (lang: Lang) => void;
  t: (key: TKey) => string;
};

const I18nContext = createContext<I18nValue | null>(null);

export function I18nProvider({ children }: { children: ReactNode }) {
  const [lang, setLangState] = useState<Lang>("pt");

  useEffect(() => {
    const stored = window.localStorage.getItem("kuya:lang");
    if (stored === "pt" || stored === "en") setLangState(stored);
  }, []);

  const setLang = useCallback((next: Lang) => {
    setLangState(next);
    window.localStorage.setItem("kuya:lang", next);
  }, []);

  const value = useMemo<I18nValue>(
    () => ({ lang, setLang, t: (key: TKey) => STRINGS[lang][key] }),
    [lang, setLang],
  );

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

export function useI18n(): I18nValue {
  const ctx = useContext(I18nContext);
  if (!ctx) throw new Error("useI18n must be used inside I18nProvider");
  return ctx;
}
