/* Rankabiz - main app */
const { useState, useEffect, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "split",
  "accent": "#FF6A00",
  "roundness": "soft"
}/*EDITMODE-END*/;

/* ---- scroll reveal hook ---- */
function useReveal(deps) {
  useEffect(() => {
    const els = Array.from(document.querySelectorAll(".reveal:not(.in)"));
    if (!els.length) return;
    const vh = window.innerHeight || 800;

    // 1) reveal anything already in (or near) the viewport immediately
    els.forEach((el) => {
      const r = el.getBoundingClientRect();
      if (r.top < vh * 0.92) el.classList.add("in");
    });

    const rest = els.filter((el) => !el.classList.contains("in"));
    if (!("IntersectionObserver" in window)) {
      rest.forEach((el) => el.classList.add("in"));
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((en) => {
          if (en.isIntersecting) {
            en.target.classList.add("in");
            io.unobserve(en.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    rest.forEach((el) => io.observe(el));

    // 2) safety net: if the observer never fires (e.g. off-screen iframe),
    //    reveal everything so content is never stuck invisible.
    const fallback = setTimeout(() => {
      document.querySelectorAll(".reveal:not(.in)").forEach((el) => el.classList.add("in"));
    }, 1600);

    return () => { io.disconnect(); clearTimeout(fallback); };
  }, deps);
}

/* ============ Hero visual (abstract local-results panel) ============ */
function HeroVisual({ t }) {
  return (
    <div className="hero-visual">
      <div className="hv-main reveal d1">
        <div className="hv-head">
          <RankIcon name="map" size={18} />
          <span>{t.hero.panel_label}</span>
        </div>
        <div className="hv-rows">
          {[
            { rank: 1, you: true },
            { rank: 2, you: false },
            { rank: 3, you: false },
          ].map((r) => (
            <div key={r.rank} className={"hv-row" + (r.you ? " you" : "")}>
              <span className="hv-rank">{r.rank}</span>
              <div className="hv-bars">
                <span className="hv-bar" style={{ width: r.you ? "82%" : 52 - r.rank * 6 + "%" }}></span>
                <span className="hv-bar sm" style={{ width: r.you ? "60%" : 36 + "%" }}></span>
              </div>
              {r.you && <span className="hv-you">{t.hero.you_tag || "Vous"}</span>}
            </div>
          ))}
        </div>
      </div>

      <div className="hv-float hv-calls reveal d2">
        <div className="hv-float-ico"><RankIcon name="phone" size={18} /></div>
        <div>
          <div className="hv-float-num">+38</div>
          <div className="hv-float-lbl">{t.hero.calls_lbl || "appels ce mois"}</div>
        </div>
      </div>

      <div className="hv-float hv-stars reveal d3">
        <RankIcon name="star" size={15} />
        <strong>4,9</strong>
        <span className="hv-float-lbl">· 126 {t.hero.reviews_lbl || "avis"}</span>
      </div>
    </div>
  );
}

/* ============ Hero variants ============ */
function Hero({ t, variant }) {
  const cta = (
    <div className="hero-cta-row">
      <a href="#rdv" className="btn btn-primary btn-arrow">
        {t.hero.cta_primary}
        <span className="btn-arrow"><RankIcon name="arrow" size={19} /></span>
      </a>
      <a href="#services" className="btn btn-ghost">{t.hero.cta_secondary}</a>
    </div>
  );
  const note = (
    <p className="hero-note">
      <RankIcon name="check" size={16} style={{ color: "var(--accent)" }} />
      {t.hero.note}
    </p>
  );
  const chips = (
    <div className="hero-badges">
      {t.hero.chips.map((c, i) => (
        <span key={i} className="chip"><span className="dot"></span>{c}</span>
      ))}
    </div>
  );
  const stats = (
    <div className="stats-row">
      {t.hero.stats.map((s, i) => (
        <div className="stat reveal" key={i}>
          <div className="num">{s.num}</div>
          <div className="lbl">{s.label}</div>
        </div>
      ))}
    </div>
  );
  const eyebrow = <span className="eyebrow">{t.hero.badge}</span>;
  const heading = (
    <h1 className="display text-balance">
      {t.hero.title_a} <span className="hl">{t.hero.title_hl}</span> {t.hero.title_b}
    </h1>
  );
  const sub = <p className="lead text-pretty" style={{ marginTop: 22, maxWidth: 560 }}>{t.hero.sub}</p>;

  if (variant === "centered") {
    return (
      <section className="hero hero-centered section-pad" id="top">
        <span className="blob" style={{ width: 460, height: 460, top: -120, left: "50%", marginLeft: -230, background: "var(--tint-2)", opacity: .6 }}></span>
        <div className="container" style={{ textAlign: "center", position: "relative", zIndex: 1 }}>
          <div className="reveal" style={{ display: "inline-block" }}>{eyebrow}</div>
          <div className="reveal d1" style={{ maxWidth: 900, margin: "18px auto 0" }}>{heading}</div>
          <div className="reveal d2" style={{ margin: "0 auto", maxWidth: 620 }}>{sub}</div>
          <div className="reveal d2" style={{ display: "flex", justifyContent: "center" }}>{cta}</div>
          <div className="reveal d3" style={{ display: "flex", justifyContent: "center" }}>{note}</div>
          <div className="reveal d3" style={{ display: "flex", justifyContent: "center", flexWrap: "wrap" }}>{chips}</div>
          <div style={{ display: "flex", justifyContent: "center", marginTop: 30 }}>{stats}</div>
        </div>
      </section>
    );
  }

  if (variant === "showcase") {
    return (
      <section className="hero hero-showcase section-pad" id="top">
        <div className="container" style={{ textAlign: "center", position: "relative", zIndex: 1 }}>
          <div className="reveal" style={{ display: "inline-block" }}>{eyebrow}</div>
          <div className="reveal d1" style={{ maxWidth: 980, margin: "18px auto 0" }}>{heading}</div>
          <div className="reveal d2" style={{ margin: "0 auto", maxWidth: 600 }}>{sub}</div>
          <div className="reveal d2" style={{ display: "flex", justifyContent: "center" }}>{cta}</div>
          <div className="reveal d3" style={{ display: "flex", justifyContent: "center" }}>{note}</div>
          <div className="showcase-stage reveal d2">
            <HeroVisual t={t} />
          </div>
        </div>
      </section>
    );
  }

  /* default: split */
  return (
    <section className="hero hero-split section-pad" id="top">
      <span className="blob" style={{ width: 520, height: 520, top: -160, right: -120, background: "var(--tint-2)", opacity: .55 }}></span>
      <div className="container hero-grid">
        <div className="hero-copy">
          <div className="reveal">{eyebrow}</div>
          <div className="reveal d1">{heading}</div>
          <div className="reveal d2">{sub}</div>
          <div className="reveal d2">{cta}</div>
          <div className="reveal d3">{note}</div>
          <div className="reveal d3">{chips}</div>
        </div>
        <div className="hero-art">
          <HeroVisual t={t} />
        </div>
      </div>
      <div className="container"><div className="reveal">{stats}</div></div>
    </section>
  );
}

/* ============ Services ============ */
function Services({ t }) {
  const icons = ["target", "pin", "search"];
  return (
    <section className="section-pad" id="services">
      <div className="container">
        <div className="section-head reveal">
          <span className="eyebrow">{t.services.eyebrow}</span>
          <h2 className="h2 text-balance">{t.services.title}</h2>
          <p className="lead text-pretty">{t.services.lead}</p>
        </div>
        <div className="cards-grid">
          {t.services.items.map((it, i) => (
            <div className={"card reveal d" + (i + 1)} key={i}>
              <span className="tag">{it.tag}</span>
              <div className="icon-wrap"><RankIcon name={icons[i]} size={28} /></div>
              <h3>{it.title}</h3>
              <p>{it.desc}</p>
              <ul className="feats">
                {it.feats.map((f, j) => (
                  <li key={j}><RankIcon name="check" size={17} />{f}</li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============ Method / steps ============ */
function Method({ t }) {
  return (
    <section className="section-pad" id="method" style={{ background: "var(--cream)" }}>
      <div className="container">
        <div className="section-head center reveal">
          <span className="eyebrow center">{t.method.eyebrow}</span>
          <h2 className="h2 text-balance">{t.method.title}</h2>
          <p className="lead text-pretty">{t.method.lead}</p>
        </div>
        <div className="steps">
          {t.method.steps.map((s, i) => (
            <div className={"step reveal d" + (i % 3 + 1)} key={i}>
              <div className="step-num">{i + 1}</div>
              <h3>{s.title}</h3>
              <p>{s.desc}</p>
              {i < t.method.steps.length - 1 && (
                <span className="connector"><RankIcon name="arrow" size={22} /></span>
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============ Coverage ============ */
function Coverage({ t }) {
  const icons = ["pin", "globe", "map", "bolt"];
  const pins = [
    { top: "34%", left: "30%" },
    { top: "52%", left: "46%" },
    { top: "40%", left: "60%" },
    { top: "62%", left: "70%" },
    { top: "30%", left: "52%" },
  ];
  return (
    <section className="section-pad" id="coverage">
      <div className="container">
        <div className="coverage reveal">
          <span className="cta-deco" style={{ width: 300, height: 300, top: -120, right: -80 }}></span>
          <div className="coverage-grid">
            <div>
              <span className="eyebrow">{t.coverage.eyebrow}</span>
              <h2 className="h2 text-balance" style={{ marginTop: 16 }}>{t.coverage.title}</h2>
              <p className="lead text-pretty" style={{ marginTop: 16 }}>{t.coverage.lead}</p>
              <div className="region-list">
                {t.coverage.regions.map((r, i) => (
                  <div className="region reveal" key={i}>
                    <span className="r-icon"><RankIcon name={icons[i]} size={24} /></span>
                    <div>
                      <div className="r-name">{r.name}</div>
                      <div className="r-desc">{r.desc}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
            <div className="globe-wrap">
              <div className="globe">
                {pins.map((p, i) => (
                  <span className="pin" key={i} style={{ top: p.top, left: p.left }}></span>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ FAQ ============ */
function Faq({ t }) {
  const [open, setOpen] = useState(0);
  return (
    <section className="section-pad" id="faq" style={{ background: "var(--cream)" }}>
      <div className="container">
        <div className="section-head center reveal">
          <span className="eyebrow center">{t.faq.eyebrow}</span>
          <h2 className="h2 text-balance">{t.faq.title}</h2>
        </div>
        <div className="faq-list">
          {t.faq.items.map((it, i) => {
            const isOpen = open === i;
            return (
              <div className={"faq-item reveal" + (isOpen ? " open" : "")} key={i}>
                <button className="faq-q" onClick={() => setOpen(isOpen ? -1 : i)} aria-expanded={isOpen}>
                  {it.q}
                  <span className="faq-icon"><RankIcon name="plus" size={18} /></span>
                </button>
                <div className="faq-a" style={{ maxHeight: isOpen ? 260 : 0 }}>
                  <div className="faq-a-inner">{it.a}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ============ Final CTA ============ */
function FinalCta({ t }) {
  return (
    <section className="section-pad" id="rdv">
      <div className="container">
        <div className="cta-band reveal">
          <span className="cta-deco" style={{ width: 360, height: 360, top: -160, left: -100 }}></span>
          <span className="cta-deco" style={{ width: 220, height: 220, bottom: -120, right: -40 }}></span>
          <div style={{ position: "relative", zIndex: 1 }}>
            <h2 className="h2 text-balance" style={{ maxWidth: 720, margin: "0 auto" }}>{t.final.title}</h2>
            <p className="text-pretty">{t.final.sub}</p>
            <div className="row">
              <a href="#" className="btn btn-light btn-arrow">
                <RankIcon name="calendar" size={19} />{t.final.cta_primary}
              </a>
              <a href="#" className="btn btn-outline">{t.final.cta_secondary}</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ Footer ============ */
function Footer({ t }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="brand">
              <img src="logo-rankabiz-footer.svg" className="brand-logo" alt="Rankabiz LLC" />
            </div>
            <p className="footer-about">{t.footer.about}</p>
          </div>
          <div className="footer-col">
            <h4>{t.footer.col_services}</h4>
            {t.footer.services.map((s, i) => <a href="#services" key={i}>{s}</a>)}
          </div>
          <div className="footer-col">
            <h4>{t.footer.col_company}</h4>
            {t.footer.company.map((s, i) => <a href="#" key={i}>{s}</a>)}
          </div>
          <div className="footer-col">
            <h4>{t.footer.col_contact}</h4>
            {t.footer.contact.map((s, i) => <a href="#rdv" key={i}>{s}</a>)}
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} Rankabiz LLC. {t.footer.rights}</span>
          <span style={{ display: "flex", gap: 22 }}>
            {t.footer.legal.map((l, i) => <a href="#" key={i} style={{ color: "inherit" }}>{l}</a>)}
          </span>
        </div>
      </div>
    </footer>
  );
}

/* ============ Header + language selector ============ */
function Header({ t, lang, setLang, dict }) {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  return (
    <header className={"site-header" + (scrolled ? " scrolled" : "")}>
      <div className="container">
        <nav className="nav">
          <a href="#top" className="brand">
            <img src="logo-rankabiz-header.svg" className="brand-logo" alt="Rankabiz" />
          </a>
          <div className="nav-links">
            <a href="#services">{t.nav.services}</a>
            <a href="#method">{t.nav.method}</a>
            <a href="#coverage">{t.nav.coverage}</a>
            <a href="#faq">{t.nav.faq}</a>
          </div>
          <div className="nav-right">
            <div className={"lang" + (open ? " open" : "")} ref={ref}>
              <button className="lang-btn" onClick={() => setOpen(!open)} aria-label="Language">
                <span style={{ fontSize: 17 }}>{dict[lang].flag}</span>
                {lang.toUpperCase()}
                <RankIcon name="chevron" size={15} />
              </button>
              <div className="lang-menu">
                {Object.keys(dict).map((k) => (
                  <button key={k} className={"lang-opt" + (k === lang ? " active" : "")} onClick={() => { setLang(k); setOpen(false); }}>
                    <span className="flag">{dict[k].flag}</span>
                    {dict[k].label}
                    <span className="check"><RankIcon name="check" size={16} /></span>
                  </button>
                ))}
              </div>
            </div>
            <a href="#rdv" className="btn btn-primary" style={{ padding: "11px 20px", fontSize: 15 }}>{t.nav.cta}</a>
          </div>
        </nav>
      </div>
    </header>
  );
}

/* ============ App ============ */
function App() {
  const dict = window.RANK_I18N;
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLangState] = useState(() => localStorage.getItem("rank_lang") || "fr");
  const setLang = (l) => { setLangState(l); localStorage.setItem("rank_lang", l); };
  const t = dict[lang] || dict.fr;

  // apply tweaks
  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty("--accent", tw.accent);
    // derive a slightly darker shade
    r.style.setProperty("--accent-deep", shade(tw.accent, -0.12));
    document.documentElement.lang = lang;
  }, [tw.accent, lang]);

  useReveal([lang, tw.heroVariant]);

  return (
    <>
      <Header t={t} lang={lang} setLang={setLang} dict={dict} />
      <main>
        <Hero t={t} variant={tw.heroVariant} />
        <Services t={t} />
        <Method t={t} />
        <Coverage t={t} />
        <Faq t={t} />
        <FinalCta t={t} />
      </main>
      <Footer t={t} />

      <TweaksPanel>
        <TweakSection label="Hero" />
        <TweakRadio
          label="Style du hero"
          value={tw.heroVariant}
          options={["split", "centered", "showcase"]}
          onChange={(v) => setTweak("heroVariant", v)}
        />
        <TweakSection label="Couleur" />
        <TweakColor
          label="Orange d'accent"
          value={tw.accent}
          options={["#FF6A00", "#F4801A", "#E8590C", "#FF8C42"]}
          onChange={(v) => setTweak("accent", v)}
        />
      </TweaksPanel>
    </>
  );
}

/* darken/lighten a hex color by amount (-1..1) */
function shade(hex, amt) {
  const h = hex.replace("#", "");
  const n = parseInt(h.length === 3 ? h.split("").map((c) => c + c).join("") : h, 16);
  let r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255;
  const f = (v) => Math.max(0, Math.min(255, Math.round(v + 255 * amt)));
  r = f(r); g = f(g); b = f(b);
  return "#" + [r, g, b].map((v) => v.toString(16).padStart(2, "0")).join("");
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
