// ============================================
// Sections — Grupo Luna
// ============================================
const { useEffect: useEffect2, useRef: useRef2, useState: useState2 } = React;

// ---- Reveal hook: adds .in class when scrolled into view ----
function useReveal() {
  useEffect2(() => {
    const els = document.querySelectorAll('[data-reveal]');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -80px 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
}

// ---- Counter ----
function Counter({ to, suffix = '', plus = false, duration = 1800 }) {
  const ref = useRef2(null);
  const [val, setVal] = useState2(0);

  useEffect2(() => {
    if (!ref.current) return;
    let raf;
    const io = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        const start = performance.now();
        const tick = (t) => {
          const p = Math.min(1, (t - start) / duration);
          const eased = 1 - Math.pow(1 - p, 3);
          setVal(Math.round(to * eased));
          if (p < 1) raf = requestAnimationFrame(tick);
        };
        raf = requestAnimationFrame(tick);
        io.disconnect();
      }
    }, { threshold: 0.4 });
    io.observe(ref.current);
    return () => { io.disconnect(); cancelAnimationFrame(raf); };
  }, [to, duration]);

  return (
    <span ref={ref} className="mono">
      {plus && <span className="plus">+</span>}
      {val}
      {suffix && <span className="suffix">{suffix}</span>}
    </span>
  );
}

// ---- HERO ----
function Hero({ t, variant, scrollY, mouseX, mouseY }) {
  return (
    <section id="inicio" className="hero" data-variant={variant}>
      <div className="hero-grid"></div>
      <AmbientCubes scrollY={scrollY} />

      <div className="wrap hero-content">
        <div className="hero-text">
          <div className="eyebrow hero-eyebrow" data-reveal>{t.hero.eyebrow}</div>
          <h1 className="hero-title" data-reveal style={{ '--reveal-delay': '0.1s' }}>
            {t.hero.titleA} <em><TextMorph words={t.hero.titleB_words} speed={3000} typingSpeed={100} /></em><br />
            <b>{t.hero.titleC}</b>
          </h1>
          <p className="hero-sub" data-reveal style={{ '--reveal-delay': '0.25s' }}>
            {t.hero.sub}
          </p>

          <div className="hero-cta" data-reveal style={{ '--reveal-delay': '0.4s' }}>
            <MagneticBtn href="#contacto" className="btn btn-primary">
              {t.hero.ctaPrimary}
              <svg className="arrow" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
                <path d="M3 8h10M9 4l4 4-4 4" />
              </svg>
            </MagneticBtn>
            <MagneticBtn href="#proyectos" className="btn btn-ghost">
              {t.hero.ctaSecondary}
            </MagneticBtn>
          </div>

          <div className="hero-meta" data-reveal style={{ '--reveal-delay': '0.55s' }}>
            <div className="hero-meta-item">
              <span className="num">+<b><Counter to={30} /></b></span>
              <span className="lbl">{t.hero.metaAlbl}</span>
            </div>
            <div className="hero-meta-item">
              <span className="num">+<b><Counter to={50} /></b></span>
              <span className="lbl">{t.hero.metaBlbl}</span>
            </div>
            <div className="hero-meta-item">
              <span className="num">+<b><Counter to={15} /></b></span>
              <span className="lbl">{t.hero.metaClbl}</span>
            </div>
          </div>
        </div>

        <BrandCube scrollY={scrollY} mouseX={mouseX} mouseY={mouseY} />
      </div>

      <div className="scroll-hint">
        <span>{t.hero.scrollHint}</span>
        <div className="line"></div>
      </div>
    </section>
  );
}

// ---- NOSOTROS ----
function Nosotros({ t }) {
  const valueIcons = [
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><circle cx="6" cy="6" r="2"/><circle cx="18" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="18" r="2"/><path d="M8 6h8M6 8v8M18 8v8M8 18h8"/></svg>,
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M3 3v18h18"/><path d="M7 14l4-4 4 4 5-7"/></svg>,
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/></svg>,
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="4" y="4" width="6" height="6"/><rect x="14" y="4" width="6" height="6"/><rect x="4" y="14" width="6" height="6"/><rect x="14" y="14" width="6" height="6"/></svg>,
  ];

  return (
    <section id="nosotros" className="nosotros">
      <div className="wrap nosotros-grid">
        <div className="nosotros-text">
          <div className="eyebrow" data-reveal>{t.nosotros.num}</div>
          <h2 data-reveal style={{ marginTop: 24 }}>
            {t.nosotros.h2A} <b>{t.nosotros.h2B}</b><br />
            <span style={{ fontWeight: 300, color: 'var(--text-soft)' }}>{t.nosotros.h2C}</span>
          </h2>
          <WordReveal as="p" className="nos-para" delay={100} stagger={28}>{t.nosotros.p1}</WordReveal>
          <WordReveal as="p" className="nos-para" delay={200} stagger={22}>{t.nosotros.p2}</WordReveal>
        </div>

        <div className="values-grid" data-reveal style={{ '--reveal-delay': '0.15s' }}>
          {[
            ['v1t','v1d'],['v2t','v2d'],['v3t','v3d'],['v4t','v4d']
          ].map(([k, dk], i) => (
            <div className="value" key={i}>
              <div className="ico">{valueIcons[i]}</div>
              <h4>{t.nosotros[k]}</h4>
              <p>{t.nosotros[dk]}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---- SERVICIOS ----
function Servicios({ t }) {
  return (
    <section id="servicios" className="servicios">
      <div className="wrap">
        <div className="sec-head">
          <div>
            <div className="eyebrow" data-reveal>{t.servicios.num}</div>
            <h2 data-reveal style={{ marginTop: 16 }}>
              {t.servicios.h2A}<br /><b>{t.servicios.h2B}</b>
            </h2>
          </div>
          <p className="lead" data-reveal style={{ '--reveal-delay': '0.15s' }}>{t.servicios.lead}</p>
        </div>

        <div className="servicios-list">
          {t.servicios.items.map((s, i) => (
            <div className="servicio" key={i} data-reveal style={{ '--reveal-delay': `${0.05 * i}s` }}>
              <div className="s-num">0{i + 1}</div>
              <div className="s-title">{s.title} <b>{s.titleB}</b></div>
              <div className="s-desc">{s.desc}</div>
              <div className="s-arrow">→</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---- PROYECTO CARRUSEL ----
function ProyectoCarrusel({ t }) {
  const slides = [
    { src: 'assets/proyecto-jujuy-obra.webp',  label: t.proyectos.p4slide1 },
    { src: 'assets/proyecto-jujuy-final.webp', label: t.proyectos.p4slide2 },
  ];
  const [idx, setIdx] = useState2(0);
  const [prev, setPrev] = useState2(null);
  const [dir, setDir] = useState2(1);

  const goTo = (next) => {
    if (next === idx) return;
    setDir(next > idx ? 1 : -1);
    setPrev(idx);
    setIdx(next);
    setTimeout(() => setPrev(null), 600);
  };

  // Auto-advance
  useEffect2(() => {
    const t = setInterval(() => goTo((idx + 1) % slides.length), 5000);
    return () => clearInterval(t);
  }, [idx]);

  return (
    <div className="proyecto proyecto-4" data-reveal style={{ '--reveal-delay': '0.3s', position: 'relative', overflow: 'hidden' }}>
      {/* Slides */}
      {slides.map((s, i) => (
        <img
          key={i}
          src={s.src}
          alt={s.label}
          style={{
            position: 'absolute',
            inset: 0,
            width: '100%',
            height: '100%',
            objectFit: 'cover',
            transition: 'opacity 0.7s ease, transform 1.4s cubic-bezier(.2,.7,.2,1)',
            opacity: i === idx ? 1 : 0,
            transform: i === idx ? 'scale(1.04)' : 'scale(1)',
            zIndex: i === idx ? 2 : 1,
            filter: 'saturate(0.88) brightness(0.9)',
          }}
        />
      ))}

      {/* Overlay */}
      <div className="proyecto-overlay" style={{ zIndex: 3 }}>
        <div className="proyecto-tag">{t.proyectos.p4tag}</div>
        <div className="proyecto-title">{t.proyectos.p4title}</div>
        <div className="proyecto-loc">{t.proyectos.p4loc}</div>
      </div>

      {/* Slide label badge */}
      <div style={{
        position: 'absolute',
        top: 20, right: 20,
        zIndex: 4,
        background: 'rgba(255,255,255,0.12)',
        backdropFilter: 'blur(12px)',
        WebkitBackdropFilter: 'blur(12px)',
        border: '1px solid rgba(255,255,255,0.2)',
        borderRadius: 999,
        padding: '6px 14px',
        fontSize: 11,
        fontWeight: 600,
        letterSpacing: '0.12em',
        textTransform: 'uppercase',
        color: 'white',
        transition: 'opacity .4s',
      }}>
        {slides[idx].label}
      </div>

      {/* Arrows */}
      <button
        onClick={() => goTo((idx - 1 + slides.length) % slides.length)}
        style={arrowStyle('left')}
        aria-label="Anterior"
      >
        <svg viewBox="0 0 16 16" fill="none" stroke="white" strokeWidth="1.5" style={{width:16,height:16}}>
          <path d="M10 4L6 8l4 4"/>
        </svg>
      </button>
      <button
        onClick={() => goTo((idx + 1) % slides.length)}
        style={arrowStyle('right')}
        aria-label="Siguiente"
      >
        <svg viewBox="0 0 16 16" fill="none" stroke="white" strokeWidth="1.5" style={{width:16,height:16}}>
          <path d="M6 4l4 4-4 4"/>
        </svg>
      </button>

      {/* Dots */}
      <div style={{
        position: 'absolute',
        bottom: 20, left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 4,
        display: 'flex',
        gap: 8,
      }}>
        {slides.map((_, i) => (
          <button
            key={i}
            onClick={() => goTo(i)}
            style={{
              width: i === idx ? 22 : 8,
              height: 8,
              borderRadius: 999,
              border: 0,
              background: i === idx ? '#00a2e2' : 'rgba(255,255,255,0.4)',
              cursor: 'pointer',
              padding: 0,
              transition: 'width .4s cubic-bezier(.2,.7,.2,1), background .3s',
            }}
            aria-label={`Imagen ${i + 1}`}
          />
        ))}
      </div>
    </div>
  );
}

function arrowStyle(side) {
  return {
    position: 'absolute',
    top: '50%',
    [side]: 16,
    transform: 'translateY(-50%)',
    zIndex: 4,
    background: 'rgba(255,255,255,0.1)',
    backdropFilter: 'blur(12px)',
    WebkitBackdropFilter: 'blur(12px)',
    border: '1px solid rgba(255,255,255,0.2)',
    borderRadius: '50%',
    width: 40,
    height: 40,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    cursor: 'pointer',
    transition: 'background .25s, transform .25s',
  };
}

// ---- PROYECTOS ----
function Proyectos({ t }) {
  return (
    <section id="proyectos" className="proyectos">
      <div className="wrap">
        <div className="sec-head">
          <div>
            <div className="eyebrow" data-reveal>{t.proyectos.num}</div>
            <h2 data-reveal style={{ marginTop: 16 }}>
              {t.proyectos.h2A} <b>{t.proyectos.h2B}</b><br />
              <span style={{ fontWeight: 200, opacity: 0.8 }}>{t.proyectos.h2C}</span>
            </h2>
          </div>
          <p className="lead" data-reveal style={{ '--reveal-delay': '0.15s' }}>{t.proyectos.lead}</p>
        </div>

        <div className="proyecto-grid">
          <div className="proyecto proyecto-1" data-reveal>
            <img src="assets/proyecto-farmacia.png" alt="Farmacia La Esquina" />
            <div className="proyecto-overlay">
              <div className="proyecto-tag">{t.proyectos.p1tag}</div>
              <div className="proyecto-title">{t.proyectos.p1title}</div>
              <div className="proyecto-loc">{t.proyectos.p1loc}</div>
            </div>
          </div>

          <div className="proyecto proyecto-2" data-reveal style={{ '--reveal-delay': '0.1s' }}>
            <img src="assets/proyecto-quimsa.jpg" alt="Club Quimsa" />
            <div className="proyecto-overlay">
              <div className="proyecto-tag">{t.proyectos.p2tag}</div>
              <div className="proyecto-title">{t.proyectos.p2title}</div>
              <div className="proyecto-loc">{t.proyectos.p2loc}</div>
            </div>
          </div>

          <div className="proyecto proyecto-3" data-reveal style={{ '--reveal-delay': '0.2s' }}>
            <img src="assets/proyecto-quinta.jpg" alt="Quinta Tres Algarrobos" />
            <div className="proyecto-overlay">
              <div className="proyecto-tag">{t.proyectos.p3tag}</div>
              <div className="proyecto-title">{t.proyectos.p3title}</div>
              <div className="proyecto-loc">{t.proyectos.p3loc}</div>
            </div>
          </div>

          <ProyectoCarrusel t={t} data-reveal style={{ '--reveal-delay': '0.3s' }} />
        </div>
      </div>
    </section>
  );
}

// ---- STATS ----
function Stats({ t, scrollY }) {
  return (
    <section id="stats" className="stats">
      <div className="stats-hex-bg"></div>
      <div className="stats-cubes" style={{ transform: `translateY(calc(-50% + ${scrollY * -0.05}px)) rotate(${scrollY * 0.02}deg)` }}>
        <img src="assets/cube-blue.png" alt="" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
      </div>

      <div className="wrap">
        <div className="sec-head">
          <div>
            <div className="eyebrow" data-reveal>{t.stats.num}</div>
            <h2 data-reveal style={{ marginTop: 16 }}>
              {t.stats.h2A} <b>{t.stats.h2B}</b><br />
              <span style={{ fontWeight: 200, color: 'var(--text-soft)' }}>{t.stats.h2C}</span>
            </h2>
          </div>
          <p className="lead" data-reveal style={{ '--reveal-delay': '0.15s' }}>{t.stats.lead}</p>
        </div>

        <div className="stats-grid">
          <div className="stat" data-reveal>
            <div className="stat-num"><Counter to={30} plus duration={1500} /></div>
            <div className="stat-lbl">{t.stats.s1l}</div>
          </div>
          <div className="stat" data-reveal style={{ '--reveal-delay': '0.08s' }}>
            <div className="stat-num"><Counter to={50} plus duration={1700} /></div>
            <div className="stat-lbl">{t.stats.s2l}</div>
          </div>
          <div className="stat" data-reveal style={{ '--reveal-delay': '0.16s' }}>
            <div className="stat-num"><Counter to={15} plus duration={1500} /></div>
            <div className="stat-lbl">{t.stats.s3l}</div>
          </div>
          <div className="stat" data-reveal style={{ '--reveal-delay': '0.24s' }}>
            <div className="stat-num"><Counter to={8} plus duration={1300} /></div>
            <div className="stat-lbl">{t.stats.s4l}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---- CLIENTES ----
function Clientes({ t }) {
  const clients = [
    { mark: 'Q',  name: 'Club Quimsa' },
    { mark: 'LE', name: 'La Esquina' },
    { mark: 'M',  name: 'Municipalidad SdE' },
    { mark: 'TR', name: 'Tres Algarrobos' },
    { mark: 'GP', name: 'Gob. Pcia. Santiago' },
    { mark: 'TH', name: 'Termas Río Hondo' },
    { mark: 'C',  name: 'Constructora Norte' },
    { mark: 'A',  name: 'Aguas Santiagueñas' },
    { mark: 'F',  name: 'Forestal SA' },
    { mark: 'IN', name: 'INTA Regional' },
  ];

  return (
    <section id="clientes" className="clientes">
      <div className="wrap">
        <div className="sec-head" style={{ marginBottom: 48 }}>
          <div>
            <div className="eyebrow" data-reveal>{t.clientes.num}</div>
            <h2 data-reveal style={{ marginTop: 16 }}>
              {t.clientes.h2A}<br /><b>{t.clientes.h2B}</b>
            </h2>
          </div>
          <p className="lead" data-reveal style={{ '--reveal-delay': '0.15s' }}>{t.clientes.lead}</p>
        </div>
      </div>

      <div className="client-marquee">
        <div className="client-track">
          {[...clients, ...clients].map((c, i) => (
            <div className="client-logo" key={i}>
              <span className="mark">{c.mark}</span>
              <span>{c.name}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---- CONTACTO ----
function Contacto({ t }) {
  const [sent, setSent] = useState2(false);
  const submit = (e) => {
    e.preventDefault();
    setSent(true);
  };

  return (
    <section id="contacto" className="contacto">
      <div className="wrap contacto-grid">
        <div className="contacto-text">
          <div className="eyebrow" data-reveal style={{ color: 'var(--blue-sky)' }}>{t.contacto.num}</div>
          <h2 data-reveal style={{ marginTop: 24 }}>
            {t.contacto.h2A} <b>{t.contacto.h2B}</b>{t.contacto.h2C}
          </h2>
          <p className="lead" data-reveal style={{ '--reveal-delay': '0.1s' }}>{t.contacto.lead}</p>

          <div className="contact-list" data-reveal style={{ '--reveal-delay': '0.2s' }}>
            <a className="contact-item" href="mailto:grupoluna.consultora@gmail.com">
              <span className="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="5" width="18" height="14"/><path d="M3 7l9 7 9-7"/></svg></span>
              grupoluna.consultora@gmail.com
            </a>
            <a className="contact-item" href="tel:+543854339504">
              <span className="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 4h4l2 5-3 2a12 12 0 006 6l2-3 5 2v4a2 2 0 01-2 2A18 18 0 013 6a2 2 0 012-2z"/></svg></span>
              +54 385 433-9504
            </a>
            <a className="contact-item" href="https://www.google.com/maps/place/Grupo+Luna+%7C+Ingenieria+%26+Arquitectura/@-27.7915605,-64.2580127,1171m/data=!3m1!1e3!4m15!1m8!3m7!1s0x943b520feb7f03bd:0x910f2fe5550a081e!2sIndependencia+487,+G4204+Santiago+del+Estero!3b1!8m2!3d-27.7915605!4d-64.2554378!16s%2Fg%2F11jdlb8xnz!3m5!1s0x943b5390aeb6e82f:0x32e40e521e5bc434!8m2!3d-27.7915605!4d-64.2554378!16s%2Fg%2F11z2c3ympc?entry=ttu&g_ep=EgoyMDI2MDUxMi4wIKXMDSoASAFQAw%3D%3D" target="_blank" rel="noopener">
              <span className="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 22s8-7 8-13a8 8 0 10-16 0c0 6 8 13 8 13z"/><circle cx="12" cy="9" r="3"/></svg></span>
              {t.contacto.addr}
            </a>
            <a className="contact-item" href="https://instagram.com/grupoluna.consultora" target="_blank" rel="noopener">
              <span className="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="4"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r=".5" fill="currentColor"/></svg></span>
              {t.contacto.ig}
            </a>
          </div>
        </div>

        <div className="form" data-reveal style={{ '--reveal-delay': '0.2s' }}>
          {sent ? (
            <div className="form-success">
              <h3>{t.contacto.form.sent}</h3>
              <p>{t.contacto.form.sentMsg}</p>
            </div>
          ) : (
            <form onSubmit={submit}>
              <h3>{t.contacto.form.title}</h3>
              <div className="form-row">
                <div className="field">
                  <label>{t.contacto.form.name}</label>
                  <input type="text" required />
                </div>
                <div className="field">
                  <label>{t.contacto.form.phone}</label>
                  <input type="tel" />
                </div>
              </div>
              <div className="field">
                <label>{t.contacto.form.email}</label>
                <input type="email" required />
              </div>
              <div className="field">
                <label>{t.contacto.form.type}</label>
                <select required defaultValue="">
                  {t.contacto.form.typeOpts.map((opt, i) => (
                    <option key={i} value={i === 0 ? '' : opt} disabled={i === 0}>{opt}</option>
                  ))}
                </select>
              </div>
              <div className="field">
                <label>{t.contacto.form.message}</label>
                <textarea required rows="3" />
              </div>
              <button type="submit" className="btn-submit">
                {t.contacto.form.submit}
                <svg className="arrow" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" style={{width:16,height:16}}>
                  <path d="M3 8h10M9 4l4 4-4 4" />
                </svg>
              </button>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, Nosotros, Servicios, Proyectos, Stats, Clientes, Contacto, useReveal });
