"use client";

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from "react";

export type Locale = "en" | "th";

type Dict = Record<string, string>;

const en: Dict = {
  "site.name": "Chowrest Property",
  "nav.listings": "Listings",
  "home.title": "Properties for sale",
  "home.subtitle": "Browse listings across our portfolio.",
  "home.results.one": "result",
  "home.results.other": "results",
  "home.empty": "No listings match these filters.",
  "home.clear": "Clear",
  "filter.search": "Search title, city…",
  "filter.anyType": "Any type",
  "filter.anyBeds": "Any bd",
  "filter.minPrice": "Min $",
  "filter.maxPrice": "Max $",
  "filter.apply": "Apply filters",
  "filter.searching": "Searching…",
  "view.grid": "Grid",
  "view.map": "Map",
  "detail.bedrooms": "Bedrooms",
  "detail.bathrooms": "Bathrooms",
  "detail.area": "Area",
  "detail.location": "Location",
  "detail.amenities": "Amenities",
  "detail.back": "← Back to listings",
  "detail.whatsapp": "Chat on WhatsApp",
  "detail.requestInfo": "Request more info",
  "detail.requestSubtitle": "We’ll get back to you shortly.",
  "detail.contact": "Contact about this rental",
  "lead.name": "Your name",
  "lead.email": "Email",
  "lead.phone": "Phone (optional)",
  "lead.message": "Message",
  "lead.send": "Send inquiry",
  "lead.sending": "Sending…",
  "lead.success": "Thanks — we’ll be in touch.",
};

const th: Dict = {
  "site.name": "Chowrest Property",
  "nav.listings": "ประกาศขาย",
  "home.title": "อสังหาริมทรัพย์สำหรับขาย",
  "home.subtitle": "เลือกชมรายการประกาศของเรา",
  "home.results.one": "รายการ",
  "home.results.other": "รายการ",
  "home.empty": "ไม่มีรายการที่ตรงกับตัวกรองเหล่านี้",
  "home.clear": "ล้าง",
  "filter.search": "ค้นหาชื่อหรือเมือง…",
  "filter.anyType": "ทุกประเภท",
  "filter.anyBeds": "ห้องนอน",
  "filter.minPrice": "ราคาต่ำสุด",
  "filter.maxPrice": "ราคาสูงสุด",
  "filter.apply": "ค้นหา",
  "filter.searching": "กำลังค้นหา…",
  "view.grid": "ตาราง",
  "view.map": "แผนที่",
  "detail.bedrooms": "ห้องนอน",
  "detail.bathrooms": "ห้องน้ำ",
  "detail.area": "พื้นที่",
  "detail.location": "ที่ตั้ง",
  "detail.amenities": "สิ่งอำนวยความสะดวก",
  "detail.back": "← กลับไปยังประกาศ",
  "detail.whatsapp": "แชทผ่าน WhatsApp",
  "detail.requestInfo": "สอบถามข้อมูลเพิ่มเติม",
  "detail.requestSubtitle": "เราจะติดต่อกลับโดยเร็วที่สุด",
  "detail.contact": "ติดต่อเกี่ยวกับอสังหาริมทรัพย์นี้",
  "lead.name": "ชื่อของคุณ",
  "lead.email": "อีเมล",
  "lead.phone": "เบอร์โทรศัพท์ (ไม่บังคับ)",
  "lead.message": "ข้อความ",
  "lead.send": "ส่งคำสอบถาม",
  "lead.sending": "กำลังส่ง…",
  "lead.success": "ขอบคุณค่ะ — เราจะติดต่อกลับโดยเร็วที่สุด",
};

const dicts: Record<Locale, Dict> = { en, th };

type Ctx = {
  locale: Locale;
  setLocale: (l: Locale) => void;
  t: (key: string) => string;
};

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

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

  useEffect(() => {
    const saved = localStorage.getItem("locale") as Locale | null;
    if (saved === "en" || saved === "th") setLocaleState(saved);
  }, []);

  const setLocale = useCallback((l: Locale) => {
    setLocaleState(l);
    try {
      localStorage.setItem("locale", l);
      document.documentElement.lang = l;
    } catch {}
  }, []);

  const t = useCallback(
    (key: string) => dicts[locale][key] ?? dicts.en[key] ?? key,
    [locale],
  );

  const value = useMemo(() => ({ locale, setLocale, t }), [locale, setLocale, t]);
  return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}

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

export function LocaleToggle() {
  const ctx = useContext(I18nContext);
  if (!ctx) return null;
  return (
    <div className="inline-flex items-center gap-0.5 rounded-full border border-border bg-surface p-0.5 text-[12px]">
      {(["en", "th"] as const).map((l) => (
        <button
          key={l}
          type="button"
          onClick={() => ctx.setLocale(l)}
          className={`rounded-full px-3 py-1 transition ${ctx.locale === l ? "bg-text text-bg" : "text-text-muted hover:text-text"}`}
        >
          {l.toUpperCase()}
        </button>
      ))}
    </div>
  );
}

export function T({ k }: { k: string }) {
  const { t } = useI18n();
  return <>{t(k)}</>;
}
