// ===== RIVAMAR Group — Landing pública (v4: dinámica + editable) =====

function Hero({ go, cms, edit, onEdit }) {
  const words = (cms.hero_titulo || '').split(' ');
  const head = words.slice(0, -2).join(' ');
  const tail = words.slice(-2).join(' ');
  const pillars = cms.pillars || [];
  return (
    <section className="relative overflow-hidden min-h-[88vh] flex items-center">
      {/* Slider de fondo: 3 fotos en rotación con desenfoque */}
      <div className="absolute inset-0 overflow-hidden">
        <div className="hero-slider">
          {[cms.hero_img, cms.hero_img2, cms.hero_img3].filter(Boolean).map((src, i) => (
            <div className="hero-slide" key={i}>
              <ImgSlot label="Gastronomía RIVAMAR" src={src} tone="#B5552E" className="w-full h-full" />
            </div>
          ))}
        </div>
        <div className="absolute inset-0" style={{ background: 'linear-gradient(to right, rgb(var(--c-carbon) / calc(var(--hero-overlay,0.6) * 1.55)), rgb(var(--c-carbon) / calc(var(--hero-overlay,0.6) * 0.95)) 42%, rgb(var(--c-carbon) / calc(var(--hero-overlay,0.6) * 0.22)))' }}></div>
        <div className="absolute inset-0" style={{ background: 'linear-gradient(to top, rgb(var(--c-carbon) / calc(var(--hero-overlay,0.6) * 1.1)), transparent 55%)' }}></div>
        <div className="fx-glow fx-float absolute -bottom-20 right-[12%] w-[26rem] h-[26rem] rounded-full pointer-events-none" style={{ background: 'radial-gradient(circle, rgba(var(--c-gold),0.18), transparent 70%)' }}></div>
      </div>

      <div className="relative max-w-7xl mx-auto px-5 lg:px-8 py-24 w-full">
        <div className="max-w-3xl">
          <div className="flex items-center gap-3 mb-7 reveal">
            <ExponorPill />
            <span className="text-xs font-mono uppercase tracking-[0.2em] text-gray-400">Antofagasta · Chile</span>
          </div>
          <h1 className="font-display text-[2.7rem] leading-[1.05] md:text-[4.4rem] md:leading-[1.02] font-extrabold text-gray-50 tracking-tight reveal reveal-d1" style={{ textShadow: '0 2px 24px rgba(0,0,0,0.18)' }}>
            {edit
              ? <Editable as="span" value={cms.hero_titulo} path="site.hero_titulo" edit={edit} onEdit={onEdit} />
              : <>{head} <span className="text-shimmer">{tail}</span></>}
          </h1>
          <Editable as="p" value={cms.hero_subtitulo} path="site.hero_subtitulo" edit={edit} onEdit={onEdit}
            className="mt-6 text-lg md:text-2xl text-cream font-display font-semibold italic reveal reveal-d2" />
          <Editable as="p" value={cms.hero_cuerpo} path="site.hero_cuerpo" edit={edit} onEdit={onEdit}
            className="mt-5 text-base md:text-lg text-gray-300 leading-relaxed max-w-xl reveal reveal-d2" />
          <div className="mt-9 flex flex-wrap gap-3 reveal reveal-d3">
            <Btn variant="gold" onClick={() => go('reservas', { exponor: true })} className="!px-7 !text-base animate-pulse-soft">
              Reservar Mesa · 15% Dcto.
            </Btn>
            <a href={cms.mch_url || 'https://www.mch.cl/'} target="_blank" rel="noopener" className="fx-shine inline-flex items-center justify-center gap-2 font-semibold rounded-lg transition-all min-h-[44px] px-5 !text-base bg-white/5 text-gray-100 border border-gold/30 hover:border-gold hover:bg-white/10">
              <svg width="18" height="18" 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>
              Léenos en la Revista Minera Chilena
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M7 17L17 7M7 7h10v10"/></svg>
            </a>
          </div>

          {/* Pilares de la revista */}
          <div className="mt-12 grid grid-cols-1 sm:grid-cols-3 gap-3 max-w-2xl reveal reveal-d4">
            {pillars.map(([t, d], i) => (
              <div key={i} className="flex items-center gap-3 bg-steel/60 backdrop-blur border border-gold/20 rounded-xl px-4 py-3">
                <span className="grid place-items-center w-9 h-9 rounded-lg bg-gold/15 text-gold shrink-0">
                  {[<StarG key="s" />, <UsersG key="u" />, <ChefG key="c" />][i] || <StarG />}
                </span>
                <div className="min-w-0">
                  <div className="text-sm font-bold text-gray-50 leading-tight">{t}</div>
                  <div className="text-[11px] text-gray-400 leading-tight">{d}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="absolute bottom-6 left-1/2 -translate-x-1/2 text-gray-500 animate-bounce hidden md:block">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="6 9 12 15 18 9"/></svg>
      </div>
    </section>
  );
}

function StarG() { return <svg width="17" height="17" viewBox="0 0 24 24" fill="currentColor"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>; }
function UsersG() { return <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/></svg>; }
function ChefG() { return <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 13.87A4 4 0 0 1 7.41 6a5.11 5.11 0 0 1 1.05-1.54 5 5 0 0 1 7.08 0A5.11 5.11 0 0 1 16.59 6 4 4 0 0 1 18 13.87V21H6z"/><line x1="6" y1="17" x2="18" y2="17"/></svg>; }

function ExponorBanner({ go, cms }) {
  return (
    <section className="relative">
      <div className="max-w-7xl mx-auto px-5 lg:px-8 -mt-10 relative z-10">
        <div className="rounded-2xl border border-gold/40 bg-gradient-to-r from-steel to-steel/60 p-1 shadow-2xl shadow-black/50 reveal">
          <div className="rounded-xl bg-steel/85 backdrop-blur p-6 md:p-8 flex flex-col md:flex-row md:items-center gap-6">
            <div className="grid place-items-center w-20 h-20 rounded-2xl bg-gold/15 border border-gold/40 shrink-0 fx-float">
              <span className="font-sans font-black text-4xl text-shimmer leading-none flex items-start tracking-tight">15<span className="text-xl mt-1">%</span></span>
            </div>
            <div className="flex-1">
              <div className="flex items-center gap-3 flex-wrap">
                <h3 className="font-display text-xl md:text-2xl font-bold text-gray-50">EXPONOR CHILE 2026 — Descuento exclusivo</h3>
                <span className="text-[10px] font-mono uppercase tracking-wider px-2 py-0.5 rounded bg-emerald-500/15 text-emerald-400">8–11 junio · Antofagasta</span>
              </div>
              <p className="mt-2 text-sm text-gray-300 leading-relaxed max-w-2xl">{cms.banner_exponor}</p>
            </div>
            <div className="flex flex-col gap-2 shrink-0">
              <Btn variant="gold" onClick={() => go('reservas', { exponor: true })} className="whitespace-nowrap animate-pulse-soft !text-base !font-bold">Reservar con descuento</Btn>
              <button onClick={() => go('exponor')} className="text-xs text-gold/80 hover:text-gold text-center">Ver campaña EXPONOR →</button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function ExperienciaCard({ local, go, i }) {
  return (
    <div className={`fx-card group rounded-xl overflow-hidden bg-iron border border-white/10 hover:border-gold/50 transition-all duration-300 hover:-translate-y-1.5 hover:shadow-2xl hover:shadow-black/40 flex flex-col reveal reveal-d${i + 1}`}>
      <button onClick={() => go('local', { slug: local.slug })} className="relative text-left overflow-hidden">
        <div className="group-hover:scale-105 transition-transform duration-500">
          <ImgSlot label={local.foto} src={local.foto_img} tone={local.tono} ratio="16/10" className="w-full" />
        </div>
        <div className="absolute inset-0 bg-gradient-to-t from-carbon/75 to-transparent"></div>
        <span className="absolute top-3 left-3 text-[10px] font-mono uppercase tracking-wider px-2 py-1 rounded bg-carbon/80 backdrop-blur text-gold border border-gold/30">
          {local.tagline}
        </span>
      </button>
      <div className="p-6 flex flex-col flex-1">
        <h3 className="font-display text-xl font-bold text-gray-50">{local.nombre}</h3>
        <p className="text-xs text-gray-500 mt-1 font-mono">{local.ubicacion}</p>
        <p className="mt-3 text-sm text-gray-400 leading-relaxed flex-1">{local.especialidad}</p>
        <div className="mt-4 flex flex-wrap gap-1.5">
          {local.destacados.map((d) => (
            <span key={d} className="text-[11px] px-2 py-1 rounded bg-gold/10 text-gold/90 border border-gold/15">{d}</span>
          ))}
        </div>
        <div className="mt-5 flex items-center justify-between pt-4 border-t border-white/5">
          <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-copper">
            <UsersG /> {local.capacidadLabel}
          </span>
          <button onClick={() => go('reservas', { local: local.id })} className="text-sm font-semibold text-gray-100 hover:text-gold transition-colors flex items-center gap-1">
            Reservar →
          </button>
        </div>
      </div>
    </div>
  );
}

function TresExperiencias({ go }) {
  return (
    <section className="max-w-7xl mx-auto px-5 lg:px-8 py-24">
      <div className="reveal"><SectionHead eyebrow="Tres experiencias, un mismo estándar" title="Nuestros locales" desc="Cada local tiene una identidad culinaria propia bajo el estándar operativo unificado de RIVAMAR Group." /></div>
      <div className="grid md:grid-cols-3 gap-6">
        {LOCALES.map((l, i) => <ExperienciaCard key={l.id} local={l} go={go} i={i} />)}
      </div>
    </section>
  );
}

function Stats({ stats }) {
  return (
    <section className="border-y border-gold/15 bg-gradient-to-b from-steel/50 to-steel/20">
      <div className="max-w-7xl mx-auto px-5 lg:px-8 py-16 grid grid-cols-2 lg:grid-cols-4 gap-8">
        {(stats || []).map((s, i) => (
          <div key={s.label} className={`text-center reveal reveal-d${i + 1}`}>
            <div className="font-display text-4xl md:text-6xl font-extrabold text-shimmer">
              <CountUp end={s.n} suffix={s.suf} />
            </div>
            <div className="text-sm text-gray-400 mt-2">{s.label}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function GaleriaPreview({ go }) {
  const preview = GALERIA.filter((g) => g.destacada).slice(0, 4);
  return (
    <section className="max-w-7xl mx-auto px-5 lg:px-8 py-24">
      <div className="flex items-end justify-between gap-4 mb-10 reveal">
        <SectionHead eyebrow="Galería" title="Sabores que hablan por sí solos" />
        <button onClick={() => go('galeria')} className="text-sm font-semibold text-gold hover:text-goldBright shrink-0 mb-10">Ver galería completa →</button>
      </div>
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        {preview.map((g, i) => (
          <button key={g.id} onClick={() => go('galeria')} className={`relative group rounded-lg overflow-hidden reveal reveal-d${i + 1}`}>
            <div className="group-hover:scale-110 transition-transform duration-500">
              <ImgSlot label={g.label} src={g.img} tone={LOCAL_MAP[g.local].tono} ratio="1/1" className="w-full" />
            </div>
            <div className="absolute inset-0 bg-gradient-to-t from-carbon/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity"></div>
            <span className="absolute top-2 left-2 text-[9px] font-mono uppercase px-1.5 py-0.5 rounded bg-gold text-carbon font-bold">★</span>
          </button>
        ))}
      </div>
    </section>
  );
}

function ConveniosCTA({ go, convenios, edit, onEdit }) {
  const beneficios = (convenios && convenios.beneficios) || [];
  return (
    <section className="border-t border-white/10 bg-steel/40">
      <div className="max-w-7xl mx-auto px-5 lg:px-8 py-24 grid lg:grid-cols-2 gap-12 items-center">
        <div className="reveal">
          <p className="text-xs font-semibold uppercase tracking-[0.28em] text-copper mb-3">Convenios empresariales · B2B</p>
          <h2 className="font-display text-3xl md:text-4xl font-bold text-gray-50 tracking-tight leading-[1.1]">
            Alimentación masiva e industrial para la minería
          </h2>
          <Editable as="p" value={convenios && convenios.intro} path="convenios.intro" edit={edit} onEdit={onEdit}
            className="mt-4 text-base text-gray-400 leading-relaxed" />
          <ul className="mt-8 space-y-4">
            {beneficios.map(([t, d]) => (
              <li key={t} className="flex gap-3">
                <span className="grid place-items-center w-6 h-6 rounded-full bg-gold/15 text-gold shrink-0 mt-0.5">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>
                </span>
                <div>
                  <span className="font-semibold text-gray-100 text-sm">{t}</span>
                  <span className="text-gray-400 text-sm"> — {d}</span>
                </div>
              </li>
            ))}
          </ul>
          <div className="mt-9">
            <Btn variant="primary" onClick={() => go('convenios')} className="!px-7 !text-base">
              Cotización Rápida para Delegaciones Mineras
            </Btn>
          </div>
        </div>
        <div className="relative reveal reveal-d2">
          <ImgSlot label="Banquete corporativo minero — salón privado Rivamar" src={convenios && convenios.img} tone="#3E8C84" ratio="4/3" className="w-full rounded-xl" />
          <div className="absolute -bottom-5 -left-5 bg-carbon border border-gold/20 rounded-xl p-4 shadow-2xl hidden sm:block">
            <div className="font-display text-2xl font-extrabold text-gold">50+</div>
            <div className="text-xs text-gray-400">pax por servicio</div>
          </div>
        </div>
      </div>
    </section>
  );
}

function CampaignCountdown({ target }) {
  const calc = () => {
    const diff = new Date(target).getTime() - Date.now();
    const live = diff <= 0;
    const ad = Math.abs(diff);
    return {
      live,
      d: Math.floor(ad / 86400000),
      h: Math.floor((ad % 86400000) / 3600000),
      m: Math.floor((ad % 3600000) / 60000),
      s: Math.floor((ad % 60000) / 1000),
    };
  };
  const [t, setT] = React.useState(calc());
  React.useEffect(() => {
    const id = setInterval(() => setT(calc()), 1000);
    return () => clearInterval(id);
  }, [target]);
  if (t.live) {
    return (
      <div className="rounded-xl bg-exponor/15 border border-exponor/40 px-4 py-4 text-center">
        <div className="inline-flex items-center gap-2 text-exponor font-bold text-base sm:text-lg">
          <span className="flex h-2.5 w-2.5 relative"><span className="animate-ping absolute inline-flex h-2.5 w-2.5 rounded-full bg-exponor opacity-75"></span><span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-exponor"></span></span>
          ¡EXPONOR está en marcha!
        </div>
        <p className="text-sm text-gray-200 mt-1.5">Reserva tu <strong className="text-gold">15% de descuento</strong> — vigente todo junio.</p>
      </div>
    );
  }
  const cell = (val, lbl) => (
    <div className="flex flex-col items-center">
      <div className="grid place-items-center min-w-[56px] sm:min-w-[68px] h-16 sm:h-20 rounded-xl bg-carbon/70 border border-gold/30 font-display font-extrabold text-2xl sm:text-4xl text-gold tabular-nums">
        {String(val).padStart(2, '0')}
      </div>
      <span className="mt-1.5 text-[10px] sm:text-xs uppercase tracking-wider text-gray-400">{lbl}</span>
    </div>
  );
  return (
    <div className="flex items-start gap-2.5 sm:gap-4">
      {cell(t.d, 'días')}
      {cell(t.h, 'hrs')}
      {cell(t.m, 'min')}
      {cell(t.s, 'seg')}
    </div>
  );
}

function ExponorCampaign({ go }) {
  return (
    <section className="relative overflow-hidden bg-steel">
      <div className="absolute inset-0 opacity-25">
        <ImgSlot label="EXPONOR 2026" src={(window.SITE && (window.SITE.hero_img3 || window.SITE.hero_img)) || ''} tone="#F5A623" className="w-full h-full" />
      </div>
      <div className="absolute inset-0 bg-gradient-to-r from-carbon/95 via-carbon/85 to-carbon/70"></div>
      <div className="absolute -top-24 -right-16 w-96 h-96 rounded-full fx-glow pointer-events-none" style={{ background: 'radial-gradient(circle, rgba(var(--c-exponor),0.22), transparent 70%)' }}></div>

      <div className="relative max-w-7xl mx-auto px-5 lg:px-8 py-16 lg:py-20 grid lg:grid-cols-[1.3fr_1fr] gap-10 items-center">
        <div className="reveal">
          <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-exponor/20 border border-exponor/40 text-exponor text-xs font-bold uppercase tracking-wider mb-5">
            <span className="flex h-2 w-2"><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>
            Campaña oficial · 8–11 de junio
          </div>
          <h2 className="font-display text-3xl md:text-5xl font-extrabold text-gray-50 leading-[1.06] tracking-tight">
            Reserva en EXPONOR 2026 y ahorra un <span className="text-shimmer">15%</span> todo junio
          </h2>
          <p className="mt-4 text-base md:text-lg text-gray-300 leading-relaxed max-w-xl">
            Presenta tu credencial de la feria —asistente, visitante, expositor, proveedor o trabajador— y obtén
            <span className="text-exponor font-semibold"> 15% de descuento</span> en los tres locales de RIVAMAR Group durante todo el mes.
          </p>
          <div className="mt-8 flex flex-col sm:flex-row gap-3">
            <Btn variant="gold" onClick={() => go('reservas', { exponor: true })} className="!px-7 !text-base animate-pulse-soft !font-bold">
              Reservar con 15% Dcto.
            </Btn>
            <Btn variant="ghost" onClick={() => go('exponor')} className="!text-base">Ver la campaña completa →</Btn>
          </div>
        </div>

        <div className="reveal reveal-d2 lg:justify-self-end">
          <div className="bg-iron/60 backdrop-blur border border-gold/20 rounded-2xl p-6 sm:p-7">
            <p className="text-sm font-semibold text-gray-200 mb-1">Comienza EXPONOR Chile 2026</p>
            <p className="text-xs text-gray-400 mb-5">Antofagasta · 8 al 11 de junio</p>
            <CampaignCountdown target="2026-06-08T10:00:00" />
            <div className="mt-6 pt-5 border-t border-white/10 flex items-center gap-3">
              <span className="grid place-items-center w-11 h-11 rounded-xl bg-exponor/15 border border-exponor/30 text-exponor font-sans font-black text-base shrink-0">15%</span>
              <p className="text-xs text-gray-300 leading-snug">Beneficio válido <strong className="text-gray-100">todo junio</strong> presentando credencial EXPONOR.</p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Marquee() {
  const items = ['Alta cocina de autor', 'Carnes a la piedra volcánica', 'Cocina marina norteña', 'Catering industrial', 'Buffet corporativo', 'Coctelería premium', 'Servicio 360°', 'Banquetes mineros'];
  const row = [...items, ...items];
  return (
    <section className="border-y border-gold/15 bg-steel/40 py-4 overflow-hidden fx-marquee-wrap">
      <div className="fx-marquee">
        {row.map((t, i) => (
          <span key={i} className="inline-flex items-center text-sm font-display font-semibold text-gray-300 px-6">
            <span className="text-gold mr-6 text-lg leading-none">◆</span> {t}
          </span>
        ))}
      </div>
    </section>
  );
}

function Landing({ go, cms, convenios, stats, edit, onEdit }) {
  return (
    <main>
      <Hero go={go} cms={cms} edit={edit} onEdit={onEdit} />
      <ExponorBanner go={go} cms={cms} />
      <Marquee />
      <TresExperiencias go={go} />
      <ExponorCampaign go={go} />
      <section className="max-w-7xl mx-auto px-5 lg:px-8 pb-4 -mt-4">
        <p className="text-center font-display text-xl md:text-2xl font-bold text-gray-50 mb-5 reveal">
          Las grandes mineras ya nos eligen. <span className="text-shimmer">Conoce por qué en la prensa oficial.</span>
        </p>
        <RevistaMCH />
      </section>
      <Stats stats={stats} />
      <GaleriaPreview go={go} />
      <ConveniosCTA go={go} convenios={convenios} edit={edit} onEdit={onEdit} />
    </main>
  );
}

Object.assign(window, { Landing });
