/* ============================================================
   lomi — pantalla HOME (data-driven desde window.LOMI_DATA.settings)
   ============================================================ */

// Helpers para leer settings con fallback
function S(key, fallback) {
  const s = (window.LOMI_DATA && window.LOMI_DATA.settings) || {};
  return s[key] != null && s[key] !== '' ? s[key] : fallback;
}
function J(key, fallback) {
  try {
    const v = S(key, null);
    if (v === null) return fallback;
    if (typeof v === 'object') return v;
    return JSON.parse(v);
  } catch { return fallback; }
}
function V(key) {
  const v = S(key, '1');
  return v === '1' || v === 1 || v === true;
}

/* ── Carrusel de banners promocionales ── */
function BannerCarousel({ go }) {
  const banners = (window.LOMI_DATA && window.LOMI_DATA.BANNERS) || [];
  const autoplay = S('banners_autoplay', '1') === '1';
  const interval = Number(S('banners_interval', '5000'));
  const [idx, setIdx] = React.useState(0);
  const [prev_idx, setPrevIdx] = React.useState(null);
  const timerRef = React.useRef(null);

  function startAuto() {
    clearInterval(timerRef.current);
    if (!autoplay || banners.length <= 1) return;
    timerRef.current = setInterval(() => setIdx(i => (i + 1) % banners.length), interval);
  }

  React.useEffect(() => {
    startAuto();
    return () => clearInterval(timerRef.current);
  }, [banners.length, autoplay, interval]);

  function go_to(i) {
    setPrevIdx(idx);
    setIdx(i);
    startAuto();
  }
  function goPrev() { go_to((idx - 1 + banners.length) % banners.length); }
  function goNext() { go_to((idx + 1) % banners.length); }

  if (!banners.length) return null;

  const b = banners[idx];

  function handleBtnClick() {
    const url = b.button_url || '';
    if (!url) return;
    if (url.startsWith('http')) window.open(url, '_blank', 'noopener');
    else go({ name: url.replace(/^\//, '') || 'catalog' });
  }

  return (
    <div style={{ position:'relative', overflow:'hidden', background:'var(--surface-2,#f5f5f0)', lineHeight:0 }}>
      <style>{`
        .bc-track { position:relative; width:100%; overflow:hidden; }
        .bc-slide { position:relative; width:100%; aspect-ratio:21/7; min-height:180px; max-height:460px; overflow:hidden; display:flex; align-items:center; }
        .bc-slide img { position:absolute; inset:0; width:100%; height:100%; object-fit:cover; display:block; transition:opacity 0.5s ease; }
        .bc-overlay { position:absolute; inset:0; background:linear-gradient(100deg,rgba(0,0,0,0.52) 0%,rgba(0,0,0,0.22) 55%,rgba(0,0,0,0.04) 100%); }
        .bc-overlay-color { position:absolute; inset:0; }
        .bc-body { position:relative; z-index:2; padding: clamp(24px,5vw,56px) clamp(24px,7vw,80px); max-width:640px; line-height:1; }
        .bc-eyebrow { font-size:12px; font-weight:700; letter-spacing:0.1em; text-transform:uppercase; color:rgba(255,255,255,0.75); margin-bottom:10px; display:block; }
        .bc-title { font-size:clamp(1.35rem,3.5vw,2.5rem); font-weight:800; color:#fff; margin:0 0 10px; font-family:var(--font-display,inherit); line-height:1.18; text-shadow:0 2px 12px rgba(0,0,0,0.18); }
        .bc-sub { font-size:clamp(0.88rem,1.8vw,1.05rem); color:rgba(255,255,255,0.86); margin:0 0 22px; line-height:1.5; max-width:440px; }
        .bc-btn { display:inline-flex; align-items:center; gap:8px; padding:11px 24px; border-radius:var(--r-sm,8px); background:#fff; color:var(--coral,#e05c3a); font-weight:700; font-size:14px; border:none; cursor:pointer; transition:transform 0.15s,box-shadow 0.15s; box-shadow:0 4px 18px rgba(0,0,0,0.18); }
        .bc-btn:hover { transform:translateY(-1px); box-shadow:0 6px 24px rgba(0,0,0,0.22); }
        .bc-no-img { position:absolute; inset:0; display:flex; align-items:center; }
        .bc-arrows { position:absolute; top:50%; transform:translateY(-50%); display:flex; justify-content:space-between; width:100%; padding:0 12px; pointer-events:none; z-index:3; box-sizing:border-box; }
        .bc-arrow { pointer-events:all; width:40px; height:40px; border-radius:50%; background:rgba(0,0,0,0.28); backdrop-filter:blur(8px); border:1.5px solid rgba(255,255,255,0.22); color:#fff; cursor:pointer; display:flex; align-items:center; justify-content:center; font-size:20px; font-weight:300; transition:background 0.2s,transform 0.15s; line-height:1; padding:0; }
        .bc-arrow:hover { background:rgba(0,0,0,0.5); transform:scale(1.08); }
        .bc-dots { position:absolute; bottom:14px; left:50%; transform:translateX(-50%); display:flex; gap:6px; z-index:3; }
        .bc-dot { width:7px; height:7px; border-radius:50%; background:rgba(255,255,255,0.4); border:none; cursor:pointer; padding:0; transition:all 0.25s; }
        .bc-dot.on { background:#fff; width:24px; border-radius:4px; }
        @media(max-width:540px){ .bc-slide { aspect-ratio:16/9; } .bc-body { padding:20px 18px; } }
      `}</style>
      <div className="bc-track">
        <div className="bc-slide">
          {b.video_url
            ? <><video src={b.video_url} autoPlay muted loop playsInline style={{ position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover' }} /><div className="bc-overlay" /></>
            : b.image_url
              ? <><img src={b.image_url} alt={b.title || 'Banner'} loading="eager" style={{ objectPosition: b.object_position || 'center center' }} /><div className="bc-overlay" /></>
              : <div className="bc-overlay-color" style={{ background:'linear-gradient(135deg, var(--coral,#e05c3a) 0%, var(--teal,#2d9e8f) 100%)' }} />
          }
          <div className="bc-body">
            {b.subtitle && <span className="bc-eyebrow">{b.subtitle}</span>}
            {b.title && <h2 className="bc-title">{b.title}</h2>}
            {b.button_text && (
              <button className="bc-btn" onClick={handleBtnClick}>
                {b.button_text}
                <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="4" y1="12" x2="20" y2="12"/><polyline points="14 6 20 12 14 18"/></svg>
              </button>
            )}
          </div>
        </div>
      </div>
      {banners.length > 1 && (
        <>
          <div className="bc-arrows">
            <button className="bc-arrow" onClick={goPrev} aria-label="Anterior">‹</button>
            <button className="bc-arrow" onClick={goNext} aria-label="Siguiente">›</button>
          </div>
          <div className="bc-dots">
            {banners.map((_, i) => (
              <button key={i} className={'bc-dot' + (i === idx ? ' on' : '')} onClick={() => go_to(i)} aria-label={`Banner ${i + 1}`} />
            ))}
          </div>
        </>
      )}
    </div>
  );
}

/* ── Carrusel personalizado (sección custom del page builder) ── */
function CustomCarousel({ section, go, addToCart, favorites, onToggleFavorite }) {
  const { PRODUCTS } = window.LOMI_DATA;
  let data = {};
  try { data = JSON.parse(section.data || '{}'); } catch {}
  const productIds = data.products || [];
  const products = productIds.map(id => PRODUCTS.find(p => p.id === id)).filter(Boolean);
  if (!products.length) return null;
  return (
    <section className="wrap section">
      <div className="section-head">
        <div>
          {section.eyebrow && <span className="eyebrow">{section.eyebrow}</span>}
          <h2 className="section-title">{section.title || 'Productos'}</h2>
        </div>
        {data.view_all_text && (
          <button className="link-arrow" onClick={() => go({ name: "catalog" })}>
            {data.view_all_text} <Icon name="arrow" size={16}/>
          </button>
        )}
      </div>
      <div className="prod-grid">
        {products.map((p, i) => (
          <ProductCard key={p.id} product={p} idx={i}
            onOpen={pr => go({ name: 'product', id: pr.id })}
            onAdd={addToCart}
            favorites={favorites}
            onToggleFavorite={onToggleFavorite}
          />
        ))}
      </div>
    </section>
  );
}

/* ── Bloque imagen+texto (tipo richblock) ── */
function RichBlock({ section, go }) {
  let data = {};
  try { data = JSON.parse(section.data || '{}'); } catch {}
  const layout  = data.layout || 'image-left';
  const hasImg  = !!data.image && layout !== 'no-image';
  const isRight = layout === 'image-right';

  function handleCta() {
    const url = data.cta_url || '';
    if (url.startsWith('http')) window.open(url, '_blank', 'noopener');
    else if (url) go({ name: url.replace(/^\//, '') });
  }

  return (
    <section className="wrap section">
      <div className={'richblock ' + (isRight ? 'richblock-right' : hasImg ? 'richblock-left' : 'richblock-noimg')}>
        {hasImg && (
          <div className="richblock-img">
            <img src={data.image} alt={section.title || ''} loading="lazy" />
          </div>
        )}
        <div className="richblock-copy reveal">
          {section.eyebrow && <span className="eyebrow">{section.eyebrow}</span>}
          {section.title   && <h2 className="section-title">{section.title}</h2>}
          {data.body && <p className="richblock-body">{data.body}</p>}
          {data.cta_text && (
            <button className="btn btn-primary" onClick={handleCta}>
              {data.cta_text} <Icon name="arrow" size={16}/>
            </button>
          )}
        </div>
      </div>
    </section>
  );
}

/* ── Renderiza las secciones custom para una posición dada ── */
function RenderSections({ position, go, addToCart, favorites, onToggleFavorite }) {
  const sections = (window.LOMI_DATA && window.LOMI_DATA.SECTIONS) || [];
  const matching = sections
    .filter(s => s.active && s.position === position)
    .sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));
  if (!matching.length) return null;
  return (
    <>
      {matching.map(s => {
        if (s.type === 'carousel')  return <CustomCarousel key={s.id} section={s} go={go} addToCart={addToCart} favorites={favorites} onToggleFavorite={onToggleFavorite}/>;
        if (s.type === 'richblock') return <RichBlock key={s.id} section={s} go={go} />;
        return null;
      })}
    </>
  );
}

function Home({ go, addToCart, _v, favorites, onToggleFavorite }) {
  const { PRODUCTS, CATEGORIES, TESTIMONIALS } = window.LOMI_DATA;
  const bannersVisible = V('banners_visible');

  // Featured products: si hay lista en settings, la usa; si no, usa badge
  const featuredIds = J('featured_products', []);
  const featured = featuredIds.length > 0
    ? featuredIds.map(id => PRODUCTS.find(p => p.id === id)).filter(Boolean).slice(0, 8)
    : PRODUCTS.filter((p) => p.badge === "Más vendido" || p.badge === "Top").slice(0, 8);

  const deals = PRODUCTS.filter((p) => p.oldPrice).slice(0, 4);

  // Hero
  const heroTitle    = S('hero_title',    'Todo para tu {coral}regalón{/coral},\nen la puerta de tu casa.');
  const heroSubtitle = S('hero_subtitle', 'Comida, juguetes, salud y mil mimos más. Despacho exprés, suscripción inteligente y veterinario en línea cuando lo necesites.');
  const heroEyebrow  = S('hero_eyebrow',  '🐾 Tienda de mascotas · Chile');
  const heroCta1     = S('hero_cta_text',  'Explorar tienda');
  const heroCta2     = S('hero_cta2_text', 'Ver alimentos');
  const heroCta1Link = S('hero_cta1_link', 'catalog');
  const heroCta2Link = S('hero_cta2_link', 'alimento');
  const heroPetsImg  = S('hero_pets_image', '/hero-pets.png');
  const heroBg       = S('hero_bg', '');
  const heroStats = J('hero_stats', [
    { value: '+25.000', label: 'regalones felices' },
    { value: '24 h',   label: 'despacho exprés' },
    { value: '4.9★',  label: '2.8k reseñas' },
  ]);

  // Renderiza el título del hero con soporte de \n
  function renderHeroTitle(raw) {
    // Si contiene {coral}...{/coral} renderiza con span
    if (raw.includes('{coral}')) {
      const parts = raw.split(/\{coral\}(.*?)\{\/coral\}/g);
      return parts.map((p, i) =>
        i % 2 === 1
          ? <span key={i} className="hl hl-coral">{p}</span>
          : p.split('\n').reduce((acc, line, j) => j === 0 ? [line] : [...acc, <br key={j}/>, line], [])
      );
    }
    return raw.split('\n').reduce((acc, line, j) => j === 0 ? [line] : [...acc, <br key={j}/>, line], []);
  }

  // Valores strip
  const valuesVisible = V('values_visible');
  const valuesItems = J('values_items', [
    { icon: 'truck',   title: 'Despacho 24h',       sub: 'Gratis sobre $30.000' },
    { icon: 'star',    title: 'Productos premium',    sub: 'Marcas seleccionadas' },
    { icon: 'chat',    title: 'Vet en línea',        sub: 'Asesoría 24/7 gratis' },
    { icon: 'shield',  title: 'Compra segura',       sub: 'Devolución en 30 días' },
  ]);

  // Categorías
  const categoriesVisible = V('categories_visible');
  const categoriesEyebrow = S('categories_eyebrow', 'Explora por categoría');
  const categoriesTitle   = S('categories_title', '¿Qué necesita hoy?');

  // Destacados
  const featuredVisible  = V('featured_visible');
  const featuredEyebrow  = S('featured_eyebrow', 'Los favoritos de la manada');
  const featuredTitle    = S('featured_title', 'Más vendidos esta semana');

  // Ofertas
  const dealsVisible  = V('deals_visible');
  const dealsEyebrow  = S('deals_eyebrow', 'Ofertas relámpago');
  const dealsTitle    = S('deals_title', 'Precios de regalón');

  // Testimonios
  const testiVisible  = V('testimonials_visible');
  const testiEyebrow  = S('testimonials_eyebrow', 'Nos quieren (y a sus mascotas también)');
  const testiTitle    = S('testimonials_title', 'Más de 25.000 colas felices');

  // CTA Final
  const ctaVisible = V('cta_visible');
  const ctaTitle   = S('cta_title', '¿Listo para consentir\na tu regalón?');
  const ctaText    = S('cta_text', 'Crea tu cuenta y recibe 15% off en tu primera compra.');
  const ctaBtn1    = S('cta_btn1', 'Empezar a comprar');
  const ctaBtn2    = S('cta_btn2', 'Crear cuenta');

  useReveal("home");

  const bannersPosition = S('banners_position', 'top');

  return (
    <main className="home">
      {bannersVisible && bannersPosition === 'top' && <BannerCarousel go={go} />}

      {/* ===== HERO ===== */}
      <section className="hero" style={heroBg ? { background: heroBg } : {}}>
        <div className="hero-bg-blob hero-blob-1" />
        <div className="hero-bg-blob hero-blob-2" />
        <div className="hero-inner">
          <div className="hero-left">
            <div className="hero-copy">
              {heroEyebrow && <span className="hero-eyebrow-tag fade-up">{heroEyebrow}</span>}
              <h1 className="hero-title fade-up d1">
                {renderHeroTitle(heroTitle)}
              </h1>
              <p className="hero-sub fade-up d2">{heroSubtitle}</p>
              <div className="hero-cta fade-up d3">
                <button className="btn btn-primary btn-lg" onClick={() => {
                  const cat = window.LOMI_DATA.CATEGORIES.find(c => c.id === heroCta1Link || c.name.toLowerCase() === heroCta1Link.toLowerCase());
                  go(cat ? { name:'catalog', category: cat.id } : { name: heroCta1Link || 'catalog' });
                }}>
                  {heroCta1} <Icon name="arrow" size={18} />
                </button>
                <button className="btn btn-ghost btn-lg" onClick={() => {
                  const cat = window.LOMI_DATA.CATEGORIES.find(c => c.id === heroCta2Link || c.name.toLowerCase() === heroCta2Link.toLowerCase());
                  go(cat ? { name:'catalog', category: cat.id } : { name: heroCta2Link || 'catalog' });
                }}>
                  {heroCta2}
                </button>
              </div>
              <div className="hero-stats fade-up d4">
                {heroStats.map((st, i) => (
                  <React.Fragment key={i}>
                    {i > 0 && <div className="hero-stat-div" />}
                    <div><strong>{st.value}</strong><span>{st.label}</span></div>
                  </React.Fragment>
                ))}
              </div>
            </div>
          </div>
          <div className="hero-visual">
            <img src={heroPetsImg} alt="Gatito y perrito Planeta Pet" className="hero-pets-img" />
          </div>
        </div>
        <div className="hero-fade" />
      </section>

      {bannersVisible && bannersPosition === 'below_hero' && <BannerCarousel go={go} />}

      <RenderSections position="after_hero" go={go} addToCart={addToCart} favorites={favorites} onToggleFavorite={onToggleFavorite}/>

      {/* ===== TIRA DE VALORES ===== */}
      {valuesVisible && (
        <section className="valuestrip">
          <div className="wrap valuestrip-grid">
            {valuesItems.map((v, i) => (
              <div className="value-item reveal" key={i} style={{ transitionDelay: i * 0.06 + "s" }}>
                <span className="value-ic"><Icon name={v.icon} size={24} /></span>
                <div><strong>{v.title}</strong><span>{v.sub}</span></div>
              </div>
            ))}
          </div>
        </section>
      )}

      <RenderSections position="after_values" go={go} addToCart={addToCart} favorites={favorites} onToggleFavorite={onToggleFavorite}/>

      {/* ===== CATEGORÍAS ===== */}
      {categoriesVisible && (
        <section className="wrap section">
          <div className="section-head">
            <div>
              <span className="eyebrow">{categoriesEyebrow}</span>
              <h2 className="section-title">{categoriesTitle}</h2>
            </div>
            <button className="link-arrow" onClick={() => go({ name: "catalog" })}>Ver todo <Icon name="arrow" size={16} /></button>
          </div>
          <div className="cat-grid">
            {CATEGORIES.map((c, i) => (
              <button key={c.id} className="cat-card reveal" style={{ transitionDelay: i * 0.05 + 's' }} onClick={() => go({ name: 'catalog', category: c.id })}>
                <div className="cat-card-top" style={{ background: c.tint, color: c.accent }}>
                  <Icon name={c.icon} size={40} stroke={1.4} />
                </div>
                <div className="cat-card-bot">
                  <strong>{c.name}</strong>
                  <span className="cat-sub">{c.sub}</span>
                </div>
              </button>
            ))}
          </div>
        </section>
      )}

      <RenderSections position="after_categories" go={go} addToCart={addToCart} favorites={favorites} onToggleFavorite={onToggleFavorite}/>

      {/* ===== DESTACADOS ===== */}
      {featuredVisible && (
        <section className="wrap section">
          <div className="section-head">
            <div>
              <span className="eyebrow">{featuredEyebrow}</span>
              <h2 className="section-title">{featuredTitle}</h2>
            </div>
            <button className="link-arrow" onClick={() => go({ name: "catalog" })}>Ver catálogo <Icon name="arrow" size={16} /></button>
          </div>
          <div className="prod-grid">
            {featured.map((p, i) => <ProductCard key={p.id} product={p} idx={i} onOpen={(pr) => go({ name: "product", id: pr.id })} onAdd={addToCart} favorites={favorites} onToggleFavorite={onToggleFavorite} />)}
          </div>
        </section>
      )}

      <RenderSections position="after_featured" go={go} addToCart={addToCart} favorites={favorites} onToggleFavorite={onToggleFavorite}/>

      {/* ===== OFERTAS ===== */}
      {dealsVisible && (
        <section className="deals-band">
          <div className="wrap">
            <div className="section-head">
              <div>
                <span className="eyebrow" style={{ color: "var(--teal-deep)" }}><Icon name="bolt" size={14} /> {dealsEyebrow}</span>
                <h2 className="section-title">{dealsTitle}</h2>
              </div>
            </div>
            <div className="prod-grid">
              {deals.map((p, i) => <ProductCard key={p.id} product={p} idx={i} onOpen={(pr) => go({ name: "product", id: pr.id })} onAdd={addToCart} favorites={favorites} onToggleFavorite={onToggleFavorite} />)}
            </div>
          </div>
        </section>
      )}

      <RenderSections position="after_deals" go={go} addToCart={addToCart} favorites={favorites} onToggleFavorite={onToggleFavorite}/>

      {/* ===== TESTIMONIOS ===== */}
      {testiVisible && (
        <section className="wrap section">
          <div className="section-head center">
            <div>
              <span className="eyebrow">{testiEyebrow}</span>
              <h2 className="section-title">{testiTitle}</h2>
            </div>
          </div>
          <div className="testi-grid">
            {TESTIMONIALS.map((t, i) => (
              <div className="testi-card reveal" key={i} style={{ transitionDelay: i * 0.08 + "s" }}>
                <div className="testi-stars"><Stars value={5} size={16} /></div>
                <p>"{t.text}"</p>
                <div className="testi-who">
                  <span className="testi-av" style={{ background: t.tint }}>{t.name[0]}</span>
                  <div><strong>{t.name}</strong><span>{t.pet}</span></div>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}

      <RenderSections position="after_testimonials" go={go} addToCart={addToCart} favorites={favorites} onToggleFavorite={onToggleFavorite}/>

      {/* ===== CTA FINAL ===== */}
      {ctaVisible && (
        <section className="wrap section">
          <div className="final-cta reveal">
            <h2>
              {ctaTitle.split('\n').reduce((acc, line, j) => j === 0 ? [line] : [...acc, <br key={j}/>, line], [])}
            </h2>
            <p>{ctaText}</p>
            <div className="hero-cta">
              <button className="btn btn-primary btn-lg" onClick={() => go({ name: "catalog" })}>
                {ctaBtn1} <Icon name="arrow" size={18} />
              </button>
              <button className="btn btn-dark btn-lg">{ctaBtn2}</button>
            </div>
          </div>
        </section>
      )}
    </main>
  );
}
window.Home = Home;
