import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/hooks/useAuth";

export type Theme = "light" | "dark";
export type Lang = "en" | "zh";

type SettingsCtx = {
  theme: Theme;
  lang: Lang;
  setTheme: (t: Theme) => void;
  setLang: (l: Lang) => void;
  toggleTheme: () => void;
  toggleLang: () => void;
};

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

const THEME_KEY = "tdl.theme";
const LANG_KEY = "tdl.lang";

function readInitial<T extends string>(key: string, fallback: T): T {
  if (typeof window === "undefined") return fallback;
  try {
    const v = window.localStorage.getItem(key);
    return (v as T) || fallback;
  } catch {
    return fallback;
  }
}

export function SettingsProvider({ children }: { children: ReactNode }) {
  const { user } = useAuth();
  const [theme, setThemeState] = useState<Theme>(() => readInitial<Theme>(THEME_KEY, "light"));
  const [lang, setLangState] = useState<Lang>(() => readInitial<Lang>(LANG_KEY, "en"));
  const [hydrated, setHydrated] = useState(false);

  // Apply theme to <html>
  useEffect(() => {
    const root = document.documentElement;
    if (theme === "dark") root.classList.add("dark");
    else root.classList.remove("dark");
    try { window.localStorage.setItem(THEME_KEY, theme); } catch { /* ignore */ }
  }, [theme]);

  useEffect(() => {
    document.documentElement.lang = lang === "zh" ? "zh-CN" : "en";
    try { window.localStorage.setItem(LANG_KEY, lang); } catch { /* ignore */ }
  }, [lang]);

  // Hydrate from DB once per user.id (not on every user object reference change)
  useEffect(() => {
    if (!user?.id) { setHydrated(true); return; }
    setHydrated(false);
    let cancelled = false;
    supabase
      .from("user_preferences")
      .select("theme, lang")
      .eq("user_id", user.id)
      .maybeSingle()
      .then(({ data }) => {
        if (cancelled) return;
        if (data) {
          if (data.theme === "light" || data.theme === "dark") {
            setThemeState(data.theme);
            try { window.localStorage.setItem(THEME_KEY, data.theme); } catch { /* ignore */ }
          }
          if (data.lang === "en" || data.lang === "zh") setLangState(data.lang);
        }
        setHydrated(true);
      });
    return () => { cancelled = true; };
  }, [user?.id]);

  // Persist to DB on change — only AFTER hydration to avoid overwriting saved prefs
  useEffect(() => {
    if (!user || !hydrated) return;
    void supabase
      .from("user_preferences")
      .upsert({ user_id: user.id, theme, lang }, { onConflict: "user_id" });
  }, [user, theme, lang, hydrated]);

  const value: SettingsCtx = {
    theme,
    lang,
    setTheme: setThemeState,
    setLang: setLangState,
    toggleTheme: () => setThemeState((t) => (t === "dark" ? "light" : "dark")),
    toggleLang: () => setLangState((l) => (l === "zh" ? "en" : "zh")),
  };
  return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}

export function useSettings(): SettingsCtx {
  const ctx = useContext(Ctx);
  if (!ctx) throw new Error("useSettings must be used inside <SettingsProvider>");
  return ctx;
}

// === Mini i18n dictionary for UI chrome ===
const DICT: Record<string, { en: string; zh: string }> = {
  "nav.today": { en: "Today", zh: "今日" },
  "nav.today.desc": { en: "30-second brief", zh: "30秒简报" },
  "nav.industry": { en: "Industry", zh: "行业" },
  "nav.industry.desc": { en: "Segment outlook", zh: "细分市场展望" },
  "nav.competitors": { en: "Competitors", zh: "竞争对手" },
  "nav.competitors.desc": { en: "Nearby properties", zh: "附近酒店" },
  "nav.selfexam": { en: "Self-Exam", zh: "自检" },
  "nav.selfexam.desc": { en: "Your digital footprint", zh: "数字足迹" },
  "nav.actions": { en: "Actions", zh: "行动" },
  "nav.actions.desc": { en: "3 moves to make", zh: "3项行动" },
  "nav.ask": { en: "Chat", zh: "聊天" },
  "nav.ask.desc": { en: "Your hotel copilot", zh: "您的酒店智能助手" },

  "shell.brand": { en: "The Daily Ledger", zh: "每日简报" },
  "shell.menu": { en: "Menu", zh: "菜单" },
  "shell.property": { en: "Property", zh: "酒店" },
  "shell.allHotels": { en: "All hotels (portfolio)", zh: "全部酒店（组合）" },
  "shell.addHotel": { en: "Add another hotel", zh: "添加另一家酒店" },
  "shell.deleteAccount": { en: "Delete account", zh: "删除账户" },
  "shell.profile": { en: "Profile & settings", zh: "个人与设置" },
  "shell.rooms": { en: "rooms", zh: "间客房" },
  "shell.kmWatch": { en: "km watch", zh: "公里监测" },
  "shell.refresh": { en: "Refresh briefing", zh: "刷新简报" },
  "shell.editHotel": { en: "Edit hotel", zh: "编辑酒店" },
  "shell.removeHotel": { en: "Remove this hotel", zh: "移除此酒店" },
  "remove.title": { en: "Remove this hotel?", zh: "移除此酒店？" },
  "remove.body": {
    en: "This permanently deletes this property and all of its briefings, self-examinations, action progress, and chat history. This cannot be undone.",
    zh: "这将永久删除此酒店及其所有简报、自检记录、行动进度和聊天历史。此操作无法撤销。",
  },
  "remove.confirm": { en: "Type the hotel name to confirm", zh: "输入酒店名称以确认" },
  "remove.cancel": { en: "Cancel", zh: "取消" },
  "remove.cta": { en: "Remove permanently", zh: "永久移除" },
  "shell.signOut": { en: "Sign out", zh: "退出登录" },
  "shell.theme.light": { en: "Light mode", zh: "浅色模式" },
  "shell.theme.dark": { en: "Dark mode", zh: "深色模式" },
  "shell.lang": { en: "中文", zh: "English" },

  "common.loading": { en: "Loading...", zh: "加载中..." },
  "common.tryAgain": { en: "Try again", zh: "重试" },
  "common.viewAll": { en: "View all", zh: "查看全部" },
  "common.sources": { en: "Sources", zh: "来源" },
  "common.backedBy": { en: "Backed by", zh: "依据" },
  "common.why": { en: "Why", zh: "原因" },
  "common.viewDeepDive": { en: "View deep-dive analysis", zh: "查看深度分析" },
  "common.deepDive": { en: "Deep dive", zh: "深入分析" },

  "deepDive.subtitle": { en: "Cross-validated analysis with named, reachable sources.", zh: "经多方交叉验证的分析，附可访问来源。" },
  "deepDive.loading": { en: "Cross-checking sources and synthesising the analysis…", zh: "正在交叉核对来源并综合分析…" },
  "deepDive.keyFindings": { en: "Key findings", zh: "关键发现" },
  "deepDive.opportunities": { en: "Opportunities", zh: "机会" },
  "deepDive.risks": { en: "Risks", zh: "风险" },
  "deepDive.moves": { en: "Recommended moves", zh: "推荐行动" },
  "deepDive.crossValidated": { en: "Cross-validated", zh: "交叉验证" },
  "deepDive.back": { en: "Back", zh: "返回" },
  "deepDive.benchmark": { en: "Benchmark", zh: "基准" },
  "deepDive.subject": { en: "Subject", zh: "主体" },
  "deepDive.trend": { en: "Trend", zh: "趋势" },
  "deepDive.generate": { en: "Generate analysis", zh: "生成分析" },
  "deepDive.generated": { en: "Generated", zh: "生成于" },
  "deepDive.refresh": { en: "Refresh", zh: "刷新" },
  "deepDive.refreshing": { en: "Refreshing…", zh: "正在刷新…" },
  "deepDive.industryEyebrow": { en: "Industry deep dive", zh: "行业深度分析" },
  "deepDive.competitorEyebrow": { en: "Competitor deep dive", zh: "竞争对手深度分析" },
  "deepDive.notYet.title": { en: "No analysis yet", zh: "尚无分析" },
  "deepDive.notYet.body": { en: "Generate a fresh, cross-validated deep dive — we'll cache it so you can revisit instantly.", zh: "生成全新的交叉验证深度分析 — 我们会缓存以便随时再次查看。" },
  "deepDive.selectHotel": { en: "Select a single hotel to view a deep dive.", zh: "请选择一家酒店查看深度分析。" },
  "competitors.viewDetails": { en: "View details & deep dive", zh: "查看详情与深度分析" },

  "today.eyebrow": { en: "Today's brief", zh: "今日简报" },
  "today.summary": { en: "Today's summary", zh: "今日摘要" },
  "today.actions": { en: "Recommended actions", zh: "推荐行动" },
  "today.signals": { en: "Market signals (Malaysia)", zh: "市场信号（马来西亚）" },
  "today.occupancy": { en: "Occupancy outlook", zh: "入住率展望" },
  "today.demand": { en: "Market demand", zh: "市场需求" },
  "today.pricing": { en: "Competitor pricing", zh: "竞争对手定价" },
  "today.todo": { en: "To do", zh: "待办" },
  "today.doing": { en: "Doing", zh: "进行中" },
  "today.done": { en: "Done", zh: "完成" },
  "today.urgency.today": { en: "Today", zh: "今天" },
  "today.urgency.week": { en: "This week", zh: "本周" },
  "today.urgency.month": { en: "This month", zh: "本月" },

  "portfolio.empty": { en: "No hotels yet — add your first.", zh: "尚未添加酒店——添加第一家吧。" },
  "portfolio.subtitleHint": {
    en: "All your properties at a glance. Pick one to see today's full brief.",
    zh: "一目了然查看您所有的酒店。选择一家查看今天的完整简报。",
  },
  "portfolio.viewBrief": { en: "View brief", zh: "查看简报" },
  "portfolio.pickHotel": {
    en: "Select a specific hotel to see today's AI briefing.",
    zh: "选择具体酒店以查看今日的 AI 简报。",
  },

  "delete.title": { en: "Delete your account?", zh: "确定删除账户？" },
  "delete.body": {
    en: "This permanently removes all your hotels, briefings, chats, action history, and the account itself. This cannot be undone.",
    zh: "这将永久删除您所有的酒店、简报、聊天记录、行动历史以及账户本身。此操作无法撤销。",
  },
  "delete.confirm": { en: "Type DELETE to confirm", zh: "输入 DELETE 以确认" },
  "delete.cta": { en: "Delete forever", zh: "永久删除" },
  "delete.cancel": { en: "Cancel", zh: "取消" },

  // Today / Home
  "today.title.fallback": { en: "Good morning, {name}.", zh: "早上好，{name}。" },
  "today.subtitle.fallback": {
    en: "30-second snapshot for {hotel}. Read it, act on it, get on with your day.",
    zh: "为 {hotel} 准备的 30 秒简报。读完即行动，开始美好的一天。",
  },
  "today.summary.title": { en: "Today's summary", zh: "今日摘要" },
  "today.recommendedActions": { en: "Recommended actions", zh: "推荐行动" },
  "today.marketSignals": { en: "Market signals (Malaysia)", zh: "市场信号（马来西亚）" },
  "today.summary.occupancy": { en: "Occupancy outlook", zh: "入住率展望" },
  "today.summary.demand": { en: "Market demand", zh: "市场需求" },
  "today.summary.pricing": { en: "Competitor pricing", zh: "竞争对手定价" },
  "today.error.title": { en: "Couldn't load today's briefing.", zh: "无法加载今日简报。" },

  "occupancy.HIGH": { en: "HIGH", zh: "高" },
  "occupancy.MEDIUM": { en: "MEDIUM", zh: "中" },
  "occupancy.LOW": { en: "LOW", zh: "低" },
  "demand.STRONG": { en: "STRONG", zh: "强劲" },
  "demand.STEADY": { en: "STEADY", zh: "平稳" },
  "demand.WEAK": { en: "WEAK", zh: "疲软" },
  "pricing.HIGHER": { en: "HIGHER", zh: "高于市场" },
  "pricing.INLINE": { en: "INLINE", zh: "持平" },
  "pricing.LOWER": { en: "LOWER", zh: "低于市场" },

  "urgency.today": { en: "Today", zh: "今天" },
  "urgency.this_week": { en: "This week", zh: "本周" },
  "urgency.this_month": { en: "This month", zh: "本月" },

  "status.todo": { en: "To do", zh: "待办" },
  "status.doing": { en: "Doing", zh: "进行中" },
  "status.done": { en: "Done", zh: "已完成" },
  "status.inProgress": { en: "In progress", zh: "进行中" },

  "signal.public_holiday": { en: "Public holiday", zh: "公共假期" },
  "signal.school_holiday": { en: "School holiday", zh: "学校假期" },
  "signal.event": { en: "Event", zh: "活动" },
  "signal.tourism_trend": { en: "Tourism trend", zh: "旅游趋势" },
  "impact.surge": { en: "surge", zh: "激增" },
  "impact.uptick": { en: "uptick", zh: "上升" },
  "impact.soft": { en: "soft", zh: "疲软" },
  "impact.neutral": { en: "neutral", zh: "中性" },

  // Portfolio (home)
  "portfolio.eyebrow": { en: "Portfolio overview", zh: "组合概览" },
  "portfolio.titleSingular": { en: "{n} property", zh: "{n} 家酒店" },
  "portfolio.titlePlural": { en: "{n} properties", zh: "{n} 家酒店" },
  "portfolio.viewBriefBtn": { en: "View today's brief", zh: "查看今日简报" },
  "portfolio.rooms": { en: "rooms", zh: "间客房" },
  "portfolio.defaultProperty": { en: "Property", zh: "酒店" },

  // Pages
  "industry.eyebrow": { en: "Industry analysis", zh: "行业分析" },
  "industry.title": { en: "{segment} outlook for {location}", zh: "{location} 的 {segment} 细分市场展望" },
  "industry.subtitle": {
    en: "Where the {segment} segment is heading — and what it means for {hotel}.",
    zh: "{segment} 细分市场的走向，以及对 {hotel} 的意义。",
  },
  "competitors.eyebrow": { en: "Competitor intel", zh: "竞争对手情报" },
  "competitors.title": { en: "Who you're up against in {location}", zh: "{location} 的竞争对手" },
  "actions.eyebrow": { en: "Action plan", zh: "行动计划" },
  "actions.title": { en: "Three moves for {hotel}", zh: "为 {hotel} 准备的三个动作" },
  "actions.subtitle": {
    en: "Always three. Never more. Mark them as you go — your progress is saved on this device.",
    zh: "始终三个，绝不多。完成时标记一下——进度会保存在本设备。",
  },
  "selfexam.eyebrow": { en: "Self-examination", zh: "自我检查" },
  "selfexam.title": { en: "How {hotel} shows up online", zh: "{hotel} 在网上的表现" },
  "selfexam.subtitle": {
    en: "We scan your website, OTA listings, social profiles and reviews — then tell you what's missing and what to fix.",
    zh: "我们扫描您的网站、OTA 平台、社交资料和评价——然后告诉您缺什么、改什么。",
  },

  // PortfolioPrompt
  "prompt.title": { en: "Pick a hotel to continue", zh: "请先选择一家酒店" },
  "prompt.subtitle": {
    en: "This view is per-property. Select one of your hotels below or switch from the sidebar.",
    zh: "此页面按酒店显示。请在下方选择一家，或从侧边栏切换。",
  },
  "prompt.addFirst": { en: "Add your first hotel", zh: "添加您的第一家酒店" },

  // Profile page
  "profile.eyebrow": { en: "Profile", zh: "个人资料" },
  "profile.title": { en: "Account & settings", zh: "账户与设置" },
  "profile.subtitle": {
    en: "Manage your account, appearance, and language preferences.",
    zh: "管理您的账户、外观和语言偏好。",
  },
  "profile.account": { en: "Your account", zh: "您的账户" },
  "profile.preferences": { en: "Preferences", zh: "偏好设置" },
  "profile.preferences.desc": {
    en: "Appearance and language sync across your devices.",
    zh: "外观和语言会在您的所有设备上同步。",
  },
  "profile.theme": { en: "Theme", zh: "主题" },
  "profile.language": { en: "Language", zh: "语言" },
  "profile.theme.dark": { en: "Dark", zh: "深色" },
  "profile.theme.light": { en: "Light", zh: "浅色" },
  "profile.lang.en": { en: "English", zh: "英文" },
  "profile.lang.zh": { en: "Chinese (Simplified)", zh: "中文（简体）" },
  "profile.currentProperty": { en: "Current property", zh: "当前酒店" },

  // Industry page
  "industry.outlookEyebrow": { en: "Segment outlook", zh: "细分市场展望" },
  "industry.benchmark.adr": { en: "Segment benchmark ADR", zh: "细分市场基准 ADR" },
  "industry.benchmark.adr.hint": { en: "Average daily rate", zh: "平均每日房价" },
  "industry.benchmark.occ": { en: "Segment benchmark occupancy", zh: "细分市场基准入住率" },
  "industry.benchmark.occ.hint": { en: "Typical occupancy rate", zh: "典型入住率" },
  "industry.drivers": { en: "Demand drivers", zh: "需求驱动因素" },
  "industry.risks": { en: "Risks", zh: "风险" },
  "industry.error": { en: "Couldn't load analysis.", zh: "无法加载分析。" },

  // Actions page
  "actions.error": { en: "Couldn't load action plan.", zh: "无法加载行动计划。" },
  "actions.planMonitor": { en: "Plan Monitor", zh: "计划监测" },
  "actions.doneOf": { en: "{done} of {total} done", zh: "已完成 {done} / {total}" },
  "actions.resetProgress": { en: "Reset progress", zh: "重置进度" },

  // Competitors page
  "competitors.subtitle.scanning": {
    en: "Scanning hotels within {km} km of {hotel}…",
    zh: "正在扫描 {hotel} 周边 {km} 公里内的酒店…",
  },
  "competitors.subtitle.done": {
    en: "Scanned {n} hotels within {km} km of {hotel} — {top} closely match your {profile}.",
    zh: "已扫描 {hotel} 周边 {km} 公里内的 {n} 家酒店——其中 {top} 家与您的 {profile} 高度匹配。",
  },
  "competitors.within": { en: "Within ~{km} km of your property", zh: "约在您酒店 {km} 公里范围内" },
  "competitors.error": { en: "Couldn't load competitors.", zh: "无法加载竞争对手。" },
  "competitors.stat.scanned": { en: "Hotels scanned", zh: "已扫描酒店" },
  "competitors.stat.adr": { en: "Avg. competitor ADR ({c})", zh: "对手平均 ADR（{c}）" },
  "competitors.stat.occ": { en: "Avg. competitor occupancy", zh: "对手平均入住率" },
  "competitors.stat.promo": { en: "Active promotions nearby", zh: "周边在售促销" },
  "competitors.section.top": { en: "Closest matches to your hotel", zh: "与您酒店最相似的对手" },
  "competitors.section.top.desc": {
    en: "Same star tier, similar profile, same target guest — these are your true comp set.",
    zh: "同等星级、相似定位、相同目标客群——这些才是您的真实对标集。",
  },
  "competitors.section.others": { en: "All other hotels in your radius", zh: "范围内的其他酒店" },
  "competitors.section.others.desc": {
    en: "Different star tier or target guest, but still part of the local market.",
    zh: "星级或目标客群不同，但仍是本地市场的一部分。",
  },
  "competitors.section.ranked": { en: "Competitors ranked by {sort}", zh: "按 {sort} 排序的对手" },
  "competitors.section.ranked.desc": {
    en: "Ordered by your chosen filter. Items marked with a brand badge are your closest comp set.",
    zh: "按您选择的排序方式排列。带品牌标记的为最贴近的对标集。",
  },
  "competitors.topMatches": { en: "{n} top matches", zh: "{n} 家高度匹配" },
  "competitors.kmAway": { en: "{km} km away", zh: "距离 {km} 公里" },
  "competitors.estAdr": { en: "Est. ADR", zh: "预估 ADR" },
  "competitors.occupancy": { en: "Occupancy", zh: "入住率" },
  "competitors.vsYou": { en: "vs You", zh: "与您对比" },
  "competitors.match": { en: "{n}% match", zh: "匹配 {n}%" },
  "competitors.showDetails": { en: "Show details", zh: "查看详情" },
  "competitors.hideDetails": { en: "Hide details", zh: "收起详情" },
  "competitors.reviews": { en: "{n} reviews", zh: "{n} 条评价" },
  "competitors.reviewsLabel": { en: "reviews", zh: "评价" },
  "competitors.recentMove": { en: "Recent move:", zh: "近期动作：" },
  "competitors.position.below": { en: "Below", zh: "低于" },
  "competitors.position.inline": { en: "Inline", zh: "持平" },
  "competitors.position.above": { en: "Above", zh: "高于" },
  "competitors.threat.low": { en: "low threat", zh: "低威胁" },
  "competitors.threat.medium": { en: "medium threat", zh: "中等威胁" },
  "competitors.threat.high": { en: "high threat", zh: "高威胁" },
  "competitors.profile.default": { en: "profile", zh: "定位" },
};

function format(s: string, vars?: Record<string, string | number>): string {
  if (!vars) return s;
  return s.replace(/\{(\w+)\}/g, (_, k) => String(vars[k] ?? `{${k}}`));
}

export function useT() {
  const { lang } = useSettings();
  return (
    key: string,
    fallbackOrVars?: string | Record<string, string | number>,
    vars?: Record<string, string | number>,
  ): string => {
    const entry = DICT[key];
    let fallback: string | undefined;
    let v: Record<string, string | number> | undefined;
    if (typeof fallbackOrVars === "string") {
      fallback = fallbackOrVars;
      v = vars;
    } else {
      v = fallbackOrVars;
    }
    const raw = entry ? entry[lang] : (fallback ?? key);
    return format(raw, v);
  };
}
