// Reusable section components
// THEME_URI is defined globally in data.jsx (loaded before this file)

const useReveal = () => {
  React.useEffect(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          const el = e.target;
          const delay = parseFloat(el.dataset.delay || 0);
          setTimeout(() => el.classList.add('in'), delay * 1000);
          io.unobserve(el);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px 10% 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
};

const BlurText = ({ text, className = '', startDelay = 0, perWord = 0.08 }) => {
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setShown(true), startDelay * 1000);
    return () => clearTimeout(t);
  }, [startDelay]);
  const words = text.split(' ');
  return (
    <span className={className}>
      {words.map((w, i) => (
        <span
          key={i}
          className={`word ${shown ? 'in' : ''}`}
          style={{ transitionDelay: `${i * perWord}s`, whiteSpace: 'pre' }}
        >{w}{i < words.length - 1 ? ' ' : ''}</span>
      ))}
    </span>
  );
};

const Navbar = ({ onContact, activePage = 'inicio' }) => {
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    const close = (e) => {
      if (!e.target.closest('nav.top')) setOpen(false);
    };
    window.addEventListener('click', close);
    return () => window.removeEventListener('click', close);
  }, [open]);

  const ligaHref = activePage === 'inicio' ? '#liga' : '/#liga';

  return (
    <nav className="top">
      <div className="bar">
        <div className="brand">
          <a href="/" style={{display: 'flex', alignItems: 'center'}}>
            <img src={THEME_URI + '/src/images/logo-el-bocha.png'} alt="El Bocha Logo" style={{height: 64, objectFit: 'contain'}}/>
          </a>
        </div>
        <div className="links">
          <a href="/" style={activePage === 'inicio' ? {color:'var(--fg)'} : {}}>Inicio</a>
          <a href="/servicios/" style={activePage === 'servicios' ? {color:'var(--fg)'} : {}}>Servicios</a>
          <a href="/quienes-somos/" style={activePage === 'quienes-somos' ? {color:'var(--fg)'} : {}}>Quienes Somos</a>
        </div>
        <div className="social-links">
          <a href="https://www.instagram.com/agenciaelbocha/" target="_blank" rel="noopener" aria-label="Instagram" className="social-btn"><Icon name="instagram" size={16}/></a>
          <a href="https://www.facebook.com/agenciaelbocha" target="_blank" rel="noopener" aria-label="Facebook" className="social-btn"><Icon name="facebook" size={16}/></a>
          <a href="https://www.tiktok.com/@agenciaelbocha?_r=1&_t=ZS-968a997uLBw" target="_blank" rel="noopener" aria-label="TikTok" className="social-btn"><Icon name="tiktok" size={16}/></a>
        </div>
        <button
          className="nav-hamburger"
          onClick={(e) => { e.stopPropagation(); setOpen(o => !o); }}
          aria-label={open ? 'Cerrar menú' : 'Abrir menú'}
        >
          <Icon name={open ? 'x' : 'menu'} size={16}/>
        </button>
      </div>

      <div className={`nav-mobile-menu ${open ? 'open' : ''}`}>
        <a href="/" className={`nav-mobile-link${activePage === 'inicio' ? ' active' : ''}`} onClick={() => setOpen(false)}>Inicio</a>
        <a href="/servicios/" className={`nav-mobile-link${activePage === 'servicios' ? ' active' : ''}`} onClick={() => setOpen(false)}>Servicios</a>
        <a href="/quienes-somos/" className={`nav-mobile-link${activePage === 'quienes-somos' ? ' active' : ''}`} onClick={() => setOpen(false)}>Quienes Somos</a>
        <div className="nav-mobile-socials">
          <a href="https://www.instagram.com/agenciaelbocha/" target="_blank" rel="noopener" aria-label="Instagram" className="social-btn"><Icon name="instagram" size={16}/></a>
          <a href="https://www.facebook.com/agenciaelbocha" target="_blank" rel="noopener" aria-label="Facebook" className="social-btn"><Icon name="facebook" size={16}/></a>
          <a href="https://www.tiktok.com/@agenciaelbocha?_r=1&_t=ZS-968a997uLBw" target="_blank" rel="noopener" aria-label="TikTok" className="social-btn"><Icon name="tiktok" size={16}/></a>
        </div>
      </div>
    </nav>
  );
};

const Hero = () => {
  const heroTitulo    = (window.WP_DATA && window.WP_DATA.hero_titulo)    ? window.WP_DATA.hero_titulo    : null;
  const heroSubtitulo = (window.WP_DATA && window.WP_DATA.hero_subtitulo) ? window.WP_DATA.hero_subtitulo : null;

  return (
    <section id="inicio" className="hero container">
      <div className="hero-grid">
        <div className="hero-content">
          <div className="meta">
            <div className="reveal" data-delay="0">
              <div className="eyebrow hero-eyebrow" id="hero-eyebrow">Agencia de Marketing y Publicidad</div>
            </div>
          </div>

          <h1>
            {heroTitulo ? (
              <BlurText text={heroTitulo} startDelay={0.2} />
            ) : (
              <>
                <BlurText text="Transformamos tu negocio," startDelay={0.2} />
                <br/>
                <BlurText text="incrementamos tus" startDelay={0.5} />
                {' '}
                <BlurText text="ventas." startDelay={0.9} />
              </>
            )}
          </h1>

          <p className="lede reveal" data-delay="1.4">
            {heroSubtitulo || 'Estrategias digitales, publicidad radial y presencia de marca para empresas que quieren crecer.'}
          </p>

          <div className="ctas reveal" data-delay="1.6">
            <a href={`https://wa.me/593991810190?text=${encodeURIComponent('Hola, quiero más información sobre los servicios de Agencia El Bocha.')}`} target="_blank" rel="noopener" className="btn btn-red">
              <span className="dot"></span>
              WhatsApp directo
              <img src={THEME_URI + '/src/images/Logo_Whatsapp_CTA.png'} alt="WhatsApp" style={{height: '15px', width: 'auto'}}/>
            </a>
            <a href="/servicios/" className="btn">
              Ver servicios <Icon name="arrow-right" size={16}/>
            </a>
          </div>
        </div>

        <div className="hero-ceo reveal" data-delay="1.2">
          <img src={THEME_URI + '/src/images/CEO-hero-bocha.png'} alt="CEO Ing. Edison Ramírez" className="ceo-image"/>
          <div className="ceo-caption">CEO — Ing. EDISON "BOCHA" RAMÍREZ</div>
        </div>
      </div>
    </section>
  );
};

const Services = ({ onOpen }) => (
  <section id="servicios" className="container">
    <div className="section-hd">
      <div className="lhs reveal">
        <span className="num">01 — Servicios</span>
        <h2>Lo que hacemos,<br/><span className="serif">en orden de impacto.</span></h2>
      </div>
      <div className="rhs reveal" data-delay="0.15">
        <p>Cinco prácticas con un mismo propósito: que tu marca sea reconocible, recordable y elegida. Cada servicio se vende solo y se integra con los demás.</p>
      </div>
    </div>
    <div className="services-list">
      {SERVICES.map((s, i) => (
        <div key={s.id} className="service-card reveal" data-delay={i * 0.08}>
          <div className="service-grid">

            {/* IZQUIERDA — título + mini-grid de sub-servicios + CTA */}
            <div className="service-left">
              <div className="svc-header">
                <span className="svc-num">{s.num}</span>
                <h3>{s.title} {s.titleItalic}</h3>
              </div>

              <div className="svc-mini-grid">
                {s.services.map((srv, j) => (
                  <div key={j} className="svc-mini-card">
                    <div className="svc-mini-top">
                      <span className="svc-mini-num">0{j + 1}</span>
                      <Icon name={srv.icon} size={16} stroke={1.4}/>
                    </div>
                    <div className="svc-mini-name">{srv.name}</div>
                    <div className="svc-mini-desc">{srv.desc}</div>
                  </div>
                ))}
              </div>

              <a href={`/servicios/#${s.id}`} className="btn svc-cta">
                Saber más <Icon name="arrow-right" size={15}/>
              </a>
            </div>

            {/* DERECHA — imagen */}
            <div className="service-right">
              <img src={s.image} alt={s.title} className="service-image"/>
            </div>

          </div>
        </div>
      ))}
    </div>
  </section>
);

const LduSection = ({ onOpen }) => (
  <section id="liga" className="container">
    <div className="ldu-card reveal">
      <div className="ldu-grid">
        <div>
          <div className="niche-badge">
            <span className="pulse"></span>
            Nicho deportivo · Producto estrella
          </div>
          <h2>
            Va por ti,<br/>
            Liga.
          </h2>
          <p style={{fontSize: 17, textAlign: 'justify'}}>
            Una revista mensual sobre Liga Deportiva Universitaria, distribuida directamente vía WhatsApp a
            <strong style={{color:'var(--fg)'}}> 9,500 hinchas autoidentificados.</strong> Tu marca dentro del contexto editorial que la audiencia abre porque quiere — no porque le interrumpe.
          </p>
          <div className="stats">
            <div>
              <div className="v">9.5K</div>
              <div className="l">Hinchas activos</div>
            </div>
            <div>
              <div className="v">71<span style={{fontSize:'.55em', color:'var(--fg-dim)'}}>%</span></div>
              <div className="l">Tasa apertura</div>
            </div>
            <div>
              <div className="v">3</div>
              <div className="l">Formatos pauta</div>
            </div>
          </div>
          <div className="ctas">
            <a className="btn btn-red" onClick={() => onOpen(SERVICES[5])}>
              Ver paquetes <Icon name="arrow-right" size={15}/>
            </a>
            <a className="btn">Saber más</a>
          </div>
        </div>

        <div className="mag-stage">
          <div className="mag">
            <div className="mag-tt">
              <span>N° 47 · Mayo 2026</span>
              <span>USD 0.00</span>
            </div>
            <div className="mag-title">
              <span className="red">Va por ti</span>
              Liga.
            </div>
            <div className="mag-photo"></div>
            <div className="mag-headline">"Un equipo, un país, una historia que aún se escribe."</div>
            <div className="mag-foot">
              <span className="ed">edición especial</span>
              <span>el bocha · 047</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
);

const StatsBlock = () => (
  <section id="track-record" className="container">
    <div className="section-hd">
      <div className="lhs reveal">
        <span className="num">02 — Track record</span>
        <h2>Nueve años<br/>transformando marcas</h2>
      </div>
    </div>
    <div className="stats-card reveal">
      {STATS.map((s, i) => (
        <div className="stat" key={i}>
          <div className="v">{s.v}<span className="small">{s.sub}</span></div>
          <div className="l">{s.l}</div>
        </div>
      ))}
    </div>

    <div className="testi-track">
      {TESTIMONIALS.map((t, i) => (
        <div key={i} className="liquid-glass testi reveal" data-delay={i * 0.08}>
          <div className="quote">{t.quote}</div>
          <div className="by">
            <div className="av">{t.initial}</div>
            <div className="who">
              <b>{t.name}</b>
              <span>{t.role}</span>
            </div>
          </div>
        </div>
      ))}
    </div>

    <div className="logos-carousel reveal" style={{marginTop: 48}}>
      <div className="carousel-strip">
        {[...LOGOS, ...LOGOS].map((logo, i) => (
          <div key={i} className="carousel-item">
            <img src={logo} alt="Logo marca" />
          </div>
        ))}
      </div>
    </div>
  </section>
);

const Conversion = () => {
  const [form, setForm] = React.useState({ name: '', service: '', message: '' });
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);

  const submit = (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = 'Cuéntanos cómo te llamas.';
    if (!form.service) errs.service = 'Elige un servicio.';
    if (form.message.trim().length < 10) errs.message = 'Un poco más de contexto, por favor.';
    setErrors(errs);
    if (Object.keys(errs).length) return;

    const txt = `Hola, soy ${form.name}. Me interesa: ${form.service}. ${form.message}`;
    const url = `https://wa.me/593991810190?text=${encodeURIComponent(txt)}`;
    window.open(url, '_blank');
    setSent(true);
    setTimeout(() => setSent(false), 4000);
  };

  return (
    <section className="container">
      <div className="conv reveal">
        <div className="conv-grid">
          <div>
            <div className="eyebrow" style={{marginBottom: 22}}>04 — Hablemos</div>
            <h2>¿Listo para<br/>transformar<br/>tu negocio?</h2>
            <p style={{marginTop: 28, maxWidth: '40ch'}}>Cuéntanos en una línea qué necesitas y te respondemos por WhatsApp en menos de 24 horas hábiles. Sin formularios eternos, sin tickets.</p>
            <div style={{marginTop: 40, display:'flex', flexDirection:'column', gap: 14, color:'var(--fg-dim)', fontSize: 14.5}}>
              <div style={{display:'flex', gap:12, alignItems:'center'}}><Icon name="pin" size={16}/> Av. París N41-164 e Isla Floreana, Quito – Ecuador</div>
              <div style={{display:'flex', gap:12, alignItems:'center'}}><Icon name="mail" size={16}/> info@agenciaelbocha.com</div>
              <div style={{display:'flex', gap:12, alignItems:'center'}}><Icon name="whatsapp" size={16}/> +593 99 181 0190</div>
            </div>
          </div>
          <form onSubmit={submit}>
            <div className="field">
              <label>Nombre</label>
              <input type="text" value={form.name} onChange={e => setForm({...form, name: e.target.value})} placeholder="Tu nombre completo"/>
              {errors.name && <span className="err">{errors.name}</span>}
            </div>
            <div className="field">
              <label>Servicio de interés</label>
              <select value={form.service} onChange={e => setForm({...form, service: e.target.value})}>
                <option value="">Selecciona un servicio</option>
                {SERVICES.map(s => <option key={s.id} value={`${s.title} ${s.titleItalic}`}>{s.title} {s.titleItalic}</option>)}
                <option value="Otro / no estoy seguro">Otro / no estoy seguro</option>
              </select>
              {errors.service && <span className="err">{errors.service}</span>}
            </div>
            <div className="field">
              <label>Mensaje</label>
              <textarea value={form.message} onChange={e => setForm({...form, message: e.target.value})} placeholder="Cuéntanos brevemente sobre tu negocio y qué buscas lograr."></textarea>
              {errors.message && <span className="err">{errors.message}</span>}
            </div>
            <button type="submit" className="btn btn-red" style={{width:'100%', justifyContent:'center', marginTop: 8}}>
              {sent ? 'Abriendo WhatsApp…' : 'Enviar por WhatsApp'} <img src={THEME_URI + '/src/images/Logo_Whatsapp_CTA.png'} alt="WhatsApp" style={{height: '15px', width: 'auto'}}/>
            </button>
          </form>
        </div>
      </div>
    </section>
  );
};

const Footer = () => {
  const isHome = window.location.pathname === '/';
  const trackRecordHref = isHome ? '#track-record' : '/#track-record';
  const handleTrackRecord = (e) => {
    if (!isHome) return;
    e.preventDefault();
    const el = document.getElementById('track-record');
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 90, behavior: 'smooth' });
  };
  return (
  <footer className="bottom container">
    <div className="row">
      <div className="brandblock">
        <a href="/">
          <img src={THEME_URI + '/src/images/logo-el-bocha.png'} alt="El Bocha" style={{height: 70, objectFit: 'contain'}}/>
        </a>
        <p>Agencia de marketing en Quito. Estrategia, presencia y conversión para empresas que crecen.</p>
        <div style={{display:'flex', gap: 14, marginTop: 6}}>
          <a href="https://www.instagram.com/agenciaelbocha/" target="_blank" rel="noopener" aria-label="Instagram" className="social-btn"><Icon name="instagram" size={16}/></a>
          <a href="https://www.facebook.com/agenciaelbocha" target="_blank" rel="noopener" aria-label="Facebook" className="social-btn"><Icon name="facebook" size={16}/></a>
          <a href="https://www.tiktok.com/@agenciaelbocha?_r=1&_t=ZS-968a997uLBw" target="_blank" rel="noopener" aria-label="TikTok" className="social-btn"><Icon name="tiktok" size={16}/></a>
        </div>
      </div>
      <div>
        <h4>Servicios</h4>
        <div className="lk">
          {SERVICES.slice(0,5).map(s => <a key={s.id} href={`/servicios/#${s.id}`}>{s.title} {s.titleItalic}</a>)}
        </div>
      </div>
      <div>
        <h4>Estudio</h4>
        <div className="lk">
          <a href="/quienes-somos/">Quienes Somos</a>
          <a href={trackRecordHref} onClick={handleTrackRecord}>Casos de Éxito</a>
        </div>
      </div>
      <div>
        <h4>Contacto</h4>
        <div className="lk">
          <a href="https://www.instagram.com/yosoyelbocha/" target="_blank" rel="noopener">Ing. Edison Ramírez</a>
          <span style={{color:'var(--fg-dim)', fontSize:14}}>Av. París N41-164 e Isla Floreana</span>
          <span style={{color:'var(--fg-dim)', fontSize:14}}>gerenciageneral@agenciaelbocha.com</span>
          <a href="/politica-de-privacidad/">Política de Privacidad</a>
        </div>
      </div>
    </div>
    <div className="legal">
      <span>© 2026 el bocha · Todos los derechos reservados</span>
      <span>Diseñado en Quito · 0°S</span>
    </div>
  </footer>
  );
};

const ServiceModal = ({ svc, onClose }) => {
  React.useEffect(() => {
    const onEsc = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onEsc);
    return () => document.removeEventListener('keydown', onEsc);
  }, [onClose]);

  if (!svc) return null;

  const hasDetails = svc.details && Object.keys(svc.details).length > 0;

  return (
    <div className={`modal-bg ${svc ? 'open' : ''}`} onClick={onClose}>
      {svc && (
        <div className="service-modal" onClick={e => e.stopPropagation()}>
          <button className="x" onClick={onClose}>×</button>
          <div className="service-modal-header">
            <div className="num">{svc.num} — {svc.tag}</div>
            <h2>{svc.title} {svc.titleItalic}</h2>
          </div>

          {hasDetails ? (
            <div className="service-details">
              {Object.entries(svc.details).map(([key, desc], i) => (
                <div key={i} className="detail-section">
                  <h3>{key}</h3>
                  <p>{desc}</p>
                </div>
              ))}
            </div>
          ) : (
            <>
              <p className="lede">{svc.long}</p>
              <h4>Qué incluye</h4>
              <ul>
                {svc.bullets && svc.bullets.map((b, i) => <li key={i}>{b}</li>)}
              </ul>
            </>
          )}

          <div className="row-act">
            <a className="btn btn-red" href={`https://wa.me/593991810190?text=${encodeURIComponent('Hola, quiero cotizar el servicio de ' + svc.title + ' ' + svc.titleItalic + ' con Agencia El Bocha.')}`} target="_blank" rel="noopener">
              <span className="dot"></span>
              Cotizar por WhatsApp
              <img src={THEME_URI + '/src/images/Logo_Whatsapp_CTA.png'} alt="WhatsApp" style={{height: '15px', width: 'auto'}}/>
            </a>
            <button className="btn" onClick={onClose}>Cerrar</button>
          </div>
        </div>
      )}
    </div>
  );
};

const QuienesSomos = () => (
  <section id="nosotros" className="container">
    <div className="section-hd">
      <div className="lhs reveal">
        <span className="num">03 — Quiénes somos</span>
        <h2>El equipo<br/><span className="serif">detrás del resultado.</span></h2>
      </div>
      <div className="rhs reveal" data-delay="0.1">
        <p>Más de 10 años construyendo marcas en Ecuador. Somos estrategas, creativos y comunicadores con un solo norte: que tu inversión regrese multiplicada.</p>
      </div>
    </div>

    <div className="qs-home-grid">
      <div className="qs-home-ceo reveal" data-delay="0.05">
        <img src={THEME_URI + '/src/images/Equipo-landing-page.png'} alt="Equipo Agencia El Bocha" className="qs-home-ceo-img"/>
      </div>
      <div className="qs-home-values">
        {VALUES.map((v, i) => (
          <div key={i} className="qs-home-value liquid-glass reveal" data-delay={0.08 + i * 0.08}>
            <span className="qs-home-val-num">{v.num}</span>
            <div>
              <div className="qs-home-val-name">{v.name}</div>
              <div className="qs-home-val-desc">{v.desc}</div>
            </div>
          </div>
        ))}
        <a href="/quienes-somos/" className="btn reveal" style={{marginTop:24}} data-delay="0.32">
          Conocer el equipo <Icon name="arrow-right" size={14}/>
        </a>
      </div>
    </div>
  </section>
);

const WaFloat = () => (
  <a className="wa-float" href={`https://wa.me/593991810190?text=${encodeURIComponent('Hola, me gustaría obtener más información sobre los servicios de Agencia El Bocha.')}`} target="_blank" rel="noopener" aria-label="WhatsApp">
    <img src={THEME_URI + '/src/images/Logo_Whatsapp_Chat.png'} alt="WhatsApp" style={{width: '40px', height: '40px', objectFit: 'contain'}}/>
  </a>
);

Object.assign(window, { useReveal, BlurText, Navbar, Hero, Services, LduSection, StatsBlock, QuienesSomos, Conversion, Footer, ServiceModal, WaFloat });
