/* NEXABOT — sections (bilingue) */
const { useState, useEffect, useRef } = React;
const { Icon } = window.NEXA;
const { useLang } = window.NEXA_I18N;

/* hook: reveal on scroll — entrance via WAAPI, content visible if it never fires */
function useReveal() {
  useEffect(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce || document.body.classList.contains("no-anim")) return;
    const els = [...document.querySelectorAll(".reveal:not([data-seen])")];
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          const el = e.target;
          el.setAttribute("data-seen", "1");
          const d = (parseFloat(getComputedStyle(el).getPropertyValue("--rd")) || 0) * 1000;
          el.animate(
            [{ opacity: 0, transform: "translateY(28px)" }, { opacity: 1, transform: "none" }],
            { duration: 760, delay: d, easing: "cubic-bezier(.2,.7,.3,1)", fill: "backwards" }
          );
          io.unobserve(el);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* animated counter */
function Counter({ value, suffix }) {
  const [n, setN] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (e.isIntersecting) {
          const dur = 1400, t0 = performance.now();
          const dec = value % 1 !== 0;
          const tick = (t) => {
            const p = Math.min(1, (t - t0) / dur);
            const eased = 1 - Math.pow(1 - p, 3);
            setN(dec ? +(value * eased).toFixed(1) : Math.round(value * eased));
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
          io.unobserve(el);
        }
      });
    }, { threshold: 0.5 });
    io.observe(el);
    return () => io.disconnect();
  }, [value]);
  return <span ref={ref}>{n}{suffix}</span>;
}

/* language switch FR / EN */
function LangSwitch({ className }) {
  const { lang, setLang } = useLang();
  return (
    <div className={"lang-switch " + (className || "")} role="group" aria-label="Langue / Language">
      <button className={lang === "fr" ? "on" : ""} onClick={() => setLang("fr")} aria-pressed={lang === "fr"}>FR</button>
      <span className="lang-sep" />
      <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")} aria-pressed={lang === "en"}>EN</button>
    </div>
  );
}

/* ---------------- NAV ---------------- */
function Nav() {
  const { c } = useLang();
  const [open, setOpen] = useState(false);
  const [solid, setSolid] = useState(false);
  useEffect(() => {
    const onScroll = () => setSolid(window.scrollY > 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const links = [[c.nav.services, "#services"], [c.nav.portfolio, "#portfolio"], [c.nav.about, "#apropos"]];
  return (
    <header className={"nav" + (solid ? " nav-solid" : "")}>
      <div className="wrap nav-inner">
        <a href="#top" className="logo" aria-label="Nexabot">
          <span className="logo-mark"><span className="logo-dot" /></span>
          <span className="logo-text">NEXA<span>BOT</span></span>
        </a>
        <nav className="nav-links">
          {links.map(([l, h]) => <a key={h} href={h}>{l}</a>)}
        </nav>
        <div className="nav-right">
          <LangSwitch />
          <a href="#contact" className="btn btn-primary nav-cta">{c.nav.cta}</a>
        </div>
        <button className="nav-burger" aria-label="Menu" onClick={() => setOpen((o) => !o)}>
          <span /><span /><span />
        </button>
      </div>
      {open && (
        <div className="nav-mobile">
          {links.map(([l, h]) => <a key={h} href={h} onClick={() => setOpen(false)}>{l}</a>)}
          <LangSwitch className="lang-switch-mobile" />
          <a href="#contact" className="btn btn-primary" onClick={() => setOpen(false)}>{c.nav.cta}</a>
        </div>
      )}
    </header>
  );
}

/* ---------------- HERO ---------------- */
function Hero({ intensity }) {
  const { c } = useLang();
  return (
    <section id="top" className="hero">
      <div className="hero-bg">{React.createElement(window.NodeNetwork, { intensity })}</div>
      <div className="hero-glow" />
      <div className="wrap hero-inner">
        <div className="hero-badge reveal">
          <span className="kbd-dot" /> {c.hero.badge}
        </div>
        <h1 className="hero-title reveal" style={{ "--rd": ".05s" }}>
          {c.hero.titleA}<br /><span className="grad">{c.hero.titleB}</span>
        </h1>
        <p className="hero-sub reveal" style={{ "--rd": ".12s" }}>{c.hero.sub}</p>
        <div className="hero-actions reveal" style={{ "--rd": ".18s" }}>
          <a href="#contact" className="btn btn-primary btn-lg">{c.hero.start} <Icon.arrow width="18" /></a>
          <a href="#services" className="btn btn-ghost btn-lg">{c.hero.discover}</a>
        </div>
        <div className="hero-chips reveal" style={{ "--rd": ".24s" }}>
          <span className="chip"><Icon.bolt width="15" /> {c.hero.chips[0]}</span>
          <span className="chip"><Icon.shield width="15" /> {c.hero.chips[1]}</span>
          <span className="chip"><Icon.clock width="15" /> {c.hero.chips[2]}</span>
        </div>
      </div>
      <a className="hero-scroll" href="#services" aria-label={c.hero.scroll}>
        <span className="mono">{c.hero.scroll}</span>
        <span className="hero-scroll-line" />
      </a>
    </section>
  );
}

/* ---------------- SERVICES ---------------- */
function Services() {
  const { c } = useLang();
  return (
    <section id="services" className="section-pad">
      <div className="wrap">
        <div className="section-head reveal">
          <span className="eyebrow">{c.services.eyebrow}</span>
          <h2>{c.services.h2a}<br />{c.services.h2b}</h2>
          <p>{c.services.p}</p>
        </div>
        <div className="svc-grid">
          {c.services.items.map((s, i) => {
            const IC = Icon[s.icon];
            return (
              <article key={i} className="card card-glow svc reveal" style={{ "--rd": `${i * 0.08}s` }}>
                <div className="svc-top">
                  <span className="svc-icon"><IC width="24" /></span>
                  <span className="mono svc-tag">{s.tag}</span>
                </div>
                <h3 className="svc-title">{s.title}</h3>
                <p className="svc-body">{s.body}</p>
                <ul className="svc-points">
                  {s.points.map((p) => <li key={p}><span className="tick"><Icon.bolt width="11" /></span>{p}</li>)}
                </ul>
                <span className="svc-num mono">0{i + 1}</span>
              </article>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ---------------- PORTFOLIO ---------------- */
function Portfolio() {
  const { c } = useLang();
  return (
    <section id="portfolio" className="section-pad">
      <div className="wrap">
        <div className="apps-head reveal">
          <div>
            <span className="eyebrow">{c.portfolio.eyebrow}</span>
            <h2 className="apps-h2">{c.portfolio.h2}</h2>
          </div>
          <p>{c.portfolio.p}</p>
        </div>
        <div className="portfolio-empty card reveal">
          <span className="pf-badge mono"><span className="kbd-dot" /> {c.portfolio.badge}</span>
          <h3>{c.portfolio.h3}</h3>
          <p>{c.portfolio.body}</p>
          <a href="#contact" className="btn btn-ghost">{c.portfolio.btn} <Icon.arrow width="16" /></a>
        </div>
      </div>
    </section>
  );
}

/* ---------------- ABOUT / STATS ---------------- */
function About() {
  const { c } = useLang();
  return (
    <section id="apropos" className="section-pad about-section">
      <div className="hero-glow about-glow" />
      <div className="wrap about-grid">
        <div className="about-left reveal">
          <span className="eyebrow">{c.about.eyebrow}</span>
          <h2>{c.about.h2a}<br />{c.about.h2b}</h2>
          <p className="about-lead">{c.about.lead}</p>
          <p className="about-body">{c.about.body}</p>
          <a href="#contact" className="btn btn-primary">{c.about.btn} <Icon.arrow width="18" /></a>
        </div>
        <div className="stats reveal" style={{ "--rd": ".1s" }}>
          {c.about.stats.map((s) => (
            <div key={s.label} className="stat card">
              <div className="stat-v"><Counter value={s.v} suffix={s.suffix} /></div>
              <div className="stat-l">{s.label}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- CONTACT ---------------- */
function Contact() {
  const { c } = useLang();
  const [form, setForm] = useState({ name: "", email: "", service: 0, msg: "" });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  function submit(e) {
    e.preventDefault();
    const er = {};
    if (!form.name.trim()) er.name = c.contact.errName;
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) er.email = c.contact.errEmail;
    if (form.msg.trim().length < 8) er.msg = c.contact.errMsg;
    setErrors(er);
    if (Object.keys(er).length === 0) setSent(true);
  }

  return (
    <section id="contact" className="section-pad contact-section">
      <div className="wrap contact-card reveal">
        <div className="contact-left">
          <span className="eyebrow">{c.contact.eyebrow}</span>
          <h2>{c.contact.h2a}<br />{c.contact.h2b}</h2>
          <p>{c.contact.p}</p>
          <ul className="contact-info">
            <li><span className="ci-ic"><Icon.bolt width="16" /></span> {c.contact.info[0]}</li>
            <li><span className="ci-ic"><Icon.shield width="16" /></span> {c.contact.info[1]}</li>
            <li><span className="ci-ic"><Icon.clock width="16" /></span> {c.contact.info[2]}</li>
          </ul>
        </div>
        <div className="contact-right">
          {sent ? (
            <div className="contact-sent">
              <div className="sent-check"><Icon.shield width="34" /></div>
              <h3>{c.contact.sentTitle}</h3>
              <p>{c.contact.sentBody(form.name.split(" ")[0])}</p>
              <button className="btn btn-ghost" onClick={() => { setSent(false); setForm({ name: "", email: "", service: 0, msg: "" }); }}>{c.contact.sentAgain}</button>
            </div>
          ) : (
            <form onSubmit={submit} noValidate>
              <label className="field">
                <span>{c.contact.fName}</span>
                <input value={form.name} onChange={set("name")} placeholder={c.contact.phName} className={errors.name ? "err" : ""} />
                {errors.name && <em>{errors.name}</em>}
              </label>
              <label className="field">
                <span>{c.contact.fEmail}</span>
                <input value={form.email} onChange={set("email")} placeholder={c.contact.phEmail} className={errors.email ? "err" : ""} />
                {errors.email && <em>{errors.email}</em>}
              </label>
              <label className="field">
                <span>{c.contact.fService}</span>
                <select value={form.service} onChange={set("service")}>
                  {c.contact.options.map((o, i) => <option key={i} value={i}>{o}</option>)}
                </select>
              </label>
              <label className="field">
                <span>{c.contact.fNeed}</span>
                <textarea rows="4" value={form.msg} onChange={set("msg")} placeholder={c.contact.phNeed} className={errors.msg ? "err" : ""} />
                {errors.msg && <em>{errors.msg}</em>}
              </label>
              <button type="submit" className="btn btn-primary btn-lg contact-submit">{c.contact.submit} <Icon.arrow width="18" /></button>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

/* ---------------- FOOTER ---------------- */
function Footer() {
  const { c } = useLang();
  return (
    <footer className="footer">
      <div className="wrap footer-inner">
        <div className="footer-brand">
          <a href="#top" className="logo">
            <span className="logo-mark"><span className="logo-dot" /></span>
            <span className="logo-text">NEXA<span>BOT</span></span>
          </a>
          <p>{c.footer.tagline}</p>
        </div>
        <div className="footer-cols">
          <div>
            <h4 className="mono">{c.footer.colServices}</h4>
            <a href="#services">{c.footer.sAuto}</a>
            <a href="#services">{c.footer.sApps}</a>
            <a href="#services">{c.footer.sWeb}</a>
          </div>
          <div>
            <h4 className="mono">{c.footer.colCompany}</h4>
            <a href="#apropos">{c.footer.cAbout}</a>
            <a href="#portfolio">{c.footer.cPortfolio}</a>
            <a href="#contact">{c.footer.cContact}</a>
          </div>
          <div>
            <h4 className="mono">{c.footer.colContact}</h4>
            <a href="#contact">{c.footer.quote}</a>
            <a href="mailto:contact@nexabot.io">contact@nexabot.io</a>
          </div>
        </div>
      </div>
      <div className="wrap footer-bot">
        <span className="mono">© {new Date().getFullYear()} NEXABOT</span>
        <span className="mono">{c.footer.legal}</span>
      </div>
    </footer>
  );
}

window.NexaSections = { Nav, Hero, Services, Portfolio, About, Contact, Footer, LangSwitch, useReveal };
