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

/* ---------------------------------------------------------------------- */
/*  TRANSLATIONS — all pages import { useApp } and call t("key")          */
/* ---------------------------------------------------------------------- */
export const TRANSLATIONS = {
  en: {
    // Nav / common
    dashboard: "Dashboard", settings: "Settings", search: "Search...",
    notifications: "Notifications", topUp: "Top Up", credits: "credits",
    viewAll: "View all notifications →", active: "Active",
    // Profile
    myProfile: "My Profile", billing: "Billing", help: "Help & Support",
    signOut: "Sign Out", profile: "Profile", security: "Security",
    activity: "Activity", editProfile: "Edit", saveProfile: "Save",
    closeProfile: "Close Profile", profileSaved: "Profile saved successfully!",
    // Theme / lang
    lightMode: "Light mode", darkMode: "Dark mode",
    language: "Language", nfc: "NFC", selectLanguage: "Select Language",
    // Pages
    feeManagement: "Fee Collection & Defaulters",
    welfare: "Welfare Scheme Management",
    insurance: "Group Insurance & Emergency Contacts",
    committees: "Committee Management",
    notices: "Circulars & Notifications",
    grievances: "Advocate Complaints & Inquiries",
    staff: "Staff Management",
  },
  hi: {
    dashboard: "डैशबोर्ड", settings: "सेटिंग्स", search: "खोजें...",
    notifications: "सूचनाएं", topUp: "टॉप अप", credits: "क्रेडिट",
    viewAll: "सभी सूचनाएं देखें →", active: "सक्रिय",
    myProfile: "मेरी प्रोफ़ाइल", billing: "बिलिंग", help: "सहायता",
    signOut: "साइन आउट", profile: "प्रोफ़ाइल", security: "सुरक्षा",
    activity: "गतिविधि", editProfile: "संपादित करें", saveProfile: "सहेजें",
    closeProfile: "प्रोफ़ाइल बंद करें", profileSaved: "प्रोफ़ाइल सफलतापूर्वक सहेजी गई!",
    lightMode: "लाइट मोड", darkMode: "डार्क मोड",
    language: "भाषा", nfc: "एनएफसी", selectLanguage: "भाषा चुनें",
    feeManagement: "शुल्क संग्रह और चूककर्ता",
    welfare: "कल्याण योजना प्रबंधन",
    insurance: "समूह बीमा और आपातकालीन संपर्क",
    committees: "समिति प्रबंधन",
    notices: "परिपत्र और अधिसूचनाएं",
    grievances: "वकील शिकायतें और जांच",
    staff: "कर्मचारी प्रबंधन",
  },
  ta: {
    dashboard: "டாஷ்போர்டு", settings: "அமைப்புகள்", search: "தேடு...",
    notifications: "அறிவிப்புகள்", topUp: "டாப் அப்", credits: "கிரெடிட்",
    viewAll: "அனைத்தையும் காண்க →", active: "செயலில்",
    myProfile: "என் சுயவிவரம்", billing: "பில்லிங்", help: "உதவி",
    signOut: "வெளியேறு", profile: "சுயவிவரம்", security: "பாதுகாப்பு",
    activity: "செயல்பாடு", editProfile: "திருத்து", saveProfile: "சேமி",
    closeProfile: "மூடு", profileSaved: "சுயவிவரம் சேமிக்கப்பட்டது!",
    lightMode: "ஒளி பயன்முறை", darkMode: "இருள் பயன்முறை",
    language: "மொழி", nfc: "என்எஃப்சி", selectLanguage: "மொழியை தேர்ந்தெடுக்கவும்",
    feeManagement: "கட்டண சேகரிப்பு",
    welfare: "நலன் திட்ட மேலாண்மை",
    insurance: "குழு காப்பீடு",
    committees: "குழு மேலாண்மை",
    notices: "அறிவிப்புகள்",
    grievances: "புகார்கள் மற்றும் விசாரணைகள்",
    staff: "பணியாளர் மேலாண்மை",
  },
  te: {
    dashboard: "డాష్‌బోర్డ్", settings: "సెట్టింగులు", search: "వెతకండి...",
    notifications: "నోటిఫికేషన్లు", topUp: "టాప్ అప్", credits: "క్రెడిట్లు",
    viewAll: "అన్నీ చూడండి →", active: "చురుకైన",
    myProfile: "నా ప్రొఫైల్", billing: "బిల్లింగ్", help: "సహాయం",
    signOut: "సైన్ అవుట్", profile: "ప్రొఫైల్", security: "భద్రత",
    activity: "కార్యాచరణ", editProfile: "సవరించు", saveProfile: "సేవ్ చేయి",
    closeProfile: "మూసివేయి", profileSaved: "ప్రొఫైల్ సేవ్ చేయబడింది!",
    lightMode: "లైట్ మోడ్", darkMode: "డార్క్ మోడ్",
    language: "భాష", nfc: "ఎన్ఎఫ్సి", selectLanguage: "భాషను ఎంచుకోండి",
    feeManagement: "రుసుము సేకరణ",
    welfare: "సంక్షేమ పథకం",
    insurance: "సమూహ బీమా",
    committees: "కమిటీ నిర్వహణ",
    notices: "సర్క్యులర్లు మరియు నోటిఫికేషన్లు",
    grievances: "ఫిర్యాదులు మరియు విచారణలు",
    staff: "సిబ్బంది నిర్వహణ",
  },
  mr: {
    dashboard: "डॅशबोर्ड", settings: "सेटिंग्ज", search: "शोधा...",
    notifications: "सूचना", topUp: "टॉप अप", credits: "क्रेडिट्स",
    viewAll: "सर्व पहा →", active: "सक्रिय",
    myProfile: "माझी प्रोफाइल", billing: "बिलिंग", help: "मदत",
    signOut: "साइन आउट", profile: "प्रोफाइल", security: "सुरक्षा",
    activity: "क्रियाकलाप", editProfile: "संपादित करा", saveProfile: "जतन करा",
    closeProfile: "बंद करा", profileSaved: "प्रोफाइल जतन केली!",
    lightMode: "लाइट मोड", darkMode: "डार्क मोड",
    language: "भाषा", nfc: "एनएफसी", selectLanguage: "भाषा निवडा",
    feeManagement: "शुल्क संकलन",
    welfare: "कल्याण योजना व्यवस्थापन",
    insurance: "समूह विमा",
    committees: "समिती व्यवस्थापन",
    notices: "परिपत्रके आणि सूचना",
    grievances: "तक्रारी आणि चौकशी",
    staff: "कर्मचारी व्यवस्थापन",
  },
  bn: {
    dashboard: "ড্যাশবোর্ড", settings: "সেটিংস", search: "খুঁজুন...",
    notifications: "বিজ্ঞপ্তি", topUp: "টপ আপ", credits: "ক্রেডিট",
    viewAll: "সব দেখুন →", active: "সক্রিয়",
    myProfile: "আমার প্রোফাইল", billing: "বিলিং", help: "সাহায্য",
    signOut: "সাইন আউট", profile: "প্রোফাইল", security: "নিরাপত্তা",
    activity: "কার্যক্রম", editProfile: "সম্পাদনা", saveProfile: "সংরক্ষণ",
    closeProfile: "বন্ধ করুন", profileSaved: "প্রোফাইল সংরক্ষিত হয়েছে!",
    lightMode: "লাইট মোড", darkMode: "ডার্ক মোড",
    language: "ভাষা", nfc: "এনএফসি", selectLanguage: "ভাষা নির্বাচন করুন",
    feeManagement: "ফি সংগ্রহ",
    welfare: "কল্যাণ প্রকল্প ব্যবস্থাপনা",
    insurance: "গ্রুপ বীমা",
    committees: "কমিটি ব্যবস্থাপনা",
    notices: "সার্কুলার এবং বিজ্ঞপ্তি",
    grievances: "অভিযোগ এবং তদন্ত",
    staff: "কর্মী ব্যবস্থাপনা",
  },
};

/* ---------------------------------------------------------------------- */
/*  DARK MODE — injects / removes a global <style> tag                    */
/* ---------------------------------------------------------------------- */
function injectDarkCSS() {
  const id = "app-dark-theme";
  if (document.getElementById(id)) return;
  const s = document.createElement("style");
  s.id = id;
  s.textContent = `
    body, #root {
      background-color: #111827 !important;
      color: #f9fafb !important;
    }
    /* surfaces */
    .bg-white        { background-color: #1f2937 !important; }
    .bg-gray-50      { background-color: #111827 !important; }
    .bg-gray-100     { background-color: #374151 !important; }

    /* borders */
    .border-gray-100,
    .border-gray-200 { border-color: #374151 !important; }

    /* text */
    .text-gray-900   { color: #f9fafb !important; }
    .text-gray-700   { color: #e5e7eb !important; }
    .text-gray-600   { color: #d1d5db !important; }
    .text-gray-500   { color: #9ca3af !important; }
    .text-gray-400   { color: #6b7280 !important; }

    /* dividers */
    .divide-gray-200 > * + * { border-color: #374151 !important; }
    .divide-gray-50  > * + * { border-color: #1f2937 !important; }

    /* table */
    table            { background-color: #1f2937 !important; }
    thead tr         { background-color: #111827 !important; }
    tbody tr:hover   { background-color: #374151 !important; }
    td, th           { border-color: #374151 !important; }

    /* inputs & selects */
    input:not([type=checkbox]):not([type=radio]),
    select,
    textarea {
      background-color: #1f2937 !important;
      border-color: #374151 !important;
      color: #f9fafb !important;
    }
    input::placeholder, textarea::placeholder { color: #6b7280 !important; }

    /* cards / modals */
    .shadow-sm, .shadow-md, .shadow-lg, .shadow-xl { box-shadow: none !important; }
    [class*="rounded-lg"], [class*="rounded-xl"], [class*="rounded-2xl"] {
      border-color: #374151;
    }
  `;
  document.head.appendChild(s);
}

function removeDarkCSS() {
  document.getElementById("app-dark-theme")?.remove();
}

/* ---------------------------------------------------------------------- */
/*  CONTEXT                                                                */
/* ---------------------------------------------------------------------- */
const AppContext = createContext(null);

export function AppProvider({ children }) {
  const [dark, setDarkState] = useState(false);
  const [lang, setLangState] = useState("en");

  const setDark = (val) => {
    setDarkState(val);
    if (val) {
      document.documentElement.classList.add("dark");
      document.documentElement.style.colorScheme = "dark";
      injectDarkCSS();
    } else {
      document.documentElement.classList.remove("dark");
      document.documentElement.style.colorScheme = "light";
      removeDarkCSS();
    }
  };

  const setLang = (code) => setLangState(code);

  const t = (key) => TRANSLATIONS[lang]?.[key] ?? TRANSLATIONS.en[key] ?? key;

  return (
    <AppContext.Provider value={{ dark, setDark, lang, setLang, t, translations: TRANSLATIONS[lang] || TRANSLATIONS.en }}>
      {children}
    </AppContext.Provider>
  );
}

export function useApp() {
  const ctx = useContext(AppContext);
  if (!ctx) throw new Error("useApp must be used inside <AppProvider>");
  return ctx;
}