/* ============================================================
   SYMPHO · EB — internacionalización (ES / EN / ZH)
   Traduce el menú lateral y los títulos de página del sistema Eb.
   El contenido de datos (nombres, VIN, cifras) no se traduce.
   ============================================================ */

// -- diccionario base: nav id -> {en, zh}. También se usa para el título de AppHead. --
const EB_NAV_I18N = {
  // master
  resumen:       { en: "Summary",              zh: "概览" },
  catalogo:      { en: "Catalog",               zh: "产品目录" },
  cedi:          { en: "DC Inventory",          zh: "配送中心库存" },
  ordenes:       { en: "Orders & Reservations", zh: "订单与预订" },
  importaciones: { en: "Imports",               zh: "进口管理" },
  logistica:     { en: "Logistics & VIN",       zh: "物流与车架号" },
  almacen:       { en: "Warehouse & Logistics", zh: "仓库与物流" },
  credito:       { en: "Credit & Accounts",     zh: "信用与账户" },
  garantias:     { en: "Warranties & OEM",      zh: "质保与原厂" },
  dealers:       { en: "Dealer Network",        zh: "经销商网络" },
  finanzas:      { en: "Finance",               zh: "财务" },
  facturacion:   { en: "Billing",               zh: "开票" },
  chat:          { en: "Messaging",             zh: "内部消息" },
  etiquetas:     { en: "QR Labels",             zh: "二维码标签" },
  // dealer
  "d-resumen":     { en: "Summary",             zh: "概览" },
  "d-catalogo":    { en: "Master Catalog",      zh: "总部目录" },
  "d-reservar":    { en: "Reserve from Master", zh: "向总部预订" },
  "d-ordenes":     { en: "My Orders",           zh: "我的订单" },
  "d-inventario":  { en: "My Inventory",        zh: "我的库存" },
  "d-garantias":   { en: "Warranties",          zh: "质保" },
  "d-postventa":   { en: "After-sales",         zh: "售后服务" },
  "d-scanner":     { en: "Verify Shipment",     zh: "核对货件" },
  "d-finanzas":    { en: "Finance",             zh: "财务" },
  "d-facturacion": { en: "Billing",             zh: "开票" },
  "d-chat":        { en: "Messaging",           zh: "内部消息" },
  // gerencia
  "g-dashboard": { en: "Executive Dashboard", zh: "执行仪表盘" },
  "g-ranking":   { en: "Dealer Ranking",      zh: "经销商排名" },
  "g-demanda":   { en: "Demand Forecast",     zh: "需求预测" },
};
window.EB_NAV_I18N = EB_NAV_I18N;

function ebGetCustom() {
  try { return JSON.parse(localStorage.getItem("eb_i18n_custom") || "{}"); }
  catch (e) { return {}; }
}
function ebSetCustom(obj) {
  try { localStorage.setItem("eb_i18n_custom", JSON.stringify(obj)); } catch (e) {}
}
window.ebGetCustom = ebGetCustom;
window.ebSetCustom = ebSetCustom;

// resuelve la etiqueta de nav / título de página para un id dado
function ebNavLabel(id, lang, fallback) {
  if (!id || !lang || lang === "es") return fallback;
  const custom = ebGetCustom();
  const c = custom.nav && custom.nav[id] && custom.nav[id][lang];
  if (c) return c;
  const d = EB_NAV_I18N[id] && EB_NAV_I18N[id][lang];
  return d || fallback;
}
window.ebNavLabel = ebNavLabel;
window.ebPageTitle = ebNavLabel; // mismo diccionario: el título de AppHead reutiliza la etiqueta de nav

const EB_LANG_META = { es: { label: "Español" }, en: { label: "English" }, zh: { label: "中文" } };
window.EB_LANG_META = EB_LANG_META;

// ---------------- language switch + customizer (top bar, solo dentro de Eb) ----------------
function EbLangSwitcher() {
  const nav = useNav();
  const [open, setOpen] = useState(false);
  const ref = useRef();
  useOutside([ref], () => setOpen(false));
  if (!nav || nav.loc.view !== "app" || nav.loc.appId !== "eb") return null;
  const LANGS = [["es", "ES"], ["en", "EN"], ["zh", "中"]];
  return (
    <div ref={ref} style={{ position: "relative", display: "flex", alignItems: "center", gap: 4 }}>
      <div className="eb-lang-switch">
        {LANGS.map(([code, label]) => (
          <button key={code} data-on={nav.ebLang === code} onClick={() => nav.setEbLang(code)} title={EB_LANG_META[code].label}>{label}</button>
        ))}
      </div>
      <button className="ic-btn" data-on={open} title="Personalizar idiomas" onClick={() => setOpen(v => !v)}>
        <Icon name="settings" size={16} />
      </button>
      {open && <EbLangCustomizer onClose={() => setOpen(false)} />}
    </div>
  );
}

function EbLangCustomizer({ onClose }) {
  const nav = useNav();
  const [tab, setTab] = useState(nav.ebLang !== "es" ? nav.ebLang : "en");
  const [custom, setCustom] = useState(() => ebGetCustom());
  const groups = [
    ["Master Dealer · menú", window.EB_NAV.master],
    ["Dealer · menú", window.EB_NAV.dealer],
  ];
  function setVal(id, val) {
    setCustom(c => {
      const next = { ...c, nav: { ...(c.nav || {}) } };
      next.nav[id] = { ...(next.nav[id] || {}), [tab]: val };
      return next;
    });
  }
  function val(id) {
    return (custom.nav && custom.nav[id] && custom.nav[id][tab] != null)
      ? custom.nav[id][tab]
      : (EB_NAV_I18N[id] ? EB_NAV_I18N[id][tab] : "") || "";
  }
  function save() { ebSetCustom(custom); nav.bumpI18n(); onClose(); }
  function reset() { ebSetCustom({}); setCustom({}); nav.bumpI18n(); }
  return (
    <div className="cmd-overlay" onMouseDown={onClose}>
      <div className="cmd-panel" style={{ width: 640 }} onMouseDown={e => e.stopPropagation()}>
        <div className="cmd-input" style={{ gap: 14 }}>
          <b style={{ fontSize: 14.5, whiteSpace: "nowrap" }}>Personalizar idiomas</b>
          <div className="seg" style={{ marginLeft: "auto" }}>
            <button className="seg-btn" data-on={tab === "en"} onClick={() => setTab("en")}>English</button>
            <button className="seg-btn" data-on={tab === "zh"} onClick={() => setTab("zh")}>中文</button>
          </div>
          <button className="ic-btn" onClick={onClose}><Icon name="ext" size={15} /></button>
        </div>
        <p className="muted" style={{ fontSize: 12, padding: "10px 20px 0" }}>
          Ajusta la traducción de las etiquetas del menú y los títulos de página del sistema Eb. El contenido de los datos (nombres, VIN, cifras) no se traduce.
        </p>
        <div className="cmd-list scroll" style={{ padding: "8px 20px 4px", maxHeight: "52vh" }}>
          {groups.map(([label, items]) => (
            <div key={label} style={{ marginBottom: 14 }}>
              <div className="eyebrow" style={{ padding: "10px 0 8px" }}>{label}</div>
              {items.map(n => (
                <div key={n.id} style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 7, alignItems: "center" }}>
                  <span className="muted" style={{ fontSize: 12.5 }}>{n.label}</span>
                  <input className="field" style={{ height: 32, fontSize: 12.5 }} value={val(n.id)} onChange={e => setVal(n.id, e.target.value)} />
                </div>
              ))}
            </div>
          ))}
        </div>
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", padding: "12px 20px", borderTop: "1px solid var(--line)" }}>
          <button className="btn btn-sm" onClick={reset}>Restablecer</button>
          <button className="btn btn-sm btn-primary" style={{ background: "var(--eb)" }} onClick={save}><Icon name="check" size={13} /> Guardar</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { EbLangSwitcher, EbLangCustomizer });

// ---------------- Master/Dealer + Perfil switch (Eb only) ----------------
function EbRoleProfileSwitch({ rc, role, nav }) {
  const orgs = Object.keys(rc.roles); // master, dealer
  const profiles = window.EB_PROFILES;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <div className="seg" style={{ width: "100%" }}>
        {orgs.map(rk => (
          <button key={rk} className="seg-btn" style={{ flex: 1, justifyContent: "center" }} data-on={role === rk} onClick={() => nav.setRole("eb", rk)}>
            <Icon name={rc.roles[rk].icon} size={14} /> {rc.roles[rk].label.split(" ")[0]}
          </button>
        ))}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 3, padding: 3, background: "var(--bg)", border: "1px solid var(--line)", borderRadius: 10 }}>
        {Object.keys(profiles).map(pk => {
          const on = nav.ebProfile === pk;
          return (
            <button key={pk} onClick={() => nav.setEbProfile(pk)}
              style={{ display: "flex", alignItems: "center", gap: 9, padding: "8px 10px", borderRadius: 7, border: "none", cursor: "pointer",
                background: on ? "var(--eb)" : "transparent", color: on ? "oklch(0.16 0.02 264)" : "var(--text-3)",
                fontFamily: "var(--ui)", fontSize: 12.5, fontWeight: on ? 600 : 500, textAlign: "left", width: "100%", transition: "background 0.14s, color 0.14s" }}>
              <Icon name={profiles[pk].icon} size={14} /> {profiles[pk].label}
            </button>
          );
        })}
      </div>
    </div>
  );
}
window.EbRoleProfileSwitch = EbRoleProfileSwitch;
