/* RINAU HEX — Admin: Aliados tab (partners) + logo uploader (256×256 PNG ≤100KB) + presets */

const RHX_LOGO_MAX_BYTES = 100 * 1024; // 100 KB
const RHX_LOGO_SIZE = 256;

/* ===== Process an uploaded image into a 256×256 PNG dataURL ===== */
function rhxProcessLogo(file) {
  return new Promise((resolve) => {
    if (!file) { resolve({ error: 'Sin archivo.' }); return; }
    if (!/^image\//.test(file.type)) { resolve({ error: 'El archivo debe ser una imagen.' }); return; }
    const url = URL.createObjectURL(file);
    const img = new Image();
    img.onload = () => {
      URL.revokeObjectURL(url);
      const c = document.createElement('canvas');
      c.width = RHX_LOGO_SIZE; c.height = RHX_LOGO_SIZE;
      const ctx = c.getContext('2d');
      ctx.imageSmoothingQuality = 'high';
      // contain
      const scale = Math.min(RHX_LOGO_SIZE / img.width, RHX_LOGO_SIZE / img.height);
      const w = Math.round(img.width * scale), h = Math.round(img.height * scale);
      ctx.drawImage(img, (RHX_LOGO_SIZE - w) / 2, (RHX_LOGO_SIZE - h) / 2, w, h);
      const dataUrl = c.toDataURL('image/png');
      const bytes = window.rhxDataUrlBytes(dataUrl);
      if (bytes > RHX_LOGO_MAX_BYTES) {
        resolve({ error: `El PNG pesa ${window.rhxKB(bytes)} (máx 100 KB). Usa un logo más simple o con fondo transparente.` });
      } else {
        resolve({ dataUrl, bytes });
      }
    };
    img.onerror = () => { URL.revokeObjectURL(url); resolve({ error: 'No se pudo leer la imagen.' }); };
    img.src = url;
  });
}

/* ===== Hexagon path on a canvas ctx (pointy-top) ===== */
function rhxHexPath(ctx, cx, cy, r) {
  ctx.beginPath();
  for (let i = 0; i < 6; i++) {
    const a = Math.PI / 180 * (60 * i - 90);
    const x = cx + r * Math.cos(a), y = cy + r * Math.sin(a);
    i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
  }
  ctx.closePath();
}
function rhxDrawMark(ctx, text, color) {
  const t = (text || '').toString().slice(0, 3).toUpperCase() || 'RH';
  const size = t.length >= 3 ? 86 : 108;
  ctx.fillStyle = color;
  ctx.font = `700 ${size}px "Space Grotesk", "Inter", sans-serif`;
  ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.fillText(t, RHX_LOGO_SIZE / 2, RHX_LOGO_SIZE / 2 + 4);
}

/* ===== Build a preset logo (returns dataURL) ===== */
function rhxBuildPreset(kind, mark, variant) {
  const c = document.createElement('canvas');
  c.width = RHX_LOGO_SIZE; c.height = RHX_LOGO_SIZE;
  const ctx = c.getContext('2d');
  const ink = variant === 'dark' ? '#F2F5FA' : '#0B132B';
  const teal = '#14B8A6';
  const cx = 128, cy = 128;
  if (kind === 'hex') {
    rhxHexPath(ctx, cx, cy, 110); ctx.strokeStyle = teal; ctx.lineWidth = 9; ctx.stroke();
    rhxDrawMark(ctx, mark, ink);
  } else if (kind === 'hexFill') {
    rhxHexPath(ctx, cx, cy, 112); ctx.fillStyle = teal; ctx.fill();
    rhxDrawMark(ctx, mark, '#FFFFFF');
  } else if (kind === 'disc') {
    ctx.beginPath(); ctx.arc(cx, cy, 112, 0, Math.PI * 2); ctx.fillStyle = '#0B132B'; ctx.fill();
    ctx.lineWidth = 6; ctx.strokeStyle = teal; ctx.stroke();
    rhxDrawMark(ctx, mark, teal);
  } else { /* plain monogram */
    rhxDrawMark(ctx, mark, variant === 'dark' ? '#F2F5FA' : teal);
  }
  return c.toDataURL('image/png');
}
const RHX_PRESETS = [
  { id:'hex',     label:'Hexágono' },
  { id:'hexFill', label:'Hex sólido' },
  { id:'disc',    label:'Disco' },
  { id:'mono',    label:'Monograma' },
];

/* ===== Single logo slot (light or dark) ===== */
function LogoSlot({ side, dataUrl, mark, onSet }) {
  const I = window.RHX_ICONS;
  const ref = React.useRef(null);
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const tileBg = side === 'light' ? '#FFFFFF' : '#0B132B';
  const onFile = async (e) => {
    const f = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!f) return;
    setBusy(true); setErr('');
    const r = await rhxProcessLogo(f);
    setBusy(false);
    if (r.error) { setErr(r.error); return; }
    onSet(r.dataUrl);
  };
  const bytes = dataUrl ? window.rhxDataUrlBytes(dataUrl) : 0;
  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <span className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">{side === 'light' ? 'Modo claro' : 'Modo oscuro'}</span>
        {dataUrl && <span className="font-mono text-[9px] text-[#14B8A6]">{window.rhxKB(bytes)}</span>}
      </div>
      <div className="w-full aspect-square border border-white/10 flex items-center justify-center overflow-hidden" style={{ background: tileBg }}>
        {dataUrl
          ? <img src={dataUrl} alt={side} className="w-full h-full object-contain p-3"/>
          : <span className="font-mono text-[9px] text-gray-500">vacío</span>}
      </div>
      <div className="flex items-center gap-1.5">
        <button onClick={()=>ref.current && ref.current.click()} disabled={busy}
          className="flex-1 inline-flex items-center justify-center gap-1.5 bg-[#14B8A6]/15 hover:bg-[#14B8A6]/25 text-[#14B8A6] py-2 font-mono text-[10px] uppercase tracking-widest transition-colors">
          {busy ? '…' : <React.Fragment><I.Plus size={11}/> PNG</React.Fragment>}
        </button>
        {dataUrl && (
          <button onClick={()=>onSet(null)} title="Quitar"
            className="px-2.5 py-2 text-[#EF4444] hover:bg-[#EF4444]/10 transition-colors"><I.Trash size={13}/></button>
        )}
        <input ref={ref} type="file" accept="image/png,image/*" onChange={onFile} className="hidden"/>
      </div>
      {err && <div className="font-mono text-[9px] text-[#EF4444] leading-snug">// {err}</div>}
    </div>
  );
}

/* ===== Full logo uploader: two slots + presets ===== */
function LogoUploader({ partnerId, mark, logo, setLogo }) {
  const hasNone = !logo || (!logo.light && !logo.dark);
  return (
    <div className="space-y-3 border border-white/10 p-3 bg-[#06090F]/60">
      <div className="font-mono text-[10px] text-[#14B8A6] uppercase tracking-widest">// Logo · 256×256 PNG · máx 100 KB</div>
      <div className="grid grid-cols-2 gap-3">
        <LogoSlot side="light" mark={mark} dataUrl={logo && logo.light} onSet={(d)=>setLogo('light', d)}/>
        <LogoSlot side="dark"  mark={mark} dataUrl={logo && logo.dark}  onSet={(d)=>setLogo('dark', d)}/>
      </div>
      {/* Presets */}
      <div className="space-y-2 pt-1">
        <div className="font-mono text-[9px] text-gray-500 uppercase tracking-widest">
          {hasNone ? 'Sin logo — elige una opción prediseñada:' : 'O reemplaza con un prediseñado:'}
        </div>
        <div className="grid grid-cols-4 gap-2">
          {RHX_PRESETS.map(ps => (
            <button key={ps.id} title={ps.label}
              onClick={()=>{
                setLogo('light', rhxBuildPreset(ps.id, mark, 'light'));
                setLogo('dark',  rhxBuildPreset(ps.id, mark, 'dark'));
              }}
              className="group space-y-1">
              <span className="block aspect-square border border-white/10 group-hover:border-[#14B8A6] bg-[#0B132B] overflow-hidden transition-colors">
                <img src={rhxBuildPreset(ps.id, mark, 'dark')} alt={ps.label} className="w-full h-full object-contain p-1.5"/>
              </span>
              <span className="block font-mono text-[8px] text-gray-500 text-center tracking-wider">{ps.label}</span>
            </button>
          ))}
        </div>
        <p className="font-mono text-[8px] text-gray-600 leading-relaxed">// El prediseñado usa las letras «{(mark||'RH').toUpperCase()}». Edítalas en el campo «Marca».</p>
      </div>
    </div>
  );
}

/* ===== Partner editor fields ===== */
function PartnerForm({ p, editLang, onPatch }) {
  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">Etiqueta (badge)</label>
          <window.EditInput value={p.badge} onCommit={(v)=>onPatch({ badge: v })}/>
        </div>
        <div className="space-y-1.5">
          <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Marca (1–3 letras)</label>
          <window.EditInput value={p.mark} onCommit={(v)=>onPatch({ mark: v.slice(0,3).toUpperCase() })}/>
        </div>
      </div>
      <window.IconPicker label="Ícono (si no hay logo)" value={p.icon} onChange={(name)=>onPatch({ icon: name })}/>
      <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">Nombre · ES</label>
          <window.EditInput value={p.name.es} onCommit={(v)=>onPatch({ name: { es: v } })}/>
        </div>
        <div className="space-y-1.5">
          <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Nombre · EN</label>
          <window.EditInput value={p.name.en} onCommit={(v)=>onPatch({ name: { en: v } })}/>
        </div>
      </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">Tipo · ES</label>
          <window.EditInput value={p.type.es} onCommit={(v)=>onPatch({ type: { es: v } })}/>
        </div>
        <div className="space-y-1.5">
          <label className="font-mono text-[10px] text-gray-400 uppercase tracking-widest">Tipo · EN</label>
          <window.EditInput value={p.type.en} onCommit={(v)=>onPatch({ type: { 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={p.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={p.description.en} multiline rows={2} onCommit={(v)=>onPatch({ description: { en: v } })}/>
      </div>
      <window.ListEditor label="Líneas de trabajo · ES" items={p.features.es} onCommit={(arr)=>onPatch({ features: { es: arr } })}/>
      <window.ListEditor label="Líneas de trabajo · EN" items={p.features.en} onCommit={(arr)=>onPatch({ features: { en: arr } })}/>
    </div>
  );
}

/* ============== PARTNERS TAB ============== */
function PartnersTab({ editLang, setEditLang }) {
  const adm = window.useAdmin();
  const I = window.RHX_ICONS;
  const originals = window.RHX._original.partnersData;
  const origIds = new Set(originals.map(p=>p.id));

  const list = [
    ...originals.map(p => ({ p: window.RHX_deepMerge(p, adm.partnerOverrides[p.id] || {}), isCustom: false })),
    ...adm.customPartners.map(p => ({ p, isCustom: true })),
  ];

  const addPartner = () => {
    adm.addCustomPartner({
      id: 'partner-' + Date.now(), badge: 'NUEVO', icon: 'Building', mark: 'NX',
      name: { es:'Nuevo aliado', en:'New partner' },
      type: { es:'Aliado institucional', en:'Institutional partner' },
      description: { es:'', en:'' },
      features: { es:[], en:[] },
    });
  };

  return (
    <React.Fragment>
      <LangToggle editLang={editLang} setEditLang={setEditLang}/>
      <p className="font-mono text-[10px] text-gray-500 tracking-wide leading-relaxed">// Cada logo aparece arriba (tarjeta del aliado) y abajo (grilla de clientes). Carga PNG 256×256 para claro y oscuro, o elige un prediseñado.</p>

      {list.map(({ p, isCustom }) => {
        const hidden = adm.partnerVis[p.id] === false;
        const edited = adm.partnerOverrides[p.id] !== undefined;
        const logo = adm.partnerLogos[p.id];
        const Icon = I[p.icon] || I.Building;
        const onPatch = (patch) => isCustom ? adm.updateCustomPartner(p.id, patch) : adm.setPartnerOverride(p.id, patch);
        return (
          <Collapsible key={p.id}
            title={<React.Fragment>
              <span className="w-7 h-7 border border-[#14B8A6]/30 flex items-center justify-center overflow-hidden shrink-0">
                {logo && (logo.dark || logo.light)
                  ? <img src={logo.dark || logo.light} className="w-full h-full object-contain p-0.5" alt=""/>
                  : <Icon size={14} className="text-[#14B8A6]"/>}
              </span>
              <span className={hidden?'line-through text-gray-500':''}>{p.name[editLang]}</span>
            </React.Fragment>}
            badge={<React.Fragment>
              {isCustom && <MiniBadge tone="gray">nuevo</MiniBadge>}
              {logo && (logo.light||logo.dark) && <MiniBadge>logo</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">// {p.id}</span>
              <div className="flex items-center gap-3">
                {!isCustom && (
                  <button onClick={()=>adm.setPartnerVisibility(p.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.resetPartnerOverride(p.id)}
                    className="font-mono text-[10px] text-[#EF4444] hover:underline">revertir texto</button>
                )}
                {isCustom && (
                  <button onClick={()=>adm.removeCustomPartner(p.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>
            <LogoUploader partnerId={p.id} mark={p.mark} logo={logo}
              setLogo={(side, d)=>adm.setPartnerLogo(p.id, side, d)}/>
            <PartnerForm p={p} editLang={editLang} onPatch={onPatch}/>
          </Collapsible>
        );
      })}

      <button onClick={addPartner}
        className="w-full inline-flex items-center justify-center gap-2 border border-dashed border-[#14B8A6]/40 hover:bg-[#14B8A6]/10 text-[#14B8A6] py-3 font-medium text-[11px] uppercase tracking-[0.16em] transition-colors">
        <I.Plus size={14}/> Añadir aliado
      </button>
    </React.Fragment>
  );
}

Object.assign(window, {
  rhxProcessLogo, rhxBuildPreset, RHX_PRESETS,
  LogoSlot, LogoUploader, PartnerForm, PartnersTab,
});
