// ===== RIVAMAR Group — Componentes compartidos (v1.1) =====
const { useState, useEffect, useRef } = React;

// --- Marca / Logotipo (editable desde el CMS) ---
function Logo({ size = 'base', onClick }) {
  const s = (typeof window !== 'undefined' && window.SITE) || {};
  const nombre = s.brand_nombre || 'RIVAMAR';
  const sub = s.brand_sub != null ? s.brand_sub : 'GROUP';
  const inicial = s.brand_inicial || nombre.charAt(0) || 'R';
  const dim = size === 'lg' ? 'text-2xl' : 'text-xl';
  return (
    <button onClick={onClick} className="flex items-center gap-2.5 group shrink-0">
      {s.logo_img ? (
        <img src={s.logo_img} alt={nombre} className={`${size === 'lg' ? 'h-12' : 'h-9'} w-auto object-contain`} />
      ) : (
        <span className="grid place-items-center w-9 h-9 rounded-sm bg-gold text-carbon font-display font-black text-lg leading-none shadow-[0_0_0_1px_rgba(212,165,44,0.4)] group-hover:bg-goldBright transition-colors">
          {inicial}
        </span>
      )}
      {!s.logo_img && (
        <span className={`font-display font-extrabold tracking-tight text-gray-50 ${dim} leading-none`}>
          {nombre}
          {sub ? <span className="block text-[9px] font-sans font-semibold tracking-[0.32em] text-gold -mt-0.5">{sub}</span> : null}
        </span>
      )}
    </button>
  );
}

// --- Placeholder de imagen (rayado industrial) o imagen real si hay src ---
function ImgSlot({ label, className = '', tone = '#D4A52C', ratio, src }) {
  const style = {};
  if (ratio) style.aspectRatio = ratio;
  if (src) {
    return (
      <div style={style} className={`relative overflow-hidden border border-white/5 ${className}`}>
        <img src={src} alt={label || ''} loading="lazy" className="w-full h-full object-cover" />
      </div>
    );
  }
  const placeholderStyle = {
    ...style,
    backgroundColor: '#141c26',
    backgroundImage: `repeating-linear-gradient(135deg, ${tone}16 0px, ${tone}16 2px, transparent 2px, transparent 11px)`,
  };
  return (
    <div style={placeholderStyle} className={`relative overflow-hidden border border-white/5 grid place-items-center ${className}`}>
      <span className="font-mono text-[10.5px] uppercase tracking-wider text-gray-400 px-4 text-center leading-relaxed">
        <span className="block text-gray-500 mb-1 text-[9px]">[ imagen ]</span>
        {label}
      </span>
      <span className="absolute top-2 left-2 w-2 h-2 border-l border-t" style={{ borderColor: tone }}></span>
      <span className="absolute bottom-2 right-2 w-2 h-2 border-r border-b" style={{ borderColor: tone }}></span>
    </div>
  );
}

// --- Subida de imagen: archivo → dataURL reescalado (cabe en localStorage) ---
function fileToScaledDataURL(file, maxW = 1400, quality = 0.82) {
  return new Promise((resolve, reject) => {
    if (!file || !file.type.startsWith('image/')) { reject(new Error('No es una imagen')); return; }
    const reader = new FileReader();
    reader.onerror = reject;
    reader.onload = (e) => {
      const img = new Image();
      img.onerror = reject;
      img.onload = () => {
        const scale = Math.min(1, maxW / img.width);
        const w = Math.round(img.width * scale), h = Math.round(img.height * scale);
        const canvas = document.createElement('canvas');
        canvas.width = w; canvas.height = h;
        canvas.getContext('2d').drawImage(img, 0, 0, w, h);
        try { resolve(canvas.toDataURL('image/jpeg', quality)); }
        catch (err) { reject(err); }
      };
      img.src = e.target.result;
    };
    reader.readAsDataURL(file);
  });
}

// --- Selector de imagen reutilizable: dropzone + URL ---
function ImagePicker({ value, onChange, ratio = '16/10', maxW = 1400 }) {
  const [drag, setDrag] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const inputRef = useRef(null);

  const handleFile = async (file) => {
    setErr(''); setBusy(true);
    try { onChange(await fileToScaledDataURL(file, maxW)); }
    catch (e) { setErr('No se pudo procesar la imagen.'); }
    setBusy(false);
  };
  const onDrop = (e) => {
    e.preventDefault(); setDrag(false);
    const f = e.dataTransfer.files && e.dataTransfer.files[0];
    if (f) handleFile(f);
  };

  return (
    <div>
      <div className="grid sm:grid-cols-[1fr_auto_1fr] gap-3 items-stretch">
        {/* Dropzone */}
        <div
          onClick={() => inputRef.current && inputRef.current.click()}
          onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
          onDragLeave={() => setDrag(false)}
          onDrop={onDrop}
          className={`cursor-pointer rounded-lg border-2 border-dashed grid place-items-center text-center px-4 py-7 transition-colors ${drag ? 'border-gold bg-gold/5' : 'border-white/15 bg-carbon hover:border-white/30'}`}>
          <div>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="mx-auto text-gray-400 mb-2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
            <span className="text-sm text-gray-400">{busy ? 'Procesando…' : 'Subir imagen desde tu dispositivo'}</span>
          </div>
          <input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={(e) => e.target.files[0] && handleFile(e.target.files[0])} />
        </div>
        <div className="grid place-items-center text-xs text-gray-600 font-mono sm:py-0 py-1">o</div>
        {/* URL */}
        <input
          className="w-full min-h-[44px] px-3.5 rounded-md bg-carbon border border-white/10 text-gray-100 text-sm placeholder-gray-600 focus:border-gold outline-none self-center"
          placeholder="https://... URL de imagen" value={value && value.startsWith('data:') ? '' : (value || '')}
          onChange={(e) => onChange(e.target.value)} />
      </div>
      {err && <p className="text-xs text-orange-400 mt-1.5">{err}</p>}
      {value && (
        <div className="mt-3 flex items-center gap-3">
          <div className="w-28 shrink-0 rounded-md overflow-hidden border border-white/10" style={{ aspectRatio: ratio }}>
            <img src={value} alt="" className="w-full h-full object-cover" />
          </div>
          <button onClick={() => onChange('')} className="text-xs font-semibold text-red-400 hover:text-red-300">Quitar imagen</button>
        </div>
      )}
    </div>
  );
}

// --- Badge de estado de reserva ---
function EstadoBadge({ estado }) {
  const map = {
    pendiente:  { bg: 'bg-orange-500/15',  text: 'text-orange-400',  dot: 'bg-orange-400',  label: 'Pendiente' },
    confirmada: { bg: 'bg-emerald-500/15', text: 'text-emerald-400', dot: 'bg-emerald-400', label: 'Confirmada' },
    cancelada:  { bg: 'bg-red-500/15',     text: 'text-red-400',     dot: 'bg-red-400',     label: 'Cancelada' },
    eliminada:  { bg: 'bg-gray-500/15',    text: 'text-gray-400',    dot: 'bg-gray-500',    label: 'Eliminada' },
  };
  const s = map[estado] || map.pendiente;
  return (
    <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold ${s.bg} ${s.text}`}>
      <span className={`w-1.5 h-1.5 rounded-full ${s.dot}`}></span>
      {s.label}
    </span>
  );
}

// --- Píldora EXPONOR ---
function ExponorPill({ className = '' }) {
  return (
    <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold bg-exponor/15 text-exponor border border-exponor/30 ${className}`}>
      <span className="text-[13px] leading-none">★</span> EXPONOR −15%
    </span>
  );
}

// --- Botón ---
function Btn({ children, onClick, variant = 'primary', className = '', type = 'button', disabled }) {
  const base = 'fx-shine inline-flex items-center justify-center gap-2 font-semibold rounded-lg transition-all min-h-[44px] px-5 text-sm tracking-wide disabled:opacity-50 disabled:cursor-not-allowed';
  const variants = {
    primary: 'bg-gold text-carbon hover:bg-copper hover:text-gray-50 shadow-lg shadow-gold/20 active:scale-[0.98]',
    gold: 'bg-gold text-carbon hover:bg-goldBright shadow-lg shadow-gold/25 active:scale-[0.98]',
    copper: 'bg-copper text-gray-50 hover:bg-copperDark shadow-lg shadow-copper/20 active:scale-[0.98]',
    ghost: 'bg-white/5 text-gray-100 hover:bg-white/10 border border-white/10',
    outline: 'bg-transparent text-gold border border-gold/50 hover:bg-gold/10',
  };
  return (
    <button type={type} onClick={onClick} disabled={disabled} className={`${base} ${variants[variant]} ${className}`}>
      {children}
    </button>
  );
}

// --- Navbar corporativo ---
function Navbar({ view, go }) {
  const [open, setOpen] = useState(false);
  const [localesOpen, setLocalesOpen] = useState(false);
  const links = [
    { id: 'home', label: 'Inicio' },
    { id: 'galeria', label: 'Galería' },
    { id: 'nosotros', label: 'Nosotros' },
    { id: 'convenios', label: 'Convenios B2B' },
  ];
  const linkCls = (id) =>
    `fx-underline relative px-3 py-2 rounded-md text-sm font-medium transition-colors min-h-[44px] flex items-center ${
      view === id ? 'text-gold bg-white/5' : 'text-gray-300 hover:text-gray-50'
    }`;
  return (
    <header className="sticky top-0 z-40 bg-carbon/85 backdrop-blur-md border-b border-white/10">
      <div className="max-w-7xl mx-auto px-5 lg:px-8 h-[68px] flex items-center justify-between gap-4">
        <Logo onClick={() => go('home')} />
        <nav className="hidden lg:flex items-center gap-1">
          <button className={linkCls('home')} onClick={() => go('home')}>Inicio</button>
          <button onClick={() => go('exponor')}
            className={`fx-shine relative inline-flex items-center gap-1.5 px-3.5 py-2 rounded-full text-sm font-bold transition-all min-h-[44px] ${view === 'exponor' ? 'bg-exponor text-carbon' : 'bg-exponor/15 text-exponor border border-exponor/40 hover:bg-exponor hover:text-carbon'}`}>
            <span className="text-[13px] leading-none">★</span> EXPONOR 2026
            <span className="absolute -top-1 -right-1 flex h-3 w-3"><span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-exponor opacity-75"></span><span className="relative inline-flex rounded-full h-3 w-3 bg-exponor"></span></span>
          </button>
          {/* Locales dropdown */}
          <div className="relative" onMouseEnter={() => setLocalesOpen(true)} onMouseLeave={() => setLocalesOpen(false)}>
            <button className={linkCls('local') + ' gap-1'} onClick={() => setLocalesOpen(!localesOpen)}>
              Locales <ChevronDown />
            </button>
            {localesOpen && (
              <div className="absolute top-full left-0 pt-1 w-64">
                <div className="bg-iron border border-white/10 rounded-lg shadow-2xl p-1.5">
                  {LOCALES.map((l) => (
                    <button key={l.id} onClick={() => { go('local', { slug: l.slug }); setLocalesOpen(false); }}
                      className="w-full text-left px-3 py-2.5 rounded-md hover:bg-white/5 transition-colors">
                      <span className="block text-sm font-semibold text-gray-100">{l.nombre}</span>
                      <span className="block text-xs text-gray-500">{l.tagline}</span>
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>
          <button className={linkCls('galeria')} onClick={() => go('galeria')}>Galería</button>
          <button className={linkCls('nosotros')} onClick={() => go('nosotros')}>Nosotros</button>
          <button className={linkCls('convenios')} onClick={() => go('convenios')}>Convenios B2B</button>
        </nav>
        <div className="hidden lg:flex items-center gap-2">
          <button onClick={() => go('admin')} className={`text-sm font-medium flex items-center gap-1.5 min-h-[44px] px-3 rounded-md transition-colors ${view === 'admin' ? 'text-gold' : 'text-gray-400 hover:text-gray-100'}`}>
            <LockIcon /> Admin
          </button>
          <Btn variant="gold" onClick={() => go('reservas')} className="!px-4">Reservar Mesa</Btn>
        </div>
        <button className="lg:hidden text-gray-100 p-2 -mr-2" onClick={() => setOpen(!open)} aria-label="Menú">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
        </button>
      </div>
      {open && (
        <div className="lg:hidden border-t border-white/10 bg-iron px-5 py-3 flex flex-col gap-1">
          <button className={linkCls('home') + ' w-full justify-start'} onClick={() => { go('home'); setOpen(false); }}>Inicio</button>
          <button onClick={() => { go('exponor'); setOpen(false); }}
            className="flex items-center justify-between gap-2 px-3 py-3 rounded-lg bg-exponor/15 border border-exponor/40 text-exponor font-bold">
            <span className="flex items-center gap-2"><span>★</span> EXPONOR 2026 · 15% Dcto.</span>
            <span>→</span>
          </button>
          <p className="text-[10px] font-semibold uppercase tracking-wider text-gray-600 px-3 pt-1">Nuestros locales</p>
          {LOCALES.map((l) => (
            <button key={l.id} className="text-left px-3 py-2 rounded-md text-sm text-gray-300 hover:bg-white/5" onClick={() => { go('local', { slug: l.slug }); setOpen(false); }}>{l.nombre}</button>
          ))}
          <div className="border-t border-white/5 my-1.5"></div>
          <button className={linkCls('galeria') + ' w-full justify-start'} onClick={() => { go('galeria'); setOpen(false); }}>Galería</button>
          <button className={linkCls('nosotros') + ' w-full justify-start'} onClick={() => { go('nosotros'); setOpen(false); }}>Nosotros</button>
          <button className={linkCls('convenios') + ' w-full justify-start'} onClick={() => { go('convenios'); setOpen(false); }}>Convenios B2B</button>
          <div className="border-t border-white/5 my-1.5"></div>
          <button className={linkCls('admin') + ' w-full justify-start'} onClick={() => { go('admin'); setOpen(false); }}>Panel Admin</button>
          <Btn variant="gold" onClick={() => { go('reservas'); setOpen(false); }} className="mt-2">Reservar Mesa (15% Dcto.)</Btn>
        </div>
      )}
    </header>
  );
}

function ChevronDown() { return <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="6 9 12 15 18 9"/></svg>; }
function LockIcon() { return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>; }

// --- Barra EXPONOR sticky (solo móvil) — maximiza conversión ---
function ExponorMobileBar({ go }) {
  const [closed, setClosed] = useState(false);
  if (closed) return null;
  return (
    <div className="lg:hidden fixed bottom-0 inset-x-0 z-40 bg-steel/95 backdrop-blur-md border-t border-exponor/30 px-4 py-2.5 flex items-center gap-3">
      <span className="grid place-items-center w-9 h-9 rounded-lg bg-exponor/15 border border-exponor/30 text-exponor font-sans font-black text-sm shrink-0">15%</span>
      <div className="flex-1 min-w-0">
        <p className="text-xs font-bold text-gray-50 leading-tight">Descuento EXPONOR 2026</p>
        <p className="text-[11px] text-gray-400 leading-tight truncate">Reserva con tu credencial</p>
      </div>
      <button onClick={() => go('reservas', { exponor: true })} className="shrink-0 bg-gold text-carbon text-xs font-bold px-3 py-2 rounded-lg min-h-[40px]">Reservar</button>
      <button onClick={() => setClosed(true)} aria-label="Cerrar" className="shrink-0 text-gray-500 hover:text-gray-200 w-7 h-7 grid place-items-center">✕</button>
    </div>
  );
}

// --- Utilidad: escribir en una ruta tipo 'site.hero_titulo' o 'locales.0.nombre' ---
function setPath(obj, path, value) {
  const keys = path.split('.');
  const root = Array.isArray(obj) ? obj.slice() : { ...obj };
  let cur = root;
  for (let i = 0; i < keys.length - 1; i++) {
    const k = keys[i];
    const next = cur[k];
    cur[k] = Array.isArray(next) ? next.slice() : { ...next };
    cur = cur[k];
  }
  cur[keys[keys.length - 1]] = value;
  return root;
}

function escapeHtml(s) {
  return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

// --- Texto editable inline (solo en modo edición del admin) ---
function Editable({ as = 'span', value, path, edit, onEdit, className = '' }) {
  if (!edit) return React.createElement(as, { className }, value);
  return React.createElement(as, {
    className,
    'data-cms': path,
    title: 'Clic para editar',
    contentEditable: true,
    suppressContentEditableWarning: true,
    spellCheck: false,
    onBlur: (e) => { const t = e.currentTarget.innerText.trim(); if (t !== value) onEdit(path, t); },
    dangerouslySetInnerHTML: { __html: escapeHtml(value) },
  });
}

// --- Hook de scroll reveal (no-op: la lógica vive en un script global del HTML,
//     inmune a los re-renders de React) ---
function useReveal(dep) {
  useEffect(() => {
    if (window.__revealKick) window.__revealKick();
  }, [dep]);
}

// --- Barra flotante de Modo Edición (visible solo tras login admin) ---
function EditModeBar({ edit, setEdit, go }) {
  return (
    <div className="fixed top-20 left-1/2 -translate-x-1/2 z-50 flex items-center gap-2.5 bg-steel/95 backdrop-blur-md border border-gold/30 rounded-full pl-4 pr-2 py-2 shadow-2xl">
      <span className={`w-2 h-2 rounded-full ${edit ? 'bg-emerald-400 animate-pulse' : 'bg-gray-500'}`}></span>
      <span className="text-xs font-medium text-gray-200">{edit ? 'Modo edición activo — clic sobre los textos' : 'Vista previa'}</span>
      <button onClick={() => setEdit(!edit)} className={`text-xs font-bold px-3 py-1.5 rounded-full transition-colors ${edit ? 'bg-gold text-carbon' : 'bg-white/10 text-gray-200 hover:bg-white/20'}`}>
        {edit ? 'Editando' : 'Activar'}
      </button>
      <button onClick={() => go('admin')} className="text-xs font-medium text-gray-400 hover:text-gold px-2">Panel ↗</button>
    </div>
  );
}

// --- Banner Revista Oficial MCH (reutilizable, editable desde CMS) ---
function RevistaMCH({ className = '' }) {
  const s = (typeof window !== 'undefined' && window.SITE) || {};
  const url = s.mch_url || 'https://www.mch.cl/';
  const eyebrow = s.mch_eyebrow || 'Prensa minera oficial';
  const titulo = s.mch_titulo || 'Aparecemos en la Revista Oficial de la Minería Chilena';
  const texto = s.mch_texto || 'Conoce la cobertura de EXPONOR 2026 y descubre por qué las principales empresas mineras del país eligen a RIVAMAR Group.';
  const boton = s.mch_boton || 'Ver revista oficial';
  return (
    <a href={url} target="_blank" rel="noopener"
      className={`fx-shine group relative block overflow-hidden rounded-2xl border border-gold/40 bg-gradient-to-r from-steel to-iron/60 p-1 shadow-2xl shadow-black/40 ${className}`}>
      <span className="absolute -top-16 -right-10 w-72 h-72 rounded-full fx-glow pointer-events-none" style={{ background: 'radial-gradient(circle, rgba(var(--c-gold),0.25), transparent 70%)' }}></span>
      <div className="relative rounded-xl bg-carbon/40 backdrop-blur p-7 md:p-9 flex flex-col md:flex-row md:items-center gap-6 text-left">
        <div className="grid place-items-center w-16 h-16 rounded-2xl bg-gold/15 border border-gold/40 shrink-0 fx-float text-gold">
          <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>
        </div>
        <div className="flex-1">
          <div className="inline-flex items-center gap-2 px-2.5 py-1 rounded-full bg-exponor/15 border border-exponor/40 text-exponor text-[11px] font-bold uppercase tracking-wider mb-2">
            <span className="flex h-2 w-2 relative"><span className="animate-ping absolute inline-flex h-2 w-2 rounded-full bg-exponor opacity-75"></span><span className="relative inline-flex rounded-full h-2 w-2 bg-exponor"></span></span>
            {eyebrow}
          </div>
          <h3 className="font-display text-xl md:text-2xl font-bold text-gray-50">{titulo}</h3>
          <p className="mt-2 text-sm text-gray-300 leading-relaxed max-w-2xl">{texto}</p>
        </div>
        <span className="inline-flex items-center gap-2 shrink-0 bg-gold text-carbon font-bold text-sm px-5 py-3 rounded-lg group-hover:gap-3 transition-all">
          {boton}
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M7 17L17 7M7 7h10v10"/></svg>
        </span>
      </div>
    </a>
  );
}

// --- Botón "ir arriba" (aparece al bajar) ---
function ScrollTop() {
  const [show, setShow] = useState(false);
  useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 500);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  if (!show) return null;
  return (
    <button onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })} aria-label="Volver arriba"
      className="fixed bottom-24 left-4 lg:bottom-6 lg:left-6 z-50 grid place-items-center w-12 h-12 rounded-full bg-steel/90 backdrop-blur border border-gold/40 text-gold shadow-xl hover:bg-gold hover:text-carbon transition-all hover:-translate-y-0.5 animate-fade-up">
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><polyline points="18 15 12 9 6 15"/></svg>
    </button>
  );
}

// --- Botón flotante de WhatsApp ---
function WhatsAppFAB({ whatsapp = '56900000000' }) {
  const [hover, setHover] = useState(false);
  const msg = encodeURIComponent('¡Hola! Me gustaría hacer una consulta sobre reservas en RIVAMAR Group.');
  return (
    <a href={`https://wa.me/${whatsapp}?text=${msg}`} target="_blank" rel="noopener"
       onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
       className="fixed bottom-20 lg:bottom-6 right-6 z-50 flex items-center gap-3 group">
      {hover && (
        <span className="hidden sm:block bg-iron text-gray-100 text-sm font-medium px-4 py-2.5 rounded-lg shadow-xl border border-white/10 whitespace-nowrap">
          Habla con un ejecutivo
        </span>
      )}
      <span className="grid place-items-center w-14 h-14 rounded-full bg-[#25D366] text-white shadow-xl shadow-[#25D366]/30 group-hover:scale-105 transition-transform">
        <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.6.2-.2.3-.7.9-.8 1-.2.2-.3.2-.6.1-.3-.2-1.2-.5-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.6-1.5-.8-2-.2-.5-.4-.5-.6-.5h-.5c-.2 0-.5.1-.7.3-.2.3-.9.9-.9 2.2s.9 2.5 1.1 2.7c.1.2 1.8 2.7 4.3 3.8.6.3 1.1.4 1.5.5.6.2 1.2.2 1.6.1.5-.1 1.7-.7 1.9-1.3.2-.7.2-1.2.2-1.3-.1-.2-.3-.2-.6-.4M12 2a10 10 0 0 0-8.6 15l-1.4 5.1 5.2-1.4A10 10 0 1 0 12 2"/></svg>
      </span>
    </a>
  );
}

// --- Footer ---
function SocialIcon({ kind }) {
  const p = {
    ig: <path d="M12 2.2c3.2 0 3.6 0 4.9.07 1.2.05 1.8.25 2.2.42.6.2 1 .5 1.4.9.4.4.7.8.9 1.4.17.4.37 1 .42 2.2.07 1.3.07 1.7.07 4.9s0 3.6-.07 4.9c-.05 1.2-.25 1.8-.42 2.2-.2.6-.5 1-.9 1.4-.4.4-.8.7-1.4.9-.4.17-1 .37-2.2.42-1.3.07-1.7.07-4.9.07s-3.6 0-4.9-.07c-1.2-.05-1.8-.25-2.2-.42a3.8 3.8 0 0 1-1.4-.9c-.4-.4-.7-.8-.9-1.4-.17-.4-.37-1-.42-2.2C2.2 15.6 2.2 15.2 2.2 12s0-3.6.07-4.9c.05-1.2.25-1.8.42-2.2.2-.6.5-1 .9-1.4.4-.4.8-.7 1.4-.9.4-.17 1-.37 2.2-.42C8.4 2.2 8.8 2.2 12 2.2m0 3.5a6.3 6.3 0 1 0 0 12.6 6.3 6.3 0 0 0 0-12.6m0 10.4a4.1 4.1 0 1 1 0-8.2 4.1 4.1 0 0 1 0 8.2m6.5-10.6a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0"/>,
    fb: <path d="M22 12a10 10 0 1 0-11.6 9.9v-7H7.9V12h2.5V9.8c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.8l-.4 2.9h-2.4v7A10 10 0 0 0 22 12"/>,
    in: <path d="M20.4 3H3.6A.6.6 0 0 0 3 3.6v16.8a.6.6 0 0 0 .6.6h16.8a.6.6 0 0 0 .6-.6V3.6a.6.6 0 0 0-.6-.6M8.3 18.3H5.4V9.4h2.9zM6.9 8.2a1.7 1.7 0 1 1 0-3.4 1.7 1.7 0 0 1 0 3.4m11.4 10.1h-2.9v-4.3c0-1 0-2.4-1.4-2.4s-1.7 1.1-1.7 2.3v4.4H9.4V9.4h2.8v1.2h.04c.4-.7 1.3-1.5 2.8-1.5 3 0 3.5 2 3.5 4.5z"/>,
  };
  return <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">{p[kind]}</svg>;
}

function Footer({ go, cms }) {
  const s = cms || (typeof window !== 'undefined' && window.SITE) || {};
  const socials = [['ig', s.social_ig], ['fb', s.social_fb], ['in', s.social_in]];
  return (
    <footer className="border-t border-white/10 bg-steel/40">
      <div className="max-w-7xl mx-auto px-5 lg:px-8 py-14 grid md:grid-cols-12 gap-10">
        <div className="md:col-span-4">
          <Logo />
          <p className="mt-4 text-sm text-gray-400 leading-relaxed max-w-sm">
            {s.footer_desc}
          </p>
          <div className="mt-5 flex items-center gap-2.5">
            {socials.map(([k, href]) => (
              <a key={k} href={href || '#'} target="_blank" rel="noopener" className="grid place-items-center w-9 h-9 rounded-full bg-white/5 text-gray-400 hover:text-gold hover:bg-white/10 transition-colors"><SocialIcon kind={k} /></a>
            ))}
          </div>
        </div>

        <div className="md:col-span-2">
          <h4 className="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-3">Navegación</h4>
          <ul className="space-y-2 text-sm text-gray-400">
            {[['home','Inicio'],['reservas','Reservas'],['galeria','Galería'],['convenios','Convenios B2B'],['exponor','EXPONOR 2026'],['privacidad','Privacidad'],['admin','Panel Admin']].map(([id,l]) => (
              <li key={id}><button onClick={() => go(id)} className="hover:text-gold transition-colors">{l}</button></li>
            ))}
          </ul>
        </div>

        <div className="md:col-span-6">
          <h4 className="text-xs font-semibold uppercase tracking-wider text-gray-500 mb-3">Nuestros locales</h4>
          <div className="grid sm:grid-cols-3 gap-4">
            {LOCALES.map((l) => (
              <div key={l.id} className="text-sm">
                <button onClick={() => go('local', { slug: l.slug })} className="font-semibold text-gray-200 hover:text-gold transition-colors">{l.nombre}</button>
                <p className="text-gray-500 text-xs mt-1 leading-relaxed">{l.ubicacion}</p>
                <p className="text-gray-400 text-xs mt-1 font-mono">{l.telefono}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="border-t border-white/5">
        <div className="max-w-7xl mx-auto px-5 lg:px-8 py-4 flex flex-col sm:flex-row justify-between gap-2 text-xs text-gray-500">
          <span>{s.footer_copy || '© 2026 RIVAMAR Group — Antofagasta, Chile · MAEDY GROUP'}</span>
          <span className="flex gap-4">
            <button onClick={() => go('terminos')} className="hover:text-gray-300">Términos y Condiciones</button>
            <button onClick={() => go('privacidad')} className="hover:text-gray-300">Política de Privacidad (Ley 19.628)</button>
          </span>
        </div>
      </div>
    </footer>
  );
}

// --- Sección con título ---
function SectionHead({ eyebrow, title, desc, center }) {
  return (
    <div className={`${center ? 'text-center mx-auto' : ''} max-w-2xl mb-10`}>
      {eyebrow && <p className="text-xs font-semibold uppercase tracking-[0.28em] text-copper mb-3">{eyebrow}</p>}
      <h2 className="font-display text-3xl md:text-4xl font-bold text-gray-50 tracking-tight leading-[1.1]">{title}</h2>
      {desc && <p className="mt-4 text-base text-gray-400 leading-relaxed">{desc}</p>}
    </div>
  );
}

// --- Conteo animado (estadísticas) ---
function CountUp({ end, suffix = '', dur = 1400 }) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    let started = false;
    const obs = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && !started) {
        started = true;
        const t0 = performance.now();
        const tick = (t) => {
          const p = Math.min((t - t0) / dur, 1);
          const eased = 1 - Math.pow(1 - p, 3);
          setVal(Math.round(end * eased));
          if (p < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
      }
    }, { threshold: 0.4 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [end, dur]);
  return <span ref={ref}>{val}{suffix}</span>;
}

Object.assign(window, {
  Logo, ImgSlot, EstadoBadge, ExponorPill, Btn, Navbar, WhatsAppFAB, Footer, SectionHead,
  LockIcon, CountUp, SocialIcon, ExponorMobileBar, ImagePicker, fileToScaledDataURL,
  setPath, escapeHtml, Editable, useReveal, EditModeBar, ScrollTop, RevistaMCH,
});
