/* RINAU HEX — Admin module — Provider + Login + Panel shell + Text tab */

/* Credenciales: se cargan en runtime desde /api/admin-config (variables de
   entorno en Vercel), no quedan escritas en el código fuente. Fallback local
   para cuando se abre el HTML directamente sin el endpoint (ej. sin Vercel). */
let RHX_AUTH_CONFIG = {
  user: 'admin',
  hash: '6b7b3188b28183b84a5d56b8bc2382c316a6412d34d242ece9fc63a58d874fc2',
};
let RHX_AUTH_CONFIG_READY = (async () => {
  try {
    const r = await fetch('/api/admin-config');
    if (r.ok) {
      const cfg = await r.json();
      if (cfg && cfg.hash) RHX_AUTH_CONFIG = { user: cfg.user || 'admin', hash: cfg.hash };
    }
  } catch (e) { /* sin backend disponible: se usa el fallback local */ }
})();

const AdminCtx = React.createContext(null);
window.useAdmin = () => React.useContext(AdminCtx);

/* deep clone via JSON — enough for our plain data */
const dclone = (x) => JSON.parse(JSON.stringify(x));

/* Simple non-array deep merge */
function deepMerge(target, src) {
  if (target == null || typeof target !== 'object') return src;
  if (src == null) return target;
  if (Array.isArray(src)) return src;
  const out = Array.isArray(target) ? [...target] : { ...target };
  for (const k of Object.keys(src)) {
    if (src[k] === undefined) continue;
    if (src[k] !== null && typeof src[k] === 'object' && !Array.isArray(src[k])) {
      out[k] = deepMerge(target[k], src[k]);
    } else {
      out[k] = src[k];
    }
  }
  return out;
}

/* set nested by path "hero.title1" — handles array indices like "features.items.0.t" */
function setByPath(obj, path, value) {
  const parts = path.split('.');
  let cur = obj;
  for (let i = 0; i < parts.length - 1; i++) {
    if (cur[parts[i]] == null || typeof cur[parts[i]] !== 'object') return;
    cur = cur[parts[i]];
  }
  cur[parts[parts.length - 1]] = value;
}
function getByPath(obj, path) {
  return path.split('.').reduce((o, k) => (o == null ? o : o[k]), obj);
}
window.RHX_setByPath = setByPath;
window.RHX_getByPath = getByPath;
window.RHX_deepMerge = deepMerge;
window.RHX_dclone = dclone;

/* --- LocalStorage helpers (safe) --- */
function lsGet(k, fallback) {
  try { const v = localStorage.getItem(k); return v == null ? fallback : JSON.parse(v); }
  catch (e) { return fallback; }
}
function lsSet(k, v) {
  try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {}
}

/* ============== ADMIN PROVIDER ============== */
function AdminProvider({ children }) {
  const [authed, setAuthed] = React.useState(() => {
    try { return sessionStorage.getItem('rhx-auth') === '1'; } catch (e) { return false; }
  });
  const [loginOpen, setLoginOpen] = React.useState(false);
  const [panelOpen, setPanelOpen] = React.useState(false);

  /* Text overrides: { "es.hero.title1": "Foo", "es.features.items.0.t": "Bar" } */
  const [overrides, setOverrides] = React.useState(() => lsGet('rhx-overrides', {}));

  /* Partners */
  const [partnerVis, setPartnerVis] = React.useState(() => lsGet('rhx-partner-vis', {}));
  const [customPartners, setCustomPartners] = React.useState(() => lsGet('rhx-custom-partners', []));
  const [partnerOverrides, setPartnerOverrides] = React.useState(() => lsGet('rhx-partner-overrides', {}));
  const [partnerLogos, setPartnerLogos] = React.useState(() => lsGet('rhx-partner-logos', {}));

  /* Categories */
  const [customCategories, setCustomCategories] = React.useState(() => lsGet('rhx-custom-cats', []));

  /* Services */
  const [hiddenServices, setHiddenServices] = React.useState(() => lsGet('rhx-services-hidden', {}));
  const [serviceOverrides, setServiceOverrides] = React.useState(() => lsGet('rhx-service-overrides', {}));
  const [customServices, setCustomServices] = React.useState(() => lsGet('rhx-custom-services', []));

  /* version bump so subscribed components re-render after mutating window.RHX */
  const [version, setVersion] = React.useState(0);

  /* Snapshot originals once */
  React.useEffect(() => {
    if (!window.RHX._original) {
      window.RHX._original = {
        ui: dclone(window.RHX.ui),
        partnersData: dclone(window.RHX.partnersData),
        services: dclone(window.RHX.services),
      };
    }
  }, []);

  /* Apply all overrides to live window.RHX whenever they change */
  React.useEffect(() => {
    if (!window.RHX._original) {
      window.RHX._original = {
        ui: dclone(window.RHX.ui),
        partnersData: dclone(window.RHX.partnersData),
        services: dclone(window.RHX.services),
      };
    }
    /* === UI === */
    window.RHX.ui = dclone(window.RHX._original.ui);
    for (const [key, value] of Object.entries(overrides)) {
      const dot = key.indexOf('.');
      if (dot < 0) continue;
      const lang = key.slice(0, dot);
      const path = key.slice(dot + 1);
      if (!window.RHX.ui[lang]) continue;
      setByPath(window.RHX.ui[lang], path, value);
    }
    /* Add custom categories to ui[lang].portfolio.cats */
    for (const lang of ['es','en']) {
      const cats = window.RHX.ui[lang].portfolio.cats;
      customCategories.forEach(c => {
        if (!cats.find(x => x.id === c.id)) {
          cats.push({ id: c.id, label: (c.label && c.label[lang]) || c.id, icon: c.icon || 'Layers' });
        }
      });
    }

    /* === PARTNERS === */
    const visiblePartners = window.RHX._original.partnersData
      .filter(p => partnerVis[p.id] !== false)
      .map(p => {
        const ovr = partnerOverrides[p.id] || {};
        const merged = deepMerge(p, ovr);
        const logo = partnerLogos[p.id];
        if (logo && (logo.light || logo.dark)) merged.logo = logo;
        return merged;
      });
    const customsWithLogos = customPartners.map(p => {
      const c = { ...p };
      const logo = partnerLogos[p.id];
      if (logo && (logo.light || logo.dark)) c.logo = logo;
      return c;
    });
    window.RHX.partnersData = [...visiblePartners, ...customsWithLogos];

    /* === SERVICES === */
    const visibleServices = window.RHX._original.services
      .filter(s => !hiddenServices[s.id])
      .map(s => {
        const ovr = serviceOverrides[s.id] || {};
        return deepMerge(s, ovr);
      });
    window.RHX.services = [...visibleServices, ...customServices];

    /* persist */
    lsSet('rhx-overrides', overrides);
    lsSet('rhx-partner-vis', partnerVis);
    lsSet('rhx-custom-partners', customPartners);
    lsSet('rhx-partner-overrides', partnerOverrides);
    lsSet('rhx-partner-logos', partnerLogos);
    lsSet('rhx-custom-cats', customCategories);
    lsSet('rhx-services-hidden', hiddenServices);
    lsSet('rhx-service-overrides', serviceOverrides);
    lsSet('rhx-custom-services', customServices);

    setVersion(v => v + 1);
  }, [overrides, partnerVis, customPartners, partnerOverrides, partnerLogos,
      customCategories, hiddenServices, serviceOverrides, customServices]);

  async function tryLogin(user, pass) {
    await RHX_AUTH_CONFIG_READY;
    if (user !== RHX_AUTH_CONFIG.user) return { ok: false, reason: 'user' };
    try {
      const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(pass));
      const hex = [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('');
      if (hex !== RHX_AUTH_CONFIG.hash) return { ok: false, reason: 'pass' };
    } catch (e) { return { ok: false, reason: 'crypto' }; }
    try { sessionStorage.setItem('rhx-auth', '1'); } catch (e) {}
    setAuthed(true); setLoginOpen(false); setPanelOpen(true);
    return { ok: true };
  }
  function logout() {
    try { sessionStorage.removeItem('rhx-auth'); } catch (e) {}
    setAuthed(false); setPanelOpen(false);
  }

  /* === Text overrides === */
  function setOverride(lang, path, value) {
    const key = `${lang}.${path}`;
    setOverrides(o => {
      const n = { ...o };
      if (value === '' || value == null) delete n[key];
      else n[key] = value;
      return n;
    });
  }
  function resetAllOverrides() { setOverrides({}); }

  /* === Partners === */
  function setPartnerVisibility(id, visible) { setPartnerVis(v => ({ ...v, [id]: visible })); }
  function addCustomPartner(p) { setCustomPartners(cs => [...cs, p]); }
  function removeCustomPartner(id) {
    setCustomPartners(cs => cs.filter(p => p.id !== id));
    setPartnerLogos(ls => { const n = { ...ls }; delete n[id]; return n; });
  }
  function updateCustomPartner(id, patch) {
    setCustomPartners(cs => cs.map(p => p.id === id ? deepMerge(p, patch) : p));
  }
  function setPartnerOverride(id, patch) {
    setPartnerOverrides(o => ({ ...o, [id]: deepMerge(o[id] || {}, patch) }));
  }
  function resetPartnerOverride(id) {
    setPartnerOverrides(o => { const n = { ...o }; delete n[id]; return n; });
  }
  function setPartnerLogo(id, side, dataUrl) {
    setPartnerLogos(ls => {
      const n = { ...ls };
      const entry = { ...(n[id] || {}) };
      if (dataUrl == null) delete entry[side]; else entry[side] = dataUrl;
      if (!entry.light && !entry.dark) delete n[id]; else n[id] = entry;
      return n;
    });
  }

  /* === Categories === */
  function addCustomCategory(c) { setCustomCategories(cs => [...cs, c]); }
  function removeCustomCategory(id) {
    setCustomCategories(cs => cs.filter(c => c.id !== id));
    /* also unhide services pointing here? leave as-is */
  }
  function updateCustomCategory(id, patch) {
    setCustomCategories(cs => cs.map(c => c.id === id ? deepMerge(c, patch) : c));
  }

  /* === Services === */
  function setServiceHidden(id, hidden) {
    setHiddenServices(h => {
      const n = { ...h };
      if (hidden) n[id] = true; else delete n[id];
      return n;
    });
  }
  function setServiceOverride(id, patch) {
    setServiceOverrides(o => ({ ...o, [id]: deepMerge(o[id] || {}, patch) }));
  }
  function resetServiceOverride(id) {
    setServiceOverrides(o => { const n = { ...o }; delete n[id]; return n; });
  }
  function addCustomService(s) { setCustomServices(cs => [...cs, s]); }
  function removeCustomService(id) { setCustomServices(cs => cs.filter(s => s.id !== id)); }
  function updateCustomService(id, patch) {
    setCustomServices(cs => cs.map(s => s.id === id ? deepMerge(s, patch) : s));
  }

  const value = {
    authed, loginOpen, panelOpen, version,
    overrides, partnerVis, customPartners, partnerOverrides, partnerLogos,
    customCategories, hiddenServices, serviceOverrides, customServices,
    setLoginOpen, setPanelOpen, tryLogin, logout,
    setOverride, resetAllOverrides,
    setPartnerVisibility, addCustomPartner, removeCustomPartner, updateCustomPartner,
    setPartnerOverride, resetPartnerOverride, setPartnerLogo,
    addCustomCategory, removeCustomCategory, updateCustomCategory,
    setServiceHidden, setServiceOverride, resetServiceOverride,
    addCustomService, removeCustomService, updateCustomService,
  };

  return <AdminCtx.Provider value={value}>{children}</AdminCtx.Provider>;
}

/* ============== ADM BUTTON ============== */
function AdmButton() {
  const adm = window.useAdmin();
  const I = window.RHX_ICONS;
  const open = () => { if (adm.authed) adm.setPanelOpen(true); else adm.setLoginOpen(true); };
  return (
    <button onClick={open}
      className={`flex items-center gap-1.5 uppercase transition ${adm.authed ? 'text-[#14B8A6]' : 'hover:text-[#14B8A6]'}`}
      title="Admin">
      <I.Shield size={11}/>
      <span>ADM</span>
      {adm.authed && <span className="w-1.5 h-1.5 bg-[#14B8A6] rounded-full"></span>}
    </button>
  );
}

/* ============== LOGIN MODAL ============== */
function LoginModal() {
  const adm = window.useAdmin();
  const I = window.RHX_ICONS;
  const [user, setUser] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  React.useEffect(() => {
    if (adm.loginOpen) { setUser(''); setPass(''); setErr(''); }
  }, [adm.loginOpen]);
  if (!adm.loginOpen) return null;

  const submit = async (e) => {
    e.preventDefault(); setBusy(true);
    const r = await adm.tryLogin(user.trim(), pass);
    setBusy(false);
    if (!r.ok) setErr(r.reason === 'user' ? 'Usuario incorrecto.' : 'Contraseña incorrecta.');
  };

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm"
         onClick={()=>adm.setLoginOpen(false)}>
      <form onSubmit={submit} onClick={(e)=>e.stopPropagation()}
        className="relative w-full max-w-md bg-[#0B132B] border border-[#14B8A6]/30 text-white p-8 rounded-xl shadow-2xl">
        <button type="button" onClick={()=>adm.setLoginOpen(false)}
          className="absolute top-4 right-4 text-gray-400 hover:text-white">
          <I.X size={18}/>
        </button>
        <div className="font-mono text-[10px] tracking-[0.24em] text-[#14B8A6] uppercase mb-2 flex items-center gap-2">
          <I.Shield size={11}/>// RHX · ADMIN · AUTH
        </div>
        <h3 className="font-display font-medium text-2xl tracking-tight mb-1">Acceso administrativo</h3>
        <p className="text-[12px] text-gray-400 mb-6">Ingresa tus credenciales para editar contenido del sitio.</p>
        <label className="block mb-4">
          <span className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Usuario</span>
          <input value={user} onChange={(e)=>setUser(e.target.value)} autoFocus
            className="mt-1 w-full p-3 bg-[#0A0F1A] border border-white/10 text-[14px] focus:border-[#14B8A6] outline-none transition-colors"/>
        </label>
        <label className="block mb-2">
          <span className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Contraseña</span>
          <input value={pass} onChange={(e)=>setPass(e.target.value)} type="password"
            className="mt-1 w-full p-3 bg-[#0A0F1A] border border-white/10 text-[14px] focus:border-[#14B8A6] outline-none transition-colors"/>
        </label>
        {err && <div className="mt-3 text-[12px] text-[#EF4444] font-mono">// {err}</div>}
        <button type="submit" disabled={busy}
          className="mt-6 w-full inline-flex items-center justify-center gap-3 bg-[#14B8A6] hover:bg-[#0D9488] disabled:opacity-60 text-white px-6 py-3.5 font-medium text-[12px] uppercase tracking-[0.18em] transition-colors">
          {busy ? 'Verificando…' : 'Ingresar'}
          <I.ArrowRight size={14}/>
        </button>
        <div className="mt-6 pt-5 border-t border-white/10 font-mono text-[9px] text-gray-500 tracking-wider">
          // Hash SHA-256 verificado en el cliente · sesión local
        </div>
      </form>
    </div>
  );
}

/* ============== TEXT TAB (basic copy) ============== */
const EDITABLE = [
  { sec:'Hero',     path:'hero.kicker',      label:'Kicker' },
  { sec:'Hero',     path:'hero.title1',      label:'Título — línea 1' },
  { sec:'Hero',     path:'hero.title2',      label:'Título — línea 2 (acento)' },
  { sec:'Hero',     path:'hero.desc',        label:'Descripción', multiline:true },
  { sec:'Hero',     path:'hero.cta1',        label:'CTA primario' },
  { sec:'Hero',     path:'hero.cta2',        label:'CTA secundario' },
  { sec:'Features', path:'features.title',   label:'Título' },
  { sec:'Features', path:'features.sub',     label:'Subtítulo' },
  { sec:'About',    path:'about.kicker',     label:'Kicker' },
  { sec:'About',    path:'about.title',      label:'Título' },
  { sec:'About',    path:'about.p1',         label:'Texto principal', multiline:true },
  { sec:'About',    path:'about.history.0',  label:'Historia — párrafo 1', multiline:true },
  { sec:'About',    path:'about.history.1',  label:'Historia — párrafo 2', multiline:true },
  { sec:'About',    path:'about.history.2',  label:'Historia — párrafo 3', multiline:true },
  { sec:'About',    path:'about.history.3',  label:'Historia — párrafo 4', multiline:true },
  { sec:'About',    path:'about.quote',      label:'Frase destacada', multiline:true },
  { sec:'Catálogo', path:'portfolio.kicker', label:'Kicker' },
  { sec:'Catálogo', path:'portfolio.title',  label:'Título' },
  { sec:'Catálogo', path:'portfolio.sub',    label:'Subtítulo', multiline:true },
  { sec:'Aliados',  path:'partners.kicker',  label:'Kicker' },
  { sec:'Aliados',  path:'partners.title',   label:'Título' },
  { sec:'Aliados',  path:'partners.sub',     label:'Subtítulo', multiline:true },
  { sec:'Contacto', path:'contact.kicker',   label:'Kicker' },
  { sec:'Contacto', path:'contact.title',    label:'Título' },
  { sec:'Contacto', path:'contact.sub',      label:'Subtítulo', multiline:true },
];

function TextEditor({ field, lang }) {
  const adm = window.useAdmin();
  const base = getByPath(window.RHX._original.ui[lang], field.path) || '';
  const overridden = adm.overrides[`${lang}.${field.path}`];
  const current = overridden !== undefined ? overridden : base;
  const [val, setVal] = React.useState(current);
  React.useEffect(()=>{ setVal(current); }, [current]);
  const isOverride = overridden !== undefined;

  const commit = () => {
    if (val === base) adm.setOverride(lang, field.path, '');
    else adm.setOverride(lang, field.path, val);
  };
  const revert = () => { setVal(base); adm.setOverride(lang, field.path, ''); };

  const Input = field.multiline ? 'textarea' : 'input';
  return (
    <div className="space-y-1.5">
      <div className="flex items-center justify-between">
        <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">
          {field.label} <span className="text-gray-600">· {lang.toUpperCase()}</span>
        </label>
        {isOverride && <button onClick={revert} className="font-mono text-[9px] text-[#EF4444] hover:underline">revertir</button>}
      </div>
      <Input value={val} onChange={(e)=>setVal(e.target.value)} onBlur={commit}
        rows={field.multiline ? 3 : undefined}
        className={`w-full p-2.5 bg-[#0A0F1A] border text-[13px] text-white outline-none transition-colors resize-none ${
          isOverride ? 'border-[#14B8A6]/60' : 'border-white/10 focus:border-[#14B8A6]'
        }`}/>
    </div>
  );
}

function TextTab({ editLang, setEditLang }) {
  const adm = window.useAdmin();
  const I = window.RHX_ICONS;
  const [openSec, setOpenSec] = React.useState('Hero');
  const overrideCount = Object.keys(adm.overrides).length;
  const grouped = {};
  EDITABLE.forEach(f => { (grouped[f.sec] = grouped[f.sec] || []).push(f); });

  return (
    <React.Fragment>
      <div className="flex items-center gap-2">
        <span className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Idioma:</span>
        {['es','en'].map(L => (
          <button key={L} onClick={()=>setEditLang(L)}
            className={`px-3 py-1.5 font-mono text-[10px] uppercase tracking-widest border ${
              editLang === L ? 'bg-[#14B8A6] text-white border-[#14B8A6]' : 'border-white/10 text-gray-300 hover:border-[#14B8A6]/50'
            }`}>{L}</button>
        ))}
        {overrideCount > 0 && (
          <button onClick={adm.resetAllOverrides}
            className="ml-auto font-mono text-[10px] text-[#EF4444] hover:underline">// Restaurar todo</button>
        )}
      </div>
      {Object.keys(grouped).map(sec => {
        const open = openSec === sec;
        const fields = grouped[sec];
        const dirtyCount = fields.filter(f => adm.overrides[`${editLang}.${f.path}`] !== undefined).length;
        return (
          <div key={sec} className="border border-white/10">
            <button onClick={()=>setOpenSec(open ? '' : sec)}
              className="w-full flex items-center justify-between px-4 py-3 bg-[#0A0F1A] hover:bg-[#11182B] transition-colors">
              <span className="font-display text-[14px] tracking-tight">{sec}</span>
              <span className="flex items-center gap-2">
                {dirtyCount > 0 && <span className="font-mono text-[9px] bg-[#14B8A6]/15 text-[#14B8A6] px-1.5 py-0.5 rounded-sm">{dirtyCount} edit</span>}
                <I.ChevronDown size={14} className={`text-gray-500 transition-transform ${open?'rotate-180':''}`}/>
              </span>
            </button>
            {open && (
              <div className="p-4 space-y-4 bg-[#06090F]/60">
                {fields.map(f => <TextEditor key={`${editLang}.${f.path}`} field={f} lang={editLang}/>)}
              </div>
            )}
          </div>
        );
      })}
    </React.Fragment>
  );
}

/* ============== ADMIN PANEL ============== */
function AdminPanel() {
  const adm = window.useAdmin();
  const I = window.RHX_ICONS;
  const { lang } = window.useApp();
  const [tab, setTab] = React.useState('text');
  const [editLang, setEditLang] = React.useState(lang);
  if (!adm.authed || !adm.panelOpen) return null;

  const overrideCount = Object.keys(adm.overrides).length;
  const customPartnerCount = adm.customPartners.length;
  const hiddenPartnerCount = Object.values(adm.partnerVis).filter(v => v === false).length;
  const partnersBadge = customPartnerCount + hiddenPartnerCount + Object.keys(adm.partnerOverrides).length + Object.keys(adm.partnerLogos).length;
  const principlesBadge = Object.keys(adm.overrides).filter(k => k.includes('features.items.')).length;
  const statsBadge = Object.keys(adm.overrides).filter(k => k.includes('about.stats.')).length;
  const catalogBadge = adm.customCategories.length + adm.customServices.length
    + Object.keys(adm.hiddenServices).length + Object.keys(adm.serviceOverrides).length;

  const tabs = [
    { id:'text',       label:'Texto',     count: overrideCount - principlesBadge - statsBadge },
    { id:'principles', label:'Principios',count: principlesBadge },
    { id:'stats',      label:'Métricas',  count: statsBadge },
    { id:'catalog',    label:'Catálogo',  count: catalogBadge },
    { id:'partners',   label:'Aliados',   count: partnersBadge },
  ];

  return (
    <div className="fixed top-0 right-0 bottom-0 z-[90] w-full sm:w-[480px] bg-[#0B132B] border-l border-[#14B8A6]/30 text-white shadow-2xl flex flex-col">
      {/* Header */}
      <div className="px-5 pt-5 pb-4 border-b border-white/10 flex items-center justify-between">
        <div>
          <div className="font-mono text-[10px] tracking-[0.24em] text-[#14B8A6] uppercase flex items-center gap-2">
            <I.Shield size={11}/>// RHX · ADMIN
          </div>
          <div className="font-display font-medium text-lg mt-1">Editor de contenido</div>
        </div>
        <div className="flex items-center gap-1">
          <button onClick={adm.logout} title="Cerrar sesión"
            className="w-9 h-9 flex items-center justify-center text-gray-400 hover:text-[#EF4444] hover:bg-white/5 transition-colors">
            <I.LogOut size={15}/>
          </button>
          <button onClick={()=>adm.setPanelOpen(false)} title="Ocultar panel"
            className="w-9 h-9 flex items-center justify-center text-gray-400 hover:text-white hover:bg-white/5 transition-colors">
            <I.X size={16}/>
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div className="px-3 pt-2 pb-0 flex items-center gap-0.5 border-b border-white/10 overflow-x-auto">
        {tabs.map(tb => (
          <button key={tb.id} onClick={()=>setTab(tb.id)}
            className={`relative px-2.5 pb-3 pt-2 text-[11px] font-medium tracking-wide whitespace-nowrap ${
              tab===tb.id ? 'text-[#14B8A6]' : 'text-gray-400 hover:text-white'
            }`}>
            {tb.label}
            {tb.count > 0 && <span className="ml-1 font-mono text-[8px] bg-[#14B8A6]/15 text-[#14B8A6] px-1 py-0.5 rounded-sm">{tb.count}</span>}
            {tab===tb.id && <span className="absolute left-0 right-0 -bottom-px h-0.5 bg-[#14B8A6]"></span>}
          </button>
        ))}
      </div>

      {/* Body */}
      <div className="flex-1 overflow-y-auto px-5 py-5 space-y-4">
        {tab === 'text'       && <TextTab editLang={editLang} setEditLang={setEditLang}/>}
        {tab === 'principles' && <window.FeaturesTab editLang={editLang} setEditLang={setEditLang}/>}
        {tab === 'stats'      && <window.StatsTab editLang={editLang} setEditLang={setEditLang}/>}
        {tab === 'catalog'    && <window.CatalogTab editLang={editLang} setEditLang={setEditLang}/>}
        {tab === 'partners'   && <window.PartnersTab editLang={editLang} setEditLang={setEditLang}/>}
      </div>

      {/* Footer */}
      <div className="px-5 py-3 border-t border-white/10 font-mono text-[9px] text-gray-500 tracking-wider flex items-center justify-between">
        <span>// guardado en localStorage</span>
        <span className="text-[#14B8A6]">v.2026.05</span>
      </div>
    </div>
  );
}

Object.assign(window, { AdminProvider, AdmButton, LoginModal, AdminPanel });
