/* RINAU HEX — Admin content tabs: shared helpers + Features (Principios) + Stats (Métricas) */

/* ===== Curated icon choices for pickers ===== */
const RHX_ICON_CHOICES = ['Cpu','Brain','Server','ShieldCheck','Database','Layers','Layers3',
  'GraduationCap','Briefcase','HeartPulse','Microscope','Landmark','Building','Code','Award',
  'Target','Activity','BookOpen','CheckSquare','Laptop','Monitor','Files','FolderKanban',
  'Calendar','CalendarDays','TrendingUp','User','Users','HardDrive','FlaskConical','Globe',
  'Mail','Phone','MapPin','Send'];

/* ===== dataURL byte size ===== */
function rhxDataUrlBytes(dataUrl) {
  if (!dataUrl || dataUrl.indexOf(',') < 0) return 0;
  const b64 = dataUrl.slice(dataUrl.indexOf(',') + 1);
  const pad = b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0;
  return Math.floor(b64.length * 3 / 4) - pad;
}
function rhxKB(bytes) { return (bytes / 1024).toFixed(1) + ' KB'; }

/* ===== Lang toggle (shared) ===== */
function LangToggle({ editLang, setEditLang, extra }) {
  return (
    <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>
      ))}
      {extra}
    </div>
  );
}

/* ===== Field label ===== */
function FieldLabel({ children, onRevert }) {
  return (
    <div className="flex items-center justify-between">
      <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">{children}</label>
      {onRevert && <button onClick={onRevert} className="font-mono text-[9px] text-[#EF4444] hover:underline">revertir</button>}
    </div>
  );
}

/* ===== Controlled-on-blur input ===== */
function EditInput({ value, onCommit, multiline, rows, placeholder, dirty }) {
  const [v, setV] = React.useState(value == null ? '' : value);
  React.useEffect(()=>{ setV(value == null ? '' : value); }, [value]);
  const El = multiline ? 'textarea' : 'input';
  return (
    <El value={v} placeholder={placeholder} rows={multiline ? (rows||3) : undefined}
      onChange={(e)=>setV(e.target.value)}
      onBlur={()=>{ if (v !== (value == null ? '' : value)) onCommit(v); }}
      className={`w-full p-2.5 bg-[#0A0F1A] border text-[13px] text-white outline-none transition-colors resize-none ${
        dirty ? 'border-[#14B8A6]/60' : 'border-white/10 focus:border-[#14B8A6]'
      }`}/>
  );
}

/* ===== Icon picker (expandable grid) ===== */
function IconPicker({ value, onChange, label }) {
  const I = window.RHX_ICONS;
  const [open, setOpen] = React.useState(false);
  const Cur = I[value] || I.Layers;
  return (
    <div className="space-y-1.5">
      {label && <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">{label}</label>}
      <button onClick={()=>setOpen(o=>!o)} type="button"
        className="w-full flex items-center justify-between p-2.5 bg-[#0A0F1A] border border-white/10 hover:border-[#14B8A6]/50 transition-colors">
        <span className="flex items-center gap-2.5 text-[13px] text-white">
          <span className="w-8 h-8 border border-[#14B8A6]/30 text-[#14B8A6] flex items-center justify-center"><Cur size={16}/></span>
          <span className="font-mono text-[11px] text-gray-300">{value || 'Layers'}</span>
        </span>
        <I.ChevronDown size={13} className={`text-gray-500 transition-transform ${open?'rotate-180':''}`}/>
      </button>
      {open && (
        <div className="grid grid-cols-7 gap-1 p-2 bg-[#06090F] border border-white/10 max-h-[180px] overflow-y-auto">
          {RHX_ICON_CHOICES.map(name => {
            const Ic = I[name] || I.Layers;
            const on = name === value;
            return (
              <button key={name} type="button" title={name}
                onClick={()=>{ onChange(name); setOpen(false); }}
                className={`aspect-square flex items-center justify-center border transition-colors ${
                  on ? 'bg-[#14B8A6] border-[#14B8A6] text-white' : 'border-white/10 text-gray-300 hover:border-[#14B8A6]/50 hover:text-[#14B8A6]'
                }`}>
                <Ic size={15}/>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* ===== Collapsible block ===== */
function Collapsible({ title, badge, defaultOpen, children, right }) {
  const [open, setOpen] = React.useState(!!defaultOpen);
  const I = window.RHX_ICONS;
  return (
    <div className="border border-white/10">
      <button onClick={()=>setOpen(o=>!o)}
        className="w-full flex items-center justify-between px-4 py-3 bg-[#0A0F1A] hover:bg-[#11182B] transition-colors text-left">
        <span className="font-display text-[14px] tracking-tight text-white flex items-center gap-2.5">{title}</span>
        <span className="flex items-center gap-2">
          {badge}
          {right}
          <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">{children}</div>}
    </div>
  );
}

/* ===== Small badge ===== */
function MiniBadge({ children, tone='teal' }) {
  const tones = {
    teal:'bg-[#14B8A6]/15 text-[#14B8A6]',
    gray:'bg-white/5 text-gray-400',
    red:'bg-[#EF4444]/15 text-[#EF4444]',
  };
  return <span className={`font-mono text-[9px] px-1.5 py-0.5 rounded-sm ${tones[tone]}`}>{children}</span>;
}

/* ============== FEATURES TAB (Por qué RINAU HEX — 4 íconos) ============== */
function FeaturesTab({ editLang, setEditLang }) {
  const adm = window.useAdmin();
  const base = window.RHX._original.ui[editLang].features;
  const cur = window.RHX.ui[editLang].features;

  const setTxt = (i, field, val) => {
    const path = `features.items.${i}.${field}`;
    const baseVal = window.RHX._original.ui[editLang].features.items[i][field];
    adm.setOverride(editLang, path, val === baseVal ? '' : val);
  };
  const setIcon = (i, name) => {
    const path = `features.items.${i}.i`;
    const baseEs = window.RHX._original.ui.es.features.items[i].i;
    const baseEn = window.RHX._original.ui.en.features.items[i].i;
    adm.setOverride('es', path, name === baseEs ? '' : name);
    adm.setOverride('en', path, name === baseEn ? '' : name);
  };
  const isDirty = (i, field) => adm.overrides[`${editLang}.features.items.${i}.${field}`] !== undefined;

  return (
    <React.Fragment>
      <LangToggle editLang={editLang} setEditLang={setEditLang}/>
      <p className="font-mono text-[10px] text-gray-500 tracking-wide leading-relaxed">// Sección "Por qué RINAU HEX" — cuatro principios. El ícono es común a ambos idiomas.</p>

      {/* Section heading copy */}
      <Collapsible title="Encabezado de la sección" defaultOpen={false}>
        <div className="space-y-1.5">
          <FieldLabel onRevert={adm.overrides[`${editLang}.features.title`]!==undefined ? ()=>adm.setOverride(editLang,'features.title','') : null}>Título · {editLang.toUpperCase()}</FieldLabel>
          <EditInput value={cur.title} dirty={adm.overrides[`${editLang}.features.title`]!==undefined}
            onCommit={(v)=>adm.setOverride(editLang,'features.title', v===base.title?'':v)}/>
        </div>
        <div className="space-y-1.5">
          <FieldLabel onRevert={adm.overrides[`${editLang}.features.sub`]!==undefined ? ()=>adm.setOverride(editLang,'features.sub','') : null}>Subtítulo · {editLang.toUpperCase()}</FieldLabel>
          <EditInput value={cur.sub} dirty={adm.overrides[`${editLang}.features.sub`]!==undefined}
            onCommit={(v)=>adm.setOverride(editLang,'features.sub', v===base.sub?'':v)}/>
        </div>
      </Collapsible>

      {cur.items.map((it, i) => (
        <Collapsible key={i} defaultOpen={i===0}
          title={<React.Fragment><span className="font-mono text-[10px] text-[#14B8A6]">0{i+1}</span> {it.t}</React.Fragment>}
          badge={(isDirty(i,'t')||isDirty(i,'d')||adm.overrides[`es.features.items.${i}.i`]!==undefined) ? <MiniBadge>edit</MiniBadge> : null}>
          <IconPicker label="Ícono" value={it.i} onChange={(name)=>setIcon(i, name)}/>
          <div className="space-y-1.5">
            <FieldLabel onRevert={isDirty(i,'t') ? ()=>setTxt(i,'t','') : null}>Título · {editLang.toUpperCase()}</FieldLabel>
            <EditInput value={it.t} dirty={isDirty(i,'t')} onCommit={(v)=>setTxt(i,'t',v)}/>
          </div>
          <div className="space-y-1.5">
            <FieldLabel onRevert={isDirty(i,'d') ? ()=>setTxt(i,'d','') : null}>Descripción · {editLang.toUpperCase()}</FieldLabel>
            <EditInput value={it.d} multiline rows={3} dirty={isDirty(i,'d')} onCommit={(v)=>setTxt(i,'d',v)}/>
          </div>
        </Collapsible>
      ))}
    </React.Fragment>
  );
}

/* ============== STATS TAB (06+ Años / 21 Líneas / 100% ...) ============== */
function StatsTab({ editLang, setEditLang }) {
  const adm = window.useAdmin();
  const base = window.RHX._original.ui[editLang].about;
  const cur = window.RHX.ui[editLang].about;

  const setNum = (i, val) => {
    const path = `about.stats.${i}.n`;
    const bEs = window.RHX._original.ui.es.about.stats[i].n;
    const bEn = window.RHX._original.ui.en.about.stats[i].n;
    adm.setOverride('es', path, val === bEs ? '' : val);
    adm.setOverride('en', path, val === bEn ? '' : val);
  };
  const setLabel = (i, val) => {
    const path = `about.stats.${i}.l`;
    const b = window.RHX._original.ui[editLang].about.stats[i].l;
    adm.setOverride(editLang, path, val === b ? '' : val);
  };
  const dirtyN = (i) => adm.overrides[`es.about.stats.${i}.n`] !== undefined;
  const dirtyL = (i) => adm.overrides[`${editLang}.about.stats.${i}.l`] !== undefined;

  return (
    <React.Fragment>
      <LangToggle editLang={editLang} setEditLang={setEditLang}/>
      <p className="font-mono text-[10px] text-gray-500 tracking-wide leading-relaxed">// Cuadros de métricas en "Nosotros". El número es común a ambos idiomas; la etiqueta es por idioma.</p>

      {cur.stats.map((s, i) => (
        <div key={i} className="border border-white/10 p-4 space-y-3 bg-[#06090F]/60">
          <div className="flex items-center justify-between">
            <span className="font-mono text-[10px] text-gray-500 uppercase tracking-widest">// Cuadro 0{i+1}</span>
            {(dirtyN(i)||dirtyL(i)) && <MiniBadge>edit</MiniBadge>}
          </div>
          <div className="grid grid-cols-[100px_1fr] gap-3 items-start">
            <div className="space-y-1.5">
              <FieldLabel onRevert={dirtyN(i) ? ()=>setNum(i,'') : null}>Número</FieldLabel>
              <EditInput value={s.n} dirty={dirtyN(i)} onCommit={(v)=>setNum(i,v)}/>
            </div>
            <div className="space-y-1.5">
              <FieldLabel onRevert={dirtyL(i) ? ()=>setLabel(i,'') : null}>Etiqueta · {editLang.toUpperCase()}</FieldLabel>
              <EditInput value={s.l} dirty={dirtyL(i)} onCommit={(v)=>setLabel(i,v)}/>
            </div>
          </div>
          <div className="flex items-baseline gap-3 pt-1 border-t border-white/5">
            <span className="font-display font-medium text-2xl text-[#14B8A6]">{s.n}</span>
            <span className="font-mono text-[10px] text-gray-500 uppercase tracking-widest">{s.l}</span>
          </div>
        </div>
      ))}
    </React.Fragment>
  );
}

Object.assign(window, {
  RHX_ICON_CHOICES, rhxDataUrlBytes, rhxKB,
  LangToggle, FieldLabel, EditInput, IconPicker, Collapsible, MiniBadge,
  FeaturesTab, StatsTab,
});
