/* ============ VETRA — Section components ============ */
const LOGO = "assets/vetra-logo.svg";

/* ---------- NAVBAR ---------- */
function Navbar({ t, lang, setLang }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const on = () => setScrolled(window.scrollY > 12);
    on();window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "")}>
      <div className="wrap nav-inner">
        <a href="#top"><img className="nav-logo" src="assets/vetra-logo.svg" alt="VETRA" /></a>
        <div className="nav-links">
          <a href="#producto">{t.nav.product}</a>
          <a href="#modulos">{t.nav.modules}</a>
          <a href="#como">{t.nav.how}</a>
        </div>
        <div className="nav-right">
          <div className="lang" role="group" aria-label="Language">
            <button className={lang === "es" ? "on" : ""} onClick={() => setLang("es")}>ES</button>
            <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
          </div>
          <a href="#demo" className="btn btn-primary">{t.nav.cta}</a>
        </div>
      </div>
    </nav>);

}

/* ---------- HERO ---------- */
function Hero({ t }) {
  return (
    <header className="hero" id="top" data-comment-anchor="f4283ac125-header-36-5">
      <img className="hero-mono" src="assets/hero-mono.png?v=hd3" alt="Arquitecto trabajando en su laptop" />
      <img className="hero-mono-2" src="assets/hero-mono-2.png?v=hd2" alt="Mano señalando un calendario junto a una laptop" />

      <div className="wrap hero-content">
        <h1>{t.hero.h1a}<span className="hl">{t.hero.h1hl}</span></h1>
        <p className="hero-sub">{t.hero.sub}</p>
        <div className="hero-cta">
          <a href="#demo" className="btn btn-primary btn-lg">{t.hero.cta1}<IcArrow /></a>
          <a href="#producto" className="btn btn-ghost btn-lg">{t.hero.cta2}</a>
        </div>

        <div className="proof-strip">
          <div className="label">{t.hero.proof}</div>
          <div className="logo-marquee">
            <div className="logo-track" aria-hidden="false">
              {[1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8].map((n, i) =>
              <img className="firm-logo" key={i} src={`assets/logos/firm-${n}.svg`} alt={i < 8 ? `Despacho ${n}` : ""} aria-hidden={i >= 8} />
              )}
            </div>
          </div>
        </div>
      </div>
    </header>);

}

/* ---------- PROBLEM ---------- */
function Problem({ t }) {
  const illus = ["assets/problem-3.png", "assets/problem-2.png", "assets/problem-1.png"];
  return (
    <section className="sec" id="problema">
      <div className="wrap">
        <div className="sec-head reveal">
          <h2 className="sec-title">{t.problem.title}</h2>
          <p className="sec-sub">{t.problem.sub}</p>
        </div>
        <div className="prob-grid">
          {t.problem.cards.map((c, i) =>
          <div className={"prob-card reveal d" + (i + 1)} key={i}>
              <img className="prob-illu" src={illus[i]} alt="" />
              <h3>{c.t}</h3>
              <p>{c.d}</p>
            </div>
          )}
        </div>
      </div>
    </section>);

}

/* ---------- PRODUCT — 5 PILLARS (scroll-driven glances) ---------- */
const GLANCES = [
{ file: "Operaciones Preview Card.html", w: 720, h: 430 },
{ file: "Finanzas Preview Card.html", w: 756, h: 516 },
{ file: "Equipo Preview.html", w: 740, h: 530 },
{ file: "Clientes Preview Card.html", w: 784, h: 686 },
{ file: "Documentos Preview Card.html", w: 786, h: 766 }];


/* A glance preview rendered in an isolated iframe, scaled to fit its column. */
function Glance({ file, w, h, lang }) {
  const wrapRef = React.useRef(null);
  const frameRef = React.useRef(null);
  const initialLang = React.useRef(lang);
  const [scale, setScale] = React.useState(null);
  React.useLayoutEffect(() => {
    const el = wrapRef.current;
    if (!el) return;
    const measure = () => {
      const avail = el.clientWidth;
      if (avail > 0) setScale(Math.min(1, avail / w));
    };
    measure();
    const raf = requestAnimationFrame(measure);
    let ro = null;
    if (typeof ResizeObserver !== "undefined") {
      ro = new ResizeObserver(measure);
      ro.observe(el);
    }
    window.addEventListener("resize", measure);
    return () => {
      cancelAnimationFrame(raf);
      if (ro) ro.disconnect();
      window.removeEventListener("resize", measure);
    };
  }, [w]);
  const s = scale == null ? Math.min(1, 651 / w) : scale;
  // tell the embedded card which language to render (no reload needed)
  React.useEffect(() => {
    const f = frameRef.current;
    if (f && f.contentWindow) {
      f.contentWindow.postMessage({ type: "setLang", lang: lang }, "*");
    }
  }, [lang]);
  return (
    <div className="glance-wrap" ref={wrapRef} style={{ maxWidth: w, height: Math.round(h * s) }}>
      <iframe
        ref={frameRef}
        className="glance-frame"
        src={encodeURI(file) + "?lang=" + initialLang.current}
        title=""
        aria-hidden="true"
        tabIndex={-1}
        scrolling="no"
        loading="lazy"
        onLoad={() => {
          const f = frameRef.current;
          if (f && f.contentWindow) f.contentWindow.postMessage({ type: "setLang", lang: lang }, "*");
        }}
        style={{ width: w, height: h, transform: "scale(" + s + ")" }} />
    </div>);

}

function Product({ t, lang }) {
  const secRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0);
  const [active, setActive] = React.useState(0);
  const [inView, setInView] = React.useState(false);
  const num = (i) => String(i + 1).padStart(2, "0");

  // entrance / exit animation per pane
  React.useEffect(() => {
    const sec = secRef.current;
    if (!sec) return;
    sec.classList.add("is-armed");
    const panes = sec.querySelectorAll(".pillar-pane");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        e.target.classList.toggle("active", e.isIntersecting);
        if (e.isIntersecting) {
          const i = Number(e.target.getAttribute("data-i"));
          if (!Number.isNaN(i)) setActive(i);
        }
      });
    }, { threshold: 0.4 });
    panes.forEach((p) => io.observe(p));
    return () => io.disconnect();
  }, []);

  // lateral progress indicator
  React.useEffect(() => {
    const onScroll = () => {
      const sec = secRef.current;
      if (!sec) return;
      const rect = sec.getBoundingClientRect();
      const vh = window.innerHeight;
      const total = rect.height - vh;
      const passed = Math.min(Math.max(-rect.top + vh * 0.0, 0), Math.max(total, 1));
      setProgress(total > 0 ? Math.min(1, Math.max(0, (-rect.top + vh * 0.5) / rect.height)) : 0);
      setInView(rect.top < vh * 0.5 && rect.bottom > vh * 0.5);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  return (
    <section className="product-scroll" id="producto" ref={secRef}>
      <div className={"pillar-progress" + (inView ? " on" : "")} aria-hidden="true">
        <span className="pp-count">{num(active)}</span>
        <div className="pp-track"><div className="pp-fill" style={{ height: progress * 100 + "%" }}></div></div>
        <span className="pp-total">05</span>
      </div>

      <div className="product-intro">
        <div className="wrap">
          <div className="sec-head reveal">
            <h2 className="sec-title">{t.product.title}</h2>
            <p className="sec-sub">{t.product.sub}</p>
          </div>
        </div>
      </div>

      <div id="modulos">
        {t.product.pillars.map((p, i) => {
          const g = GLANCES[i];
          return (
            <div className="pillar-pane" data-i={i} key={i} data-screen-label={"Pilar " + num(i) + " · " + p.t}>
              <div className="wrap pillar-grid">
                <div className="pillar-text">
                  <div className="pillar-num">{num(i)}</div>
                  <h3 className="pillar-title">{p.t}</h3>
                  <p className="pillar-desc">{p.d}</p>
                  <div className="pillar-pills">
                    {p.mods.map((m, j) => <span className="pillar-pill" key={j}>{m}</span>)}
                  </div>
                  <a href="#demo" className="pillar-more">{t.product.more} <span className="arr">→</span></a>
                </div>
                <div className="pillar-vis">
                  <Glance file={g.file} w={g.w} h={g.h} lang={lang} />
                </div>
              </div>
            </div>);

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

}

/* ---------- HOW IT WORKS ---------- */

/* Chisel-marker style illustrations, one per step */
const HowIllus = [
  /* 01 — Character illustration PNG */
  <img key="i1" src="assets/how-illus-01.png" alt="" aria-hidden="true" className="how-illus-img" />,
  /* 02 — Team at laptop PNG */
  <img key="i2" src="assets/how-illus-02.png" alt="" aria-hidden="true" className="how-illus-img" />,
  /* 03 — Growth chart PNG */
  <img key="i3" src="assets/how-illus-03.png" alt="" aria-hidden="true" className="how-illus-img" />
];

function How({ t }) {
  return (
    <section className="sec" id="como">
      <div className="wrap">
        <div className="how-head reveal">
          <h2 className="how-title">{t.how.title}</h2>
          <p className="how-sub">{t.how.sub}</p>
        </div>
        <div className="how-steps">
          {t.how.steps.map((s, i) => (
            <div className={"how-step reveal d" + (i + 1)} key={i}>
              {i < 2 && <div className="how-step-line"></div>}

              <div className="how-visual">
                <div className="how-ghost-num" aria-hidden="true">{s.n}</div>
                <div className="how-illus">{HowIllus[i]}</div>
              </div>
              <div className="how-step-body">
                <h3>{s.t}</h3>
                <p>{s.d}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>);

}

/* ---------- SOCIAL PROOF ---------- */
function Social({ t }) {
  const [activeIdx, setActiveIdx] = React.useState(0);
  const [animating, setAnimating] = React.useState(false);
  const [displayedQ, setDisplayedQ] = React.useState(t.social.quotes[0].q);
  const [displayedR, setDisplayedR] = React.useState(t.social.quotes[0].r);
  const [hovered, setHovered] = React.useState(null);

  React.useEffect(() => {
    setDisplayedQ(t.social.quotes[activeIdx].q);
    setDisplayedR(t.social.quotes[activeIdx].r);
  }, [t]);

  const select = (idx) => {
    if (idx === activeIdx || animating) return;
    setAnimating(true);
    setTimeout(() => {
      setDisplayedQ(t.social.quotes[idx].q);
      setDisplayedR(t.social.quotes[idx].r);
      setActiveIdx(idx);
      setTimeout(() => setAnimating(false), 350);
    }, 180);
  };

  return (
    <section className="sec">
      <div className="wrap">
        <div className="sec-head reveal">
          <h2 className="sec-title">{t.social.title}</h2>
        </div>
        <div className="metrics">
          {t.social.metrics.map((m, i) =>
            <div className={"metric reveal d" + (i + 1)} key={i}>
              <div className="val">{m.v}<span className="u">{m.u}</span></div>
              <div className="lbl">{m.l}</div>
            </div>
          )}
        </div>
        <div className="testi reveal d2">
          <div className="testi-quote-wrap">
            <span className="testi-deco testi-deco-open" aria-hidden="true">&#8220;</span>
            <p className={"testi-quote" + (animating ? " testi-out" : "")}>{displayedQ}</p>
            <span className="testi-deco testi-deco-close" aria-hidden="true">&#8221;</span>
          </div>
          <div className="testi-foot">
            <p className={"testi-role" + (animating ? " testi-out" : "")}>{displayedR}</p>
            <div className="testi-pills">
              {t.social.quotes.map((q, i) => {
                const isActive = activeIdx === i;
                const showName = isActive || hovered === i;
                return (
                  <button
                    key={i}
                    className={"testi-pill" + (isActive ? " testi-pill-active" : "") + (showName ? " testi-pill-open" : "")}
                    onClick={() => select(i)}
                    onMouseEnter={() => setHovered(i)}
                    onMouseLeave={() => setHovered(null)}
                    aria-label={q.n}
                  >
                    <span className="testi-av">{q.i}</span>
                    <span className={"testi-name" + (showName ? " testi-name-show" : "")}>{q.n}</span>
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </section>);
}

/* ---------- FINAL CTA + FORM ---------- */
function DemoForm({ t }) {
  const [v, setV] = React.useState({ name: "", email: "", firm: "", size: "" });
  const [err, setErr] = React.useState({});
  const [done, setDone] = React.useState(false);
  const c = t.cta;

  const set = (k) => (e) => {setV((s) => ({ ...s, [k]: e.target.value }));setErr((s) => ({ ...s, [k]: null }));};
  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!v.name.trim()) er.name = c.errs.name;
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.email)) er.email = c.errs.email;
    if (!v.firm.trim()) er.firm = c.errs.firm;
    if (!v.size) er.size = c.errs.size;
    setErr(er);
    if (Object.keys(er).length === 0) setDone(true);
  };

  if (done) return (
    <div className="form-card">
      <div className="success">
        <div className="check"><IcCheck /></div>
        <h3>{c.okTitle}</h3>
        <p>{c.okSub}</p>
      </div>
    </div>);


  return (
    <form className="form-card" onSubmit={submit} noValidate>
      <div className={"field" + (err.name ? " err" : "")}>
        <label className="fl">{c.fields.name}</label>
        <input type="text" placeholder={c.ph.name} value={v.name} onChange={set("name")} />
        {err.name && <div className="msg">{err.name}</div>}
      </div>
      <div className={"field" + (err.email ? " err" : "")}>
        <label className="fl">{c.fields.email}</label>
        <input type="email" placeholder={c.ph.email} value={v.email} onChange={set("email")} />
        {err.email && <div className="msg">{err.email}</div>}
      </div>
      <div className="form-row">
        <div className={"field" + (err.firm ? " err" : "")}>
          <label className="fl">{c.fields.firm}</label>
          <input type="text" placeholder={c.ph.firm} value={v.firm} onChange={set("firm")} />
          {err.firm && <div className="msg">{err.firm}</div>}
        </div>
        <div className={"field" + (err.size ? " err" : "")}>
          <label className="fl">{c.fields.size}</label>
          <select value={v.size} onChange={set("size")} required>
            <option value="" disabled>{c.ph.size}</option>
            {c.sizes.map((s, i) => <option key={i} value={s}>{s}</option>)}
          </select>
          {err.size && <div className="msg">{err.size}</div>}
        </div>
      </div>
      <button type="submit" className="btn btn-primary btn-lg form-submit">{c.submit}<IcArrow /></button>
      <p className="form-fine">{c.fine}</p>
    </form>);

}

function CTA({ t }) {
  return (
    <section className="cta" id="demo">
      <span className="spark" style={{ left: "8%", top: "40px", fontSize: "28px", transform: "rotate(10deg)" }}>✦</span>
      <span className="spark" style={{ left: "42%", top: "22px", fontSize: "16px" }}>✦</span>
      <span className="spark" style={{ right: "6%", bottom: "40px", fontSize: "22px", transform: "rotate(-8deg)" }}>✦</span>
      <div className="wrap">
        <div className="cta-grid">
          <div className="reveal">
            <h2>{t.cta.title}</h2>
            <p className="cta-sub">{t.cta.sub}</p>
          </div>
          <div className="reveal d1">
            <DemoForm t={t} />
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- FOOTER ---------- */
function Footer({ t }) {
  const f = t.foot,l = f.links;
  return (
    <footer className="sec surface foot">
      <div className="wrap">
        <div className="foot-top">
          <div>
            <img className="foot-logo" src={LOGO} alt="VETRA" />
            <p className="foot-tag">{f.tag}</p>
          </div>
          <div className="foot-links">
            <div className="foot-col">
              <h4>{f.colProduct}</h4>
              <a href="#producto">{l.product}</a>
              <a href="#modulos">{l.modules}</a>
              <a href="#como">{l.how}</a>
            </div>
            <div className="foot-col">
              <h4>{f.colCompany}</h4>
              <a href="#">{l.privacy}</a>
              <a href="#">{l.terms}</a>
            </div>
          </div>
        </div>
        <div className="foot-bot">
          <p>{f.rights}</p>
          <div className="foot-social">
            <a href="#" aria-label="LinkedIn"><IcLinkedin /></a>
            <a href="#" aria-label="Instagram"><IcInsta /></a>
          </div>
        </div>
      </div>
    </footer>);

}

Object.assign(window, { Navbar, Hero, Problem, Product, How, Social, CTA, Footer });