/* Sentosa Marketplace - bilingual layer (English / 简体中文)
   Demonstrates the "bilingual-ready" commitment: language is a runtime switch over a
   string catalogue, not a separate build. Product and venue names are translated from
   the catalogue record, which is how SDC-approved content would carry a zh field.

   Scope note for the demo: this is an illustrative slice covering the buyer-facing
   chrome, catalogue and product surfaces. Full-platform localisation is a delivery
   activity, not a claim being made here. */

const STRINGS = {
  en: {
    /* chrome */
    search: "Search products, partners or experiences",
    nav_catalogue: "Catalogue", nav_ai: "AI planner", nav_mice: "MICE venues", nav_bookings: "My bookings",
    home: "Home", signout: "Sign out", cart: "Itinerary",
    gov_band: "An official digital service of Sentosa Development Corporation",
    secure: "Secure · AWS Singapore",
    lang_label: "Language", lang_other: "中文",

    /* catalogue */
    cat_kicker: "Phase 1 · Live catalogue",
    cat_title: "Browse Sentosa island products",
    cat_lede: "Trade-rate tickets, experiences and MICE venues from accredited island partners. Add to an itinerary and book in one order.",
    cat_categories: "6 categories", cat_partners: "40+ island partners", cat_ai: "Plan an itinerary with AI",
    filters: "Filters", category: "Category", partner: "Partner",
    products: "products", sort: "Sort",
    sort_featured: "Featured", sort_low: "Price: low to high", sort_high: "Price: high to low",
    add: "Add", per: "per", trade: "trade",
    sold: "sold", no_results: "No products match your search.",
    no_results_hint: "Try a different category, or clear the seller filter.",
    clear: "Clear", clear_all: "Clear all filters", seller: "seller", sellers: "sellers",

    /* categories */
    "All categories": "All categories", "Island admission": "Island admission",
    "Attraction": "Attraction", "Experience": "Experience", "Dining": "Dining", "MICE": "MICE",

    /* product types + tags */
    "Ticket": "Ticket", "Package": "Package", "Bundle": "Bundle", "Charter": "Charter",
    "Tour": "Tour", "Event": "Event",
    "Featured": "Featured", "Bestseller": "Bestseller", "New": "New",
  },
  zh: {
    search: "搜索产品、合作伙伴或体验",
    nav_catalogue: "产品目录", nav_ai: "AI 行程规划", nav_mice: "会展场地", nav_bookings: "我的订单",
    home: "首页", signout: "退出登录", cart: "行程",
    gov_band: "圣淘沙发展局官方数字服务",
    secure: "安全连接 · AWS 新加坡",
    lang_label: "语言", lang_other: "English",

    cat_kicker: "第一阶段 · 实时产品目录",
    cat_title: "浏览圣淘沙岛屿产品",
    cat_lede: "来自认证岛屿合作伙伴的同业价门票、体验项目与会展场地。加入行程，一次下单。",
    cat_categories: "6 个类别", cat_partners: "40+ 岛屿合作伙伴", cat_ai: "使用 AI 规划行程",
    filters: "筛选", category: "类别", partner: "合作伙伴",
    products: "个产品", sort: "排序",
    sort_featured: "推荐", sort_low: "价格：由低至高", sort_high: "价格：由高至低",
    add: "加入", per: "每", trade: "同业价",
    sold: "已售", no_results: "没有符合搜索条件的产品。",
    no_results_hint: "请尝试其他类别，或清除合作伙伴筛选。",
    clear: "清除", clear_all: "清除所有筛选", seller: "个合作伙伴", sellers: "个合作伙伴",

    "All categories": "全部类别", "Island admission": "入岛门票",
    "Attraction": "景点", "Experience": "体验", "Dining": "餐饮", "MICE": "会展",

    "Ticket": "门票", "Package": "套票", "Bundle": "组合", "Charter": "包船",
    "Tour": "导览", "Event": "活动",
    "Featured": "推荐", "Bestseller": "热销", "New": "新品",
  },
};

/* Product and venue names - in production these ride on the SDC-approved catalogue record */
const NAME_ZH = {
  "Cable Car Sky Pass": "缆车空中通行证",
  "Skyline Luge & Skyride - 2 rides": "斜坡滑车与空中吊椅 - 2 次",
  "Resort Beach Day Bundle": "度假海滩一日组合",
  "Oceanarium Admission": "海洋馆门票",
  "Sunset Sail - Group Charter": "日落航行 - 团体包船",
  "Heritage Walking Tour": "历史文化步行导览",
  "Indoor Skydiving - Trade Slot": "室内跳伞 - 同业时段",
  "MICE Welcome Reception Pass": "会展欢迎酒会通行证",
  "Island Admission - Day Pass": "入岛门票 - 一日通行证",
  "Beachside Banquet - 10 pax": "海滨宴会 - 10 人桌",
  "Sky Dining - Cable Car Cabin": "空中缆车餐厅 - 包厢",
  "Multi-Attraction Pass (3-in-1)": "多景点通行证（三合一）",

  "Sentosa Cable Car": "圣淘沙缆车",
  "Skyline Luge": "斜坡滑车",
  "Sentosa Islander": "圣淘沙岛民",
  "Marine Life Park": "海洋生物园",
  "Sentosa Marina": "圣淘沙码头",
  "Fort Siloso": "西乐索炮台",
  "iFly": "iFly 新加坡",
  "Sentosa MICE": "圣淘沙会展",
  "Sentosa Development Corporation": "圣淘沙发展局",
  "Tanjong Beach Club": "丹戎海滩俱乐部",

  "adult": "成人", "person": "人", "pax": "位", "boat": "艘",
  "delegate": "代表", "table": "桌", "cabin": "包厢",
};

/* Language bus - any component can read window.LANG and re-render on change */
window.LANG = "en";
window.setLang = (l) => {
  window.LANG = l;
  document.documentElement.lang = l === "zh" ? "zh-Hans-SG" : "en";
  window.dispatchEvent(new CustomEvent("sm-lang", { detail: l }));
};

function useLang() {
  const [lang, setL] = React.useState(window.LANG);
  React.useEffect(() => {
    const h = (e) => setL(e.detail);
    window.addEventListener("sm-lang", h);
    return () => window.removeEventListener("sm-lang", h);
  }, []);
  const t = React.useCallback(
    (key) => (STRINGS[lang] && STRINGS[lang][key]) || STRINGS.en[key] || key, [lang]);
  const tn = React.useCallback(
    (name) => (lang === "zh" && NAME_ZH[name]) || name, [lang]);
  return { lang, t, tn };
}

/* Language picker.
   Shows the CURRENT language and opens a menu to choose. An earlier version was a
   single button labelled with the *other* language, which read as inverted: the page
   was Chinese but the control said "EN". A menu makes the current state explicit. */
const LANGUAGES = [
  { code: "en", label: "English", native: "English" },
  { code: "zh", label: "Chinese", native: "中文" },
];

function LangMenu() {
  const { lang } = useLang();
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const current = LANGUAGES.find(l => l.code === lang) || LANGUAGES[0];

  React.useEffect(() => {
    if (!open) return;
    const onDown = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => e.key === "Escape" && setOpen(false);
    document.addEventListener("mousedown", onDown);
    window.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("mousedown", onDown); window.removeEventListener("keydown", onKey); };
  }, [open]);

  return (
    <div ref={ref} style={{ position: "relative", flex: "none" }}>
      <button onClick={() => setOpen(o => !o)}
        aria-haspopup="listbox" aria-expanded={open} aria-label={`Language: ${current.label}`}
        style={{ display: "inline-flex", alignItems: "center", gap: 8, cursor: "pointer",
          background: open ? "#333" : "#262626", border: "1.5px solid #3a3a3a", color: "#fff",
          borderRadius: "var(--radius-md)", height: 44, padding: "0 12px",
          fontFamily: "var(--font-sans)", fontSize: 13.5, fontWeight: 600 }}>
        <Icon name="languages" size={17} color="var(--orange-300)" />
        {current.native}
        <Icon name={open ? "chevron-up" : "chevron-down"} size={15} color="#9A9A9A" />
      </button>

      {open && (
        <div role="listbox" aria-label="Select language"
          style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, minWidth: 190, zIndex: 60,
            background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius-md)",
            boxShadow: "0 12px 32px rgba(0,0,0,.22)", overflow: "hidden", padding: 4 }}>
          {LANGUAGES.map(l => {
            const on = l.code === lang;
            return (
              <button key={l.code} role="option" aria-selected={on}
                onClick={() => { window.setLang(l.code); setOpen(false); }}
                style={{ display: "flex", alignItems: "center", gap: 10, width: "100%",
                  padding: "10px 11px", cursor: "pointer", border: 0, textAlign: "left",
                  borderRadius: "var(--radius-sm)", background: on ? "var(--orange-50)" : "transparent",
                  fontFamily: "var(--font-sans)", fontSize: 14,
                  fontWeight: on ? 600 : 500, color: on ? "var(--orange-900)" : "var(--fg1)" }}>
                <span style={{ width: 16, display: "inline-flex", flex: "none" }}>
                  {on && <Icon name="check" size={16} />}
                </span>
                <span style={{ flex: 1 }}>{l.native}</span>
                {l.code !== "en" && <span style={{ fontSize: 12, color: "var(--fg3)" }}>{l.label}</span>}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* Kept so any existing reference still resolves */
const LangToggle = LangMenu;

Object.assign(window, { STRINGS, NAME_ZH, LANGUAGES, useLang, LangMenu, LangToggle });
