/* ============================================================
   FLOREA GRUP — Shared components, hooks, icons, routing
   ============================================================ */
const { useState, useEffect, useRef, useContext, createContext, useCallback } = React;

/* ---------- Language ---------- */
const LangCtx = createContext("ro");
function useL() {
  const lang = useContext(LangCtx);
  const L = useCallback((o) => (o == null ? "" : (typeof o === "object" && ("ro" in o || "en" in o) ? o[lang] : o)), [lang]);
  return { lang, L };
}

/* ---------- Icons (UI only — simple strokes) ---------- */
const Ic = {
  arrow: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 6l6 6-6 6"/></svg>,
  arrowDown: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 5v14M6 13l6 6 6-6"/></svg>,
  plus: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="M12 5v14M5 12h14"/></svg>,
  minus: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="M5 12h14"/></svg>,
  menu: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="M3 6h18M3 12h18M3 18h18"/></svg>,
  close: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="M6 6l12 12M18 6L6 18"/></svg>,
  phone: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>,
  mail: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-10 6L2 7"/></svg>,
  pin: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0z"/><circle cx="12" cy="10" r="3"/></svg>,
  ext: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M7 17 17 7M8 7h9v9"/></svg>,
  leaf: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10z"/><path d="M2 21c0-3 1.85-5.36 5.08-6"/></svg>,
  star: (p) => <svg viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M12 2l2.9 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l7.1-1.01L12 2z"/></svg>,
  check: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 6 9 17l-5-5"/></svg>,
};

/* ---------- Routing (hash) ---------- */
function useHashRoute() {
  const parse = () => {
    let h = window.location.hash.replace(/^#\/?/, "");
    const parts = h.split("/").filter(Boolean);
    return { page: parts[0] || "home", id: parts[1] || null };
  };
  const [route, setRoute] = useState(parse);
  useEffect(() => {
    const on = () => { setRoute(parse()); window.scrollTo(0, 0); };
    window.addEventListener("hashchange", on);
    return () => window.removeEventListener("hashchange", on);
  }, []);
  return route;
}
function go(page, id) {
  window.location.hash = "#/" + page + (id ? "/" + id : "");
}

/* ---------- Reveal on scroll (fail-safe: content defaults visible) ---------- */
function useInView() {
  const ref = useRef(null);
  const [seen, setSeen] = useState(true); // visible by default — never stuck hidden
  React.useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const vh = window.innerHeight || document.documentElement.clientHeight || 800;
    const r = el.getBoundingClientRect();
    // Already in (or above) the viewport → leave visible, no entrance animation.
    if (r.top <= vh * 0.88) return;
    // Below the fold → hide now (pre-paint, no flash) then reveal on scroll.
    setSeen(false);
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setSeen(true); io.disconnect(); }
    }, { threshold: 0.1, rootMargin: "0px 0px -8% 0px" });
    io.observe(el);
    const t = setTimeout(() => setSeen(true), 1600); // safety
    return () => { io.disconnect(); clearTimeout(t); };
  }, []);
  return [ref, seen];
}
function Reveal({ children, d, as, className = "", ...rest }) {
  const [ref, seen] = useInView();
  const Tag = as || "div";
  return <Tag ref={ref} className={"reveal " + className + (seen ? " in" : "")} data-d={d} {...rest}>{children}</Tag>;
}

/* ---------- Animated counter ---------- */
function Counter({ value, suffix = "", dur = 1600, immediate = false }) {
  const [ref, seenRaw] = useInView();
  const seen = immediate || seenRaw;
  const [n, setN] = useState(0);
  useEffect(() => {
    if (!seen) return;
    let raf, start;
    const tick = (t) => {
      if (!start) start = t;
      const p = Math.min((t - start) / dur, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      setN(Math.round(eased * value));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [seen, value]);
  const fmt = n.toLocaleString("ro-RO");
  return <span ref={ref} className="tnum">{fmt}{suffix}</span>;
}

/* ---------- Placeholder image ---------- */
function Ph({ label, ratio, className = "", dark, red, style }) {
  const cls = "ph" + (dark ? " ph--dark" : "") + (red ? " ph--red" : "") + (className ? " " + className : "");
  const st = { ...(ratio ? { aspectRatio: ratio } : {}), ...(style || {}) };
  return <div className={cls} data-label={label} style={st} aria-hidden="true"></div>;
}

/* ---------- Eyebrow ---------- */
function Eyebrow({ children, plain }) {
  return <span className={"eyebrow" + (plain ? " eyebrow--plain" : "")}>{children}</span>;
}

/* ---------- Section header ---------- */
function SectionHead({ kicker, title, lead, align = "left", light }) {
  return (
    <div className="sec-head" style={{ textAlign: align, maxWidth: align === "center" ? "780px" : "920px", marginInline: align === "center" ? "auto" : 0 }}>
      {kicker && <Reveal><Eyebrow>{kicker}</Eyebrow></Reveal>}
      <Reveal d="1"><h2 className="h-xl" style={{ marginTop: "0.5em", color: light ? "#fff" : "var(--ink)" }}>{title}</h2></Reveal>
      {lead && <Reveal d="2"><p className="lead" style={{ marginTop: "0.9em" }}>{lead}</p></Reveal>}
    </div>
  );
}

/* ---------- Navigation ---------- */
function Nav({ lang, setLang }) {
  const { L } = useL();
  const U = FG.UI;
  const route = useHashRoute();
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const onHome = route.page === "home";

  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 40);
    on(); window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  useEffect(() => { setOpen(false); }, [route.page, route.id]);

  const links = [
    ["about", U.nav_about], ["divisions", U.nav_divisions], ["projects", U.nav_projects],
    ["sustainability", U.nav_sustain], ["hospitality", U.nav_hospitality],
    ["careers", U.nav_careers], ["news", U.nav_news],
  ];
  const solid = scrolled || !onHome || open;

  return (
    <header className={"nav" + (solid ? " nav--solid" : "") + (open ? " nav--open" : "")}>
      <div className="nav__bar wrap">
        <a className="nav__logo" href="#/" aria-label="Florea Grup — acasă">
          <img src={solid ? "assets/logo.png" : "assets/logo-light.png"} alt="Florea Grup" />
        </a>
        <nav className="nav__links">
          {links.map(([p, lab]) => (
            <a key={p} href={"#/" + p} className={"nav__link" + (route.page === p ? " is-active" : "")}>{L(lab)}</a>
          ))}
        </nav>
        <div className="nav__right">
          <div className="langtog" role="group" aria-label="Language">
            <button className={lang === "ro" ? "on" : ""} onClick={() => setLang("ro")}>RO</button>
            <span>/</span>
            <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
          </div>
          <a href="#/contact" className="btn btn--primary nav__cta">{L(U.cta_contact)}</a>
          <button className="nav__burger" onClick={() => setOpen(o => !o)} aria-label="Menu">
            {open ? <Ic.close /> : <Ic.menu />}
          </button>
        </div>
      </div>
      <div className="nav__drawer">
        {links.concat([["contact", U.nav_contact]]).map(([p, lab]) => (
          <a key={p} href={"#/" + p} className={"nav__dlink" + (route.page === p ? " is-active" : "")}>{L(lab)}</a>
        ))}
      </div>
    </header>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  const { L } = useL();
  const U = FG.UI;
  const quick = [["about", U.nav_about], ["divisions", U.nav_divisions], ["projects", U.nav_projects], ["careers", U.nav_careers], ["contact", U.nav_contact]];
  return (
    <footer className="footer dark">
      <div className="wrap">
        <div className="footer__top">
          <div className="footer__brand">
            <img src="assets/logo-light.png" alt="Florea Grup" style={{ height: 40 }} />
            <p className="lead" style={{ marginTop: "1.2em", maxWidth: 360 }}>
              {L({ ro: "30 de ani de excelență cu capital 100% românesc. De la o stație de carburanți la lider în construcții.",
                   en: "30 years of excellence with 100% Romanian capital. From a single fuel station to a leader in construction." })}
            </p>
          </div>
          <div className="footer__cols">
            <div>
              <h4 className="footer__h">{L({ ro: "Navigare", en: "Navigate" })}</h4>
              <ul>{quick.map(([p, lab]) => <li key={p}><a href={"#/" + p}>{L(lab)}</a></li>)}</ul>
            </div>
            <div>
              <h4 className="footer__h">{L({ ro: "Branduri", en: "Brands" })}</h4>
              <ul>{FG.SUBSIDIARIES.map(s => <li key={s.web}><a href={"https://" + s.web} target="_blank" rel="noreferrer">{s.name} <Ic.ext style={{ width: 13, height: 13, opacity: .5 }} /></a></li>)}</ul>
            </div>
            <div>
              <h4 className="footer__h">{L(U.nav_contact)}</h4>
              <ul className="footer__contact">
                <li><Ic.pin style={{ width: 16 }} /> Bd. Horea nr. 2, Alba Iulia</li>
                <li><Ic.phone style={{ width: 16 }} /> +40 258 842 275</li>
                <li><Ic.mail style={{ width: 16 }} /> contact@floreagrup.ro</li>
              </ul>
            </div>
          </div>
        </div>
        <div className="footer__bot">
          <span>© {new Date().getFullYear()} Florea Grup. {L({ ro: "Toate drepturile rezervate.", en: "All rights reserved." })}</span>
          <span className="footer__botlinks">
            <a href="#/contact">{L({ ro: "Confidențialitate", en: "Privacy" })}</a>
            <button className="footer__cklink" onClick={() => window.dispatchEvent(new CustomEvent("fg-open-cookies"))}>{L({ ro: "Setări cookies", en: "Cookie settings" })}</button>
            <span className="muted" style={{ color: "var(--steel)", fontSize: ".85rem" }}>{L({ ro: "Design și dezvoltare web de ", en: "Web design and development by " })}<a href="https://aldeacosmin.ro" target="_blank" rel="noreferrer" style={{ color: "inherit", textDecoration: "underline" }}>Aldea Cosmin</a></span>
          </span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { LangCtx, useL, Ic, useHashRoute, go, useInView, Reveal, Counter, Ph, Eyebrow, SectionHead, Nav, Footer });
