"use client";

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

type Language = "en" | "ar" | "zh";

interface LanguageContextType {
  language: Language;
  setLanguage: (lang: Language) => void;
  t: (key: string) => string;
  dir: "ltr" | "rtl";
}

const translations = {
  en: {
    home: "Home",
    report: "Report Incident",
    safety: "Safety Tips",
    hero_badge: "Emergency Reporting System",
    hero_title_1: "See it. Report it.",
    hero_title_2: "Save Lives.",
    hero_sub: "A secure, fast, and anonymous platform to report accidents, crimes, and dangerous incidents. Your documentation helps public awareness and safety.",
    report_now: "Report Now",
    how_it_works: "How it Works",
    submit_report: "Submit a Report",
    incident_details: "Incident Details",
    incident_type: "Incident Type",
    location: "Location",
    description: "Description",
    contact_info: "Contact Info (Optional)",
    placeholder_location: "Street address, city, or coordinates",
    placeholder_description: "Provide as much detail as possible...",
    placeholder_contact: "Email or phone if you wish to be contacted",
    anonymous_note: "Your report will be processed securely. You can remain anonymous by leaving contact info blank.",
    accuracy_note: "By submitting, you agree that the information provided is accurate to the best of your knowledge.",
    car_accident: "Car Accident",
    train_accident: "Train Accident",
    crime: "Crime / Robbery",
    violent_crime: "Violent Crime",
    emergency: "Emergency / Hazard",
    other: "Other",
  },
  ar: {
    home: "الرئيسية",
    report: "تبليغ عن حادث",
    safety: "نصائح السلامة",
    hero_badge: "نظام التبليغ عن الطوارئ",
    hero_title_1: "شاهد – بلّغ –",
    hero_title_2: "أنقذ الأرواح",
    hero_sub: "منصة آمنة وسريعة ومجهولة للتبليغ عن الحوادث والجرائم والحوادث الخطيرة. توثيقك يساعد في الوعي العام والسلامة.",
    report_now: "بلغ الآن",
    how_it_works: "كيف يعمل",
    submit_report: "تقديم بلاغ",
    incident_details: "تفاصيل الحادث",
    incident_type: "نوع الحادث",
    location: "الموقع",
    description: "الوصف",
    contact_info: "معلومات الاتصال (اختياري)",
    placeholder_location: "عنوان الشارع، المدينة، أو الإحداثيات",
    placeholder_description: "قدم أكبر قدر ممكن من التفاصيل...",
    placeholder_contact: "البريد الإلكتروني أو الهاتف إذا كنت ترغب في التواصل معك",
    anonymous_note: "سيتم معالجة بلاغك بشكل آمن. يمكنك البقاء مجهول الهوية بترك معلومات الاتصال فارغة.",
    accuracy_note: "بتقديمك للبلاغ، فإنك توافق على أن المعلومات المقدمة دقيقة حسب علمك.",
    car_accident: "حادث سيارة",
    train_accident: "حادث قطار",
    crime: "جريمة / سرقة",
    violent_crime: "جريمة عنف",
    emergency: "طوارئ / خطر",
    other: "أخرى",
  },
  zh: {
    home: "首页",
    report: "报告事件",
    safety: "安全提示",
    hero_badge: "紧急报告系统",
    hero_title_1: "目击、报告、",
    hero_title_2: "拯救生命",
    hero_sub: "一个安全、快速且匿名的平台，用于报告事故、犯罪和危险事件。您的记录有助于提高公众意识和安全。",
    report_now: "立即报告",
    how_it_works: "工作原理",
    submit_report: "提交报告",
    incident_details: "事件详情",
    incident_type: "事件类型",
    location: "地点",
    description: "描述",
    contact_info: "联系信息（可选）",
    placeholder_location: "街道地址、城市或坐标",
    placeholder_description: "请提供尽可能详细的信息...",
    placeholder_contact: "如果您希望被联系，请提供电子邮件或电话",
    anonymous_note: "您的报告将得到安全处理。您可以不填写联系信息以保持匿名。",
    accuracy_note: "提交即表示您同意所提供的信息在您所知的范围内是准确的。",
    car_accident: "车祸",
    train_accident: "火车事故",
    crime: "犯罪 / 抢劫",
    violent_crime: "暴力犯罪",
    emergency: "紧急情况 / 危险",
    other: "其他",
  },
};

const LanguageContext = createContext<LanguageContextType | undefined>(undefined);

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [language, setLanguage] = useState<Language>("en");

  useEffect(() => {
    const saved = localStorage.getItem("lang") as Language;
    if (saved && (saved === "en" || saved === "ar" || saved === "zh")) {
      setLanguage(saved);
    }
  }, []);

  const handleSetLanguage = (lang: Language) => {
    setLanguage(lang);
    localStorage.setItem("lang", lang);
    document.documentElement.dir = lang === "ar" ? "rtl" : "ltr";
    document.documentElement.lang = lang;
  };

  const t = (key: string) => {
    return translations[language][key as keyof typeof translations["en"]] || key;
  };

  const dir = language === "ar" ? "rtl" : "ltr";

  return (
    <LanguageContext.Provider value={{ language, setLanguage: handleSetLanguage, t, dir }}>
      <div dir={dir} className={language === "ar" ? "font-arabic" : ""}>
        {children}
      </div>
    </LanguageContext.Provider>
  );
}

export function useLanguage() {
  const context = useContext(LanguageContext);
  if (context === undefined) {
    throw new Error("useLanguage must be used within a LanguageProvider");
  }
  return context;
}
