/* RINAU HEX — Admin: Catálogo tab (categorías + servicios) */

function rhxSlug(s) {
  return (s || '').toString().toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'')
    .replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'').slice(0,24) || ('cat-' + Date.now());
}

/* ===== Bilingual list editor (details) ===== */
function ListEditor({ label, items, onCommit }) {
  const text = (items || []).join('\n');
  return (
    <div className="space-y-1.5">
      <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">{label}</label>
      <window.EditInput value={text} multiline rows={5}
        placeholder={'Una característica por línea…'}
        onCommit={(v)=>onCommit(v.split('\n').map(x=>x.trim()).filter(Boolean))}/>
      <div className="font-mono text-[9px] text-gray-600">// una línea = un punto · {(items||[]).length} puntos</div>
    </div>
  );
}

/* ===== Service editor form ===== */
function ServiceForm({ svc, cats, subcats, onPatch }) {
  const catOptions = cats.filter(c => c.id !== 'all');
  const subOptions = subcats[svc.category] || [];
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Categoría</label>
          <select value={svc.category} onChange={(e)=>onPatch({ category: e.target.value, subcategory: '' })}
            className="w-full p-2.5 bg-[#0A0F1A] border border-white/10 text-[13px] text-white outline-none focus:border-[#14B8A6]">
            {catOptions.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
          </select>
        </div>
        <window.IconPicker label="Ícono" value={svc.icon} onChange={(name)=>onPatch({ icon: name })}/>
      </div>

      <div className="space-y-1.5">
        <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Subcategoría</label>
        <select value={svc.subcategory || ''} onChange={(e)=>onPatch({ subcategory: e.target.value })}
          className="w-full p-2.5 bg-[#0A0F1A] border border-white/10 text-[13px] text-white outline-none focus:border-[#14B8A6]">
          <option value="">— Sin subcategoría —</option>
          {subOptions.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
        </select>
      </div>

      <div className="space-y-1.5">
        <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Imagen (URL)</label>
        <window.EditInput value={svc.image} placeholder="https://…" onCommit={(v)=>onPatch({ image: v })}/>
      </div>

      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Título · ES</label>
          <window.EditInput value={svc.title.es} onCommit={(v)=>onPatch({ title: { es: v } })}/>
        </div>
        <div className="space-y-1.5">
          <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Título · EN</label>
          <window.EditInput value={svc.title.en} onCommit={(v)=>onPatch({ title: { en: v } })}/>
        </div>
      </div>

      <div className="space-y-1.5">
        <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Descripción · ES</label>
        <window.EditInput value={svc.description.es} multiline rows={2} onCommit={(v)=>onPatch({ description: { es: v } })}/>
      </div>
      <div className="space-y-1.5">
        <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Descripción · EN</label>
        <window.EditInput value={svc.description.en} multiline rows={2} onCommit={(v)=>onPatch({ description: { en: v } })}/>
      </div>

      <div className="pt-2 border-t border-white/5 font-mono text-[9px] text-[#14B8A6] uppercase tracking-widest">// Interior del servicio · características</div>
      <ListEditor label="Características · ES" items={svc.details.es} onCommit={(arr)=>onPatch({ details: { es: arr } })}/>
      <ListEditor label="Características · EN" items={svc.details.en} onCommit={(arr)=>onPatch({ details: { en: arr } })}/>
    </div>
  );
}

/* ============== CATALOG TAB ============== */
function CatalogTab({ editLang, setEditLang }) {
  const adm = window.useAdmin();
  const I = window.RHX_ICONS;
  const [view, setView] = React.useState('services'); // 'services' | 'cats'
  const cats = window.RHX.ui[editLang].portfolio.cats;
  const subcats = window.RHX.ui[editLang].portfolio.subcats;
  const services = window.RHX.services;
  const baseServiceIds = new Set(window.RHX._original.services.map(s=>s.id));
  const customCatIds = new Set(adm.customCategories.map(c=>c.id));
  const builtInCats = window.RHX._original.ui[editLang].portfolio.cats; // all, academic, enterprise, health

  /* new category draft */
  const [newCat, setNewCat] = React.useState({ es:'', en:'', icon:'Layers' });
  const addCat = () => {
    const label = (newCat.es || newCat.en).trim();
    if (!label) return;
    const id = rhxSlug(newCat.es || newCat.en);
    if (cats.find(c=>c.id===id)) { return; }
    adm.addCustomCategory({ id, label:{ es:newCat.es||label, en:newCat.en||newCat.es||label }, icon:newCat.icon });
    setNewCat({ es:'', en:'', icon:'Layers' });
  };

  /* new service */
  const addService = () => {
    const firstCat = cats.find(c=>c.id!=='all')?.id || 'enterprise';
    adm.addCustomService({
      id: 'svc-' + Date.now(),
      category: firstCat, icon:'Layers', image:'',
      title:{ es:'Nuevo servicio', en:'New service' },
      description:{ es:'', en:'' },
      details:{ es:[], en:[] },
    });
  };

  return (
    <React.Fragment>
      <LangToggle editLang={editLang} setEditLang={setEditLang}/>

      {/* sub-switch */}
      <div className="flex items-center gap-0.5 bg-[#0A0F1A] border border-white/10 p-0.5">
        {[['services','Servicios'],['cats','Categorías']].map(([id,lbl])=>(
          <button key={id} onClick={()=>setView(id)}
            className={`flex-1 py-2 text-[11px] font-medium tracking-wide transition-colors ${
              view===id ? 'bg-[#14B8A6] text-white' : 'text-gray-400 hover:text-white'
            }`}>{lbl}</button>
        ))}
      </div>

      {view === 'cats' && (
        <React.Fragment>
          <p className="font-mono text-[10px] text-gray-500 tracking-wide leading-relaxed">// Filtros del catálogo. Puedes editar las existentes y añadir nuevas.</p>
          {cats.map((c) => {
            const isCustom = customCatIds.has(c.id);
            const isAll = c.id === 'all';
            const idx = builtInCats.findIndex(b=>b.id===c.id);
            const count = services.filter(s=>s.category===c.id).length;
            return (
              <Collapsible key={c.id}
                title={<React.Fragment>{c.label} <span className="font-mono text-[9px] text-gray-600">/{c.id}</span></React.Fragment>}
                badge={<React.Fragment>{isCustom && <MiniBadge tone="gray">nueva</MiniBadge>}{!isAll && <MiniBadge tone="gray">{count}</MiniBadge>}</React.Fragment>}>
                <div className="space-y-3">
                  {!isAll && (
                    <IconPicker label="Ícono" value={c.icon}
                      onChange={(name)=> isCustom
                        ? adm.updateCustomCategory(c.id, { icon: name })
                        : (adm.setOverride('es',`portfolio.cats.${idx}.icon`, name), adm.setOverride('en',`portfolio.cats.${idx}.icon`, name)) }/>
                  )}
                  <div className="space-y-1.5">
                    <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Etiqueta · {editLang.toUpperCase()}</label>
                    <EditInput value={c.label}
                      onCommit={(v)=> isCustom
                        ? adm.updateCustomCategory(c.id, { label: { [editLang]: v } })
                        : adm.setOverride(editLang, `portfolio.cats.${idx}.label`, v===builtInCats[idx].label?'':v) }/>
                  </div>
                  {isCustom && (
                    <button onClick={()=>adm.removeCustomCategory(c.id)}
                      className="inline-flex items-center gap-2 font-mono text-[10px] text-[#EF4444] hover:underline">
                      <I.Trash size={12}/> Eliminar categoría
                    </button>
                  )}
                </div>
              </Collapsible>
            );
          })}

          {/* Add category */}
          <div className="border border-dashed border-[#14B8A6]/40 p-4 space-y-3 bg-[#06090F]/60">
            <div className="font-mono text-[10px] text-[#14B8A6] uppercase tracking-widest flex items-center gap-2"><I.Plus size={12}/> Nueva categoría</div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Etiqueta · ES</label>
                <input value={newCat.es} onChange={(e)=>setNewCat(n=>({...n,es:e.target.value}))}
                  className="w-full p-2.5 bg-[#0A0F1A] border border-white/10 text-[13px] text-white outline-none focus:border-[#14B8A6]"/>
              </div>
              <div className="space-y-1.5">
                <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Etiqueta · EN</label>
                <input value={newCat.en} onChange={(e)=>setNewCat(n=>({...n,en:e.target.value}))}
                  className="w-full p-2.5 bg-[#0A0F1A] border border-white/10 text-[13px] text-white outline-none focus:border-[#14B8A6]"/>
              </div>
            </div>
            <IconPicker label="Ícono" value={newCat.icon} onChange={(name)=>setNewCat(n=>({...n,icon:name}))}/>
            <button onClick={addCat} disabled={!(newCat.es||newCat.en).trim()}
              className="w-full inline-flex items-center justify-center gap-2 bg-[#14B8A6] hover:bg-[#0D9488] disabled:opacity-40 text-white py-2.5 font-medium text-[11px] uppercase tracking-[0.16em] transition-colors">
              <I.Plus size={13}/> Añadir categoría
            </button>
          </div>
        </React.Fragment>
      )}

      {view === 'services' && (
        <React.Fragment>
          <div className="flex items-center justify-between">
            <p className="font-mono text-[10px] text-gray-500 tracking-wide">// {services.length} servicios</p>
            <button onClick={addService}
              className="inline-flex items-center gap-1.5 bg-[#14B8A6] hover:bg-[#0D9488] text-white px-3 py-1.5 font-medium text-[10px] uppercase tracking-[0.14em] transition-colors">
              <I.Plus size={12}/> Nuevo servicio
            </button>
          </div>

          {services.map((s) => {
            const isCustom = !baseServiceIds.has(s.id);
            const hidden = adm.hiddenServices[s.id];
            const edited = adm.serviceOverrides[s.id] !== undefined;
            const Icon = I[s.icon] || I.Layers;
            return (
              <Collapsible key={s.id}
                title={<React.Fragment>
                  <span className={`w-7 h-7 border flex items-center justify-center shrink-0 ${hidden?'border-white/10 text-gray-600':'border-[#14B8A6]/30 text-[#14B8A6]'}`}><Icon size={14}/></span>
                  <span className={hidden?'line-through text-gray-500':''}>{s.title[editLang]}</span>
                </React.Fragment>}
                badge={<React.Fragment>
                  {isCustom && <MiniBadge tone="gray">nuevo</MiniBadge>}
                  {edited && !isCustom && <MiniBadge>edit</MiniBadge>}
                  {hidden && <MiniBadge tone="red">oculto</MiniBadge>}
                </React.Fragment>}>
                <div className="flex items-center justify-between pb-3 border-b border-white/5">
                  <span className="font-mono text-[10px] text-gray-500">// {s.id}</span>
                  <div className="flex items-center gap-3">
                    {!isCustom && (
                      <button onClick={()=>adm.setServiceHidden(s.id, !hidden)}
                        className="inline-flex items-center gap-1.5 font-mono text-[10px] text-gray-400 hover:text-[#14B8A6]">
                        {hidden ? <React.Fragment><I.Eye size={12}/> Mostrar</React.Fragment> : <React.Fragment><I.EyeOff size={12}/> Ocultar</React.Fragment>}
                      </button>
                    )}
                    {!isCustom && edited && (
                      <button onClick={()=>adm.resetServiceOverride(s.id)}
                        className="font-mono text-[10px] text-[#EF4444] hover:underline">revertir</button>
                    )}
                    {isCustom && (
                      <button onClick={()=>adm.removeCustomService(s.id)}
                        className="inline-flex items-center gap-1.5 font-mono text-[10px] text-[#EF4444] hover:underline">
                        <I.Trash size={12}/> Eliminar
                      </button>
                    )}
                  </div>
                </div>
                <ServiceForm svc={s} cats={cats} subcats={subcats}
                  onPatch={(patch)=> isCustom ? adm.updateCustomService(s.id, patch) : adm.setServiceOverride(s.id, patch)}/>
              </Collapsible>
            );
          })}
        </React.Fragment>
      )}
    </React.Fragment>
  );
}

Object.assign(window, { CatalogTab, ServiceForm, ListEditor, rhxSlug });
