// PeopleFlow 2.0 — landing app
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ----------------------------------------------------------------------------
// RibbonMark — logo symbol (V1: 3 teste stroke gradient, archi circolari G1)
// Generato programmaticamente: teste + valli, tangenti orizzontali.
// ----------------------------------------------------------------------------
function ribbonV1Path({ n = 3, r = 25, cx0 = 45, cy = 50 } = {}) {
  let x = cx0 - r;
  let d = `M ${x} ${cy} `;
  for (let i = 0; i < n; i++) {
    const xh = x + 2 * r;
    d += `A ${r} ${r} 0 0 1 ${xh} ${cy} `;
    x = xh;
    if (i < n - 1) {
      const xv = x + 2 * r;
      d += `A ${r} ${r} 0 0 0 ${xv} ${cy} `;
      x = xv;
    }
  }
  return d;
}

function RibbonMark({ width = 32, height = 14, strokeWidth = 14, ariaLabel }) {
  return (
    <svg
      className="logo-ribbon"
      width={width}
      height={height}
      viewBox="10 15 280 70"
      role={ariaLabel ? "img" : "presentation"}
      aria-label={ariaLabel}
      aria-hidden={ariaLabel ? undefined : true}
    >
      <path
        d={ribbonV1Path()}
        fill="none"
        stroke="url(#pf-ribbon-gradient)"
        strokeWidth={strokeWidth}
        strokeLinecap="round"
      />
    </svg>
  );
}

// ----------------------------------------------------------------------------
// Language hook (persisted)
// ----------------------------------------------------------------------------
function useLang() {
  const [lang, setLang] = useState(() => {
    try { return localStorage.getItem("pf_lang") || "it"; } catch { return "it"; }
  });
  useEffect(() => {
    try { localStorage.setItem("pf_lang", lang); } catch {}
    document.documentElement.lang = lang;
  }, [lang]);
  const t = window.PF_CONTENT[lang];
  return { lang, setLang, t };
}

// ----------------------------------------------------------------------------
// Reveal on scroll
// ----------------------------------------------------------------------------
function useReveal() {
  useEffect(() => {
    let io = null;
    let safety = null;
    // Delay a tick so React has finished rendering children.
    const raf = requestAnimationFrame(() => {
      document.documentElement.classList.add("js-reveal-ready");
      const els = Array.from(document.querySelectorAll(".reveal"));
      const revealAll = () => els.forEach((el) => el.classList.add("in"));

      if (!("IntersectionObserver" in window)) {
        revealAll();
        return;
      }
      io = new IntersectionObserver((entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      }, { threshold: 0.01, rootMargin: "0px 0px -2% 0px" });

      els.forEach((el) => {
        // Elements already in viewport at load — reveal immediately.
        const rect = el.getBoundingClientRect();
        if (rect.top < window.innerHeight && rect.bottom > 0) {
          el.classList.add("in");
        } else {
          io.observe(el);
        }
      });

      // Safety net: after 1500ms, force-reveal anything still hidden.
      // Protects against IntersectionObserver batching quirks in embedded/iframed contexts.
      safety = setTimeout(() => {
        document.querySelectorAll(".reveal:not(.in)").forEach((el) => {
          el.classList.add("in");
        });
      }, 1500);
    });
    return () => {
      cancelAnimationFrame(raf);
      if (io) io.disconnect();
      if (safety) clearTimeout(safety);
    };
  }, []);
}

// ----------------------------------------------------------------------------
// Demo booking page URL (single funnel — all CTAs point here)
// ----------------------------------------------------------------------------
const DEMO_URL = "demo.html";

// ----------------------------------------------------------------------------
// Nav
// ----------------------------------------------------------------------------
function Nav({ lang, setLang, t }) {
  return (
    <nav className="nav">
      <div className="container nav-inner">
        <a href="#top" className="logo" aria-label="PeopleFlow — homepage">
          <RibbonMark ariaLabel="PeopleFlow" />
          <span>PeopleFlow</span>
          <span className="logo-v">v2.0</span>
        </a>
        <div className="nav-links">
          <a href="#platform">{t.nav.product}</a>
          <a href="#how">{t.nav.how}</a>
          <a href="#ai">{t.nav.ai}</a>
          <a href="#security">{t.nav.security}</a>
          <a href="#bi">{t.nav.bi}</a>
          <a href="#faq">{t.nav.faq}</a>
        </div>
        <div className="nav-right">
          <div className="lang" role="tablist" aria-label="Language">
            <button className={lang === "it" ? "on" : ""} onClick={() => setLang("it")}>IT</button>
            <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
          </div>
          <a className="btn primary small" href={DEMO_URL}>
            {t.nav.cta} <span className="btn-arrow">→</span>
          </a>
        </div>
      </div>
    </nav>
  );
}

// ----------------------------------------------------------------------------
// Hero — headline + live chart
// ----------------------------------------------------------------------------
function HeroChart({ title, note }) {
  const ref = useRef(null);
  const chartRef = useRef(null);
  const dataRef = useRef([]);

  useEffect(() => {
    if (!window.echarts || !ref.current) return;
    const chart = window.echarts.init(ref.current, null, { renderer: "svg" });
    chartRef.current = chart;

    const N = 40;
    const now = Date.now();
    const seed = [];
    for (let i = N - 1; i >= 0; i--) {
      // Simulate retail traffic curve (hours pattern-like)
      const t = (N - i) / N;
      const base = 12 + 20 * Math.sin(t * Math.PI * 1.6) + Math.random() * 6;
      seed.push([now - i * 3000, Math.max(2, Math.round(base))]);
    }
    dataRef.current = seed;

    const s = getComputedStyle(document.documentElement);
    const accent = s.getPropertyValue("--accent").trim();
    const accent2 = s.getPropertyValue("--accent-2").trim();
    const ink2 = s.getPropertyValue("--ink-2").trim();
    const line = s.getPropertyValue("--line").trim();
    const bg = s.getPropertyValue("--bg-2").trim();

    chart.setOption({
      animation: true,
      grid: { left: 40, right: 12, top: 20, bottom: 30 },
      xAxis: {
        type: "time",
        axisLine: { lineStyle: { color: line } },
        axisLabel: {
          color: ink2,
          fontFamily: "JetBrains Mono, monospace",
          fontSize: 10,
          formatter: (v) => {
            const d = new Date(v);
            return String(d.getMinutes()).padStart(2, "0") + ":" + String(d.getSeconds()).padStart(2, "0");
          },
        },
        splitLine: { show: false },
      },
      yAxis: {
        type: "value",
        min: 0,
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { color: ink2, fontFamily: "JetBrains Mono, monospace", fontSize: 10 },
        splitLine: { lineStyle: { color: line, type: "dashed" } },
      },
      series: [
        {
          type: "line",
          smooth: 0.35,
          showSymbol: false,
          data: dataRef.current,
          lineStyle: { color: accent, width: 2 },
          areaStyle: {
            color: {
              type: "linear",
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: `color-mix(in oklch, ${accent} 35%, transparent)` },
                { offset: 1, color: `color-mix(in oklch, ${accent} 0%, transparent)` },
              ],
            },
          },
        },
      ],
    });

    const tick = setInterval(() => {
      const arr = dataRef.current;
      const last = arr[arr.length - 1];
      const prevV = last[1];
      const drift = (Math.random() - 0.45) * 6;
      const v = Math.max(2, Math.round(prevV + drift));
      arr.push([Date.now(), v]);
      while (arr.length > 40) arr.shift();
      chart.setOption({ series: [{ data: arr }] });
    }, 1500);

    const onResize = () => chart.resize();
    window.addEventListener("resize", onResize);

    return () => {
      clearInterval(tick);
      window.removeEventListener("resize", onResize);
      chart.dispose();
    };
  }, []);

  // Redraw colors when theme changes (tweaks)
  useEffect(() => {
    const obs = new MutationObserver(() => {
      if (!chartRef.current) return;
      const s = getComputedStyle(document.documentElement);
      const accent = s.getPropertyValue("--accent").trim();
      const line = s.getPropertyValue("--line").trim();
      const ink2 = s.getPropertyValue("--ink-2").trim();
      chartRef.current.setOption({
        xAxis: { axisLine: { lineStyle: { color: line } }, axisLabel: { color: ink2 } },
        yAxis: { axisLabel: { color: ink2 }, splitLine: { lineStyle: { color: line, type: "dashed" } } },
        series: [{
          lineStyle: { color: accent, width: 2 },
          areaStyle: {
            color: {
              type: "linear", x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: `color-mix(in oklch, ${accent} 35%, transparent)` },
                { offset: 1, color: `color-mix(in oklch, ${accent} 0%, transparent)` },
              ],
            },
          },
        }],
      });
    });
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ["style", "data-theme"] });
    return () => obs.disconnect();
  }, []);

  return (
    <div className="chart-card">
      <div className="chart-head">
        <div>
          <div className="mono" style={{ color: "var(--ink-2)" }}>{title}</div>
          <div style={{ fontSize: 11, color: "var(--ink-2)", marginTop: 2 }} className="mono">{note}</div>
        </div>
        <div className="live">
          <span className="live-dot"></span> LIVE
        </div>
      </div>
      <div id="hero-chart" ref={ref}></div>
    </div>
  );
}

function Hero({ t }) {
  return (
    <section className="hero" id="top">
      <div className="container">
        <div className="hero-grid">
          <div>
            <div className="eyebrow">{t.hero.eyebrow}</div>
            <h1 className="mt-24" style={{ marginTop: 20 }}>
              {t.hero.title_a}
              <span className="b">{t.hero.title_b}</span>
            </h1>
            <p className="sub">{t.hero.sub}</p>
            <div className="hero-cta">
              <a className="btn primary" href={DEMO_URL}>
                {t.hero.cta_primary} <span className="btn-arrow">→</span>
              </a>
              <a href="#how" className="btn ghost">{t.hero.cta_secondary}</a>
            </div>
            <div className="hero-trust">
              {t.hero.trust.map((it, i) => <span key={i}>{it}</span>)}
            </div>
          </div>
          <HeroChart title={t.hero.chart_title} note={t.hero.chart_note} />
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// Social proof — numeric counters
// ----------------------------------------------------------------------------
function ProofCounter({ target, suffix }) {
  const ref = useRef(null);
  const done = useRef(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !done.current) {
          done.current = true;
          const dur = 1400;
          const t0 = performance.now();
          const step = (t) => {
            const p = Math.min(1, (t - t0) / dur);
            const eased = 1 - Math.pow(1 - p, 3);
            const v = Math.round(target * eased);
            el.textContent = v.toLocaleString("it-IT") + suffix;
            if (p < 1) requestAnimationFrame(step);
          };
          requestAnimationFrame(step);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [target, suffix]);
  return <span ref={ref}>{target.toLocaleString("it-IT")}{suffix}</span>;
}

function SocialProof({ t }) {
  return (
    <section className="proof" id="proof">
      <div className="container">
        <div className="proof-grid">
          {t.proof.items.map((it, i) => (
            <div className="proof-item reveal" key={i}>
              <div className="proof-v">
                <ProofCounter target={it.v} suffix={it.suffix} />
              </div>
              <div className="proof-l">{it.l}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// Problem
// ----------------------------------------------------------------------------
function Problem({ t }) {
  return (
    <section id="problem">
      <div className="container">
        <div className="reveal">
          <div className="eyebrow">{t.problem.eyebrow}</div>
          <h2 className="mt-24" style={{ maxWidth: "18ch", marginTop: 20 }}>{t.problem.title}</h2>
          <p className="sub mt-24">{t.problem.sub}</p>
        </div>
        <div className="problem-grid reveal">
          {t.problem.items.map((it, i) => (
            <div className="problem-item" key={i}>
              <div className="n">{it.n}</div>
              <div>
                <h3>{it.t}</h3>
                <p>{it.d}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// Showcase — full-bleed editorial image
// ----------------------------------------------------------------------------
function Showcase({ t }) {
  return (
    <section className="showcase" id="showcase" aria-label="In-store people flow study">
      <div className="showcase-inner reveal">
        <img
          className="showcase-img"
          src="assets/store-flow-new.jpg"
          alt="Top-down architectural illustration of a boutique with color-coded customer and staff circulation paths"
          loading="lazy"
        />
        <div className="showcase-caption">
          <div className="quote" dangerouslySetInnerHTML={{ __html: t.showcase.quote }} />
          <div className="meta"><span className="dot"></span>{t.showcase.meta}</div>
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// Platform
// ----------------------------------------------------------------------------
function Platform({ t }) {
  return (
    <section id="platform">
      <div className="container">
        <div className="head-row reveal">
          <div>
            <div className="eyebrow">{t.platform.eyebrow}</div>
            <h2 className="head-title mt-24" style={{ marginTop: 20 }}>{t.platform.title}</h2>
          </div>
          <p className="sub" style={{ maxWidth: "40ch" }}>{t.platform.sub}</p>
        </div>
        <div className="features">
          {t.platform.features.map((f, i) => (
            <div className="feature reveal" key={i} style={{ transitionDelay: `${i * 60}ms` }}>
              <div className="k">{f.k}</div>
              <h3 className="serif">{f.t}</h3>
              <p>{f.d}</p>
              <span className="tag">{f.tag}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// Architecture — flow with pulse
// ----------------------------------------------------------------------------
function Architecture({ t }) {
  const wrapRef = useRef(null);
  const [active, setActive] = useState(0);

  useEffect(() => {
    const el = wrapRef.current;
    if (!el) return;
    let timer = null;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          // Start cycling
          if (!timer) {
            timer = setInterval(() => {
              setActive((a) => (a + 1) % t.architecture.nodes.length);
            }, 1800);
          }
        } else {
          if (timer) { clearInterval(timer); timer = null; }
        }
      });
    }, { threshold: 0.3 });
    io.observe(el);
    return () => {
      io.disconnect();
      if (timer) clearInterval(timer);
    };
  }, [t.architecture.nodes.length]);

  return (
    <section id="how" className="arch">
      <div className="container">
        <div className="reveal">
          <div className="eyebrow">{t.architecture.eyebrow}</div>
          <h2 className="mt-24" style={{ marginTop: 20, maxWidth: "20ch" }}>{t.architecture.title}</h2>
          <p className="sub mt-24">{t.architecture.sub}</p>
        </div>
        <div className="arch-flow reveal" ref={wrapRef}>
          {t.architecture.nodes.map((n, i) => (
            <div className={`arch-node ${active === i ? "active" : ""}`} key={i}>
              <div>
                <div className="idx">0{i + 1}</div>
                <h3 className="serif">{n.t}</h3>
                <p>{n.d}</p>
              </div>
              <span className="tag">{n.tag}</span>
              {i < t.architecture.nodes.length - 1 && <span className="arch-arrow"></span>}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// AI Assistant with animated chat
// ----------------------------------------------------------------------------
function AI({ t }) {
  const [visible, setVisible] = useState(0);
  const wrapRef = useRef(null);
  const startedRef = useRef(false);

  useEffect(() => {
    const el = wrapRef.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !startedRef.current) {
          startedRef.current = true;
          let i = 0;
          const total = t.ai.chat.length;
          const step = () => {
            i++;
            setVisible(i);
            if (i < total) setTimeout(step, 1400);
          };
          setTimeout(step, 400);
        }
      });
    }, { threshold: 0.35 });
    io.observe(el);
    return () => io.disconnect();
  }, [t.ai.chat.length]);

  // Reset when language changes
  useEffect(() => {
    startedRef.current = false;
    setVisible(0);
    const el = wrapRef.current;
    if (!el) return;
    // Retrigger check
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight && rect.bottom > 0) {
      startedRef.current = true;
      let i = 0;
      const total = t.ai.chat.length;
      const step = () => {
        i++;
        setVisible(i);
        if (i < total) setTimeout(step, 1200);
      };
      setTimeout(step, 300);
    }
  }, [t]);

  const renderBubble = (text) => {
    // Support **bold**
    const parts = text.split(/(\*\*[^*]+\*\*)/g);
    return parts.map((p, i) =>
      p.startsWith("**") && p.endsWith("**")
        ? <strong key={i}>{p.slice(2, -2)}</strong>
        : <span key={i}>{p}</span>
    );
  };

  return (
    <section id="ai">
      <div className="container">
        <div className="ai-grid">
          <div className="reveal">
            <div className="eyebrow">{t.ai.eyebrow}</div>
            <h2 className="mt-24" style={{ marginTop: 20 }}>{t.ai.title}</h2>
            <p className="sub mt-24">{t.ai.sub}</p>
            <ul className="ai-bullets">
              {t.ai.bullets.map((b, i) => <li key={i}>{b}</li>)}
            </ul>
          </div>
          <div className="chat-window reveal" ref={wrapRef}>
            <div className="chat-head">
              <div className="chat-dots"><span></span><span></span><span></span></div>
              <span>peopleflow · ai assistant · mcp</span>
            </div>
            <div className="chat-body">
              {t.ai.chat.map((m, i) => (
                <div className={`msg ${m.who} ${i < visible ? "show" : ""}`} key={i}>
                  <div className="bubble">{renderBubble(m.text)}</div>
                </div>
              ))}
            </div>
            <div className="chat-input">
              <span>{'>'}</span>
              <span>{t.ai.chat[0].text.slice(0, 24)}...</span>
              <span className="chat-caret"></span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// Security
// ----------------------------------------------------------------------------
function Security({ t }) {
  return (
    <section id="security">
      <div className="container">
        <div className="reveal">
          <div className="eyebrow">{t.security.eyebrow}</div>
          <h2 className="mt-24" style={{ marginTop: 20, maxWidth: "20ch" }}>{t.security.title}</h2>
          <p className="sub mt-24">{t.security.sub}</p>
        </div>
        <div className="sec-grid reveal">
          {t.security.items.map((it, i) => (
            <div className="sec-item" key={i}>
              <div className="t">{it.t}</div>
              <div className="d">{it.d}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// Comparison
// ----------------------------------------------------------------------------
function Compare({ t }) {
  return (
    <section id="compare">
      <div className="container">
        <div className="reveal">
          <div className="eyebrow">{t.compare.eyebrow}</div>
          <h2 className="mt-24" style={{ marginTop: 20 }}>{t.compare.title}</h2>
        </div>
        <div className="compare-wrap reveal">
          <table className="compare-table">
            <thead>
              <tr>
                <th></th>
                <th className="us">{t.compare.cols[0]}</th>
                <th>{t.compare.cols[1]}</th>
                <th>{t.compare.cols[2]}</th>
              </tr>
            </thead>
            <tbody>
              {t.compare.rows.map((r, i) => (
                <tr key={i}>
                  <td className="label">{r.l}</td>
                  <td className="us"><span className="tick"></span>{r.v[0]}</td>
                  <td className="them">{r.v[1]}</td>
                  <td className="them">{r.v[2]}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// Stats — animated counters
// ----------------------------------------------------------------------------
function StatValue({ value }) {
  // Extract leading number if any, animate it; else just render
  const numMatch = String(value).match(/^([≥]?)(\d+(?:[.,]\d+)?)(%?.*)$/);
  const ref = useRef(null);
  const done = useRef(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !done.current) {
          done.current = true;
          if (!numMatch) return;
          const prefix = numMatch[1] || "";
          const target = parseFloat(numMatch[2].replace(",", "."));
          const suffix = numMatch[3] || "";
          const isInt = !numMatch[2].includes(".") && !numMatch[2].includes(",");
          const dur = 1200;
          const t0 = performance.now();
          const step = (t) => {
            const p = Math.min(1, (t - t0) / dur);
            const eased = 1 - Math.pow(1 - p, 3);
            const v = target * eased;
            el.textContent = prefix + (isInt ? Math.round(v) : v.toFixed(1)) + suffix;
            if (p < 1) requestAnimationFrame(step);
            else el.textContent = value;
          };
          requestAnimationFrame(step);
        }
      });
    }, { threshold: 0.5 });
    io.observe(el);
    return () => io.disconnect();
  }, [value]);

  // Fallback: render the real value so it's readable even if the observer
  // never fires (JS off, some sandboxed iframes, etc). The animation just
  // overwrites textContent when it starts.
  return <div className="stat-v" ref={ref}>{value}</div>;
}

function Stats({ t }) {
  return (
    <section className="stats" id="stats">
      <div className="container">
        <div className="reveal">
          <div className="eyebrow">— 2026</div>
          <h2 className="mt-24" style={{ marginTop: 20, maxWidth: "16ch" }}>{t.stats.title}</h2>
        </div>
        <div className="stats-grid reveal">
          {t.stats.items.map((it, i) => (
            <div className="stat-item" key={i}>
              <StatValue value={it.v} />
              <div className="stat-l">{it.l}</div>
              <div className="stat-sub">{it.sub}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// BI Integration
// ----------------------------------------------------------------------------
function BI({ t }) {
  return (
    <section id="bi">
      <div className="container">
        <div className="reveal">
          <div className="eyebrow">{t.bi.eyebrow}</div>
          <h2 className="mt-24" style={{ marginTop: 20, maxWidth: "20ch" }}>{t.bi.title}</h2>
          <p className="sub mt-24">{t.bi.sub}</p>
        </div>
        <div className="bi-badges reveal">
          {t.bi.badges.map((b, i) => <span className="bi-badge" key={i}>{b}</span>)}
        </div>
        <div className="bi-grid reveal">
          {t.bi.items.map((it, i) => (
            <div className="bi-item" key={i}>
              <h3 className="serif">{it.t}</h3>
              <p>{it.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// Testimonials
// ----------------------------------------------------------------------------
function Testimonials({ t }) {
  return (
    <section id="testimonials" style={{ background: "var(--bg-2)", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
      <div className="container">
        <div className="reveal">
          <div className="eyebrow">{t.testimonials.eyebrow}</div>
          <h2 className="mt-24" style={{ marginTop: 20, maxWidth: "22ch" }}>{t.testimonials.title}</h2>
        </div>
        <div className="testi-grid">
          {t.testimonials.items.map((it, i) => (
            <div className="testi reveal" key={i} style={{ transitionDelay: `${i * 80}ms` }}>
              <div className="testi-mark">"</div>
              <p className="testi-quote">{it.quote}</p>
              <div className="testi-author">
                <div className="testi-name">{it.name}</div>
                <div className="testi-role">{it.role}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// FAQ
// ----------------------------------------------------------------------------
function FAQ({ t }) {
  const [open, setOpen] = useState(0);
  return (
    <section id="faq">
      <div className="container">
        <div className="reveal">
          <div className="eyebrow">{t.faq.eyebrow}</div>
          <h2 className="mt-24" style={{ marginTop: 20, maxWidth: "22ch" }}>{t.faq.title}</h2>
        </div>
        <div className="faq-list reveal">
          {t.faq.items.map((it, i) => (
            <div
              key={i}
              className={`faq-item ${open === i ? "open" : ""}`}
              onClick={() => setOpen(open === i ? -1 : i)}
            >
              <div className="faq-q">
                <span>{it.q}</span>
                <span className="faq-plus">+</span>
              </div>
              <div className="faq-a">{it.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// Final CTA
// ----------------------------------------------------------------------------
function FinalCTA({ t }) {
  return (
    <section className="final" id="cta">
      <div className="container">
        <div className="reveal">
          <div className="eyebrow">→ 30 min</div>
          <h2 className="mt-24" style={{ marginTop: 20 }}>{t.finalCta.title}</h2>
          <p className="sub">{t.finalCta.sub}</p>
          <a className="btn primary" style={{ padding: "16px 28px", fontSize: 16 }} href={DEMO_URL}>
            {t.finalCta.cta} <span className="btn-arrow">→</span>
          </a>
        </div>
      </div>
    </section>
  );
}

// ----------------------------------------------------------------------------
// Sticky CTA (mobile only, appears after scrolling past hero)
// ----------------------------------------------------------------------------
function StickyCTA({ t }) {
  const [show, setShow] = useState(false);
  useEffect(() => {
    const onScroll = () => {
      setShow(window.scrollY > window.innerHeight * 0.8 && window.scrollY < document.documentElement.scrollHeight - window.innerHeight * 1.5);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <div className={`sticky-cta ${show ? "on" : ""}`}>
      <a className="btn primary" href={DEMO_URL}>
        {t.stickyCta} <span className="btn-arrow">→</span>
      </a>
    </div>
  );
}

// ----------------------------------------------------------------------------
// Cookie banner (technical cookies only — no tracking to accept, but we show
// respect for the user's presence)
// ----------------------------------------------------------------------------
function CookieBanner({ t }) {
  const [show, setShow] = useState(false);
  useEffect(() => {
    try {
      if (!localStorage.getItem("pf_cookie_ack")) {
        setTimeout(() => setShow(true), 1200);
      }
    } catch {}
  }, []);
  const dismiss = () => {
    try { localStorage.setItem("pf_cookie_ack", "1"); } catch {}
    setShow(false);
  };
  return (
    <div className={`cookie ${show ? "on" : ""}`} role="region" aria-label="Cookie">
      <p>
        {t.cookie.msg}{" "}
        <a href="https://n3xtgentech.it/privacy-policy.html" target="_blank" rel="noopener noreferrer">{t.cookie.link}</a>
      </p>
      <div className="cookie-actions">
        <button className="btn small ghost" onClick={dismiss}>{t.cookie.only}</button>
        <button className="btn small primary" onClick={dismiss}>{t.cookie.accept}</button>
      </div>
    </div>
  );
}

// ----------------------------------------------------------------------------
// Footer
// ----------------------------------------------------------------------------
function Footer({ t }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <div className="logo">
              <RibbonMark />
              <span>PeopleFlow</span>
              <span className="logo-v">v2.0</span>
            </div>
            <p>{t.footer.tagline}</p>
          </div>
          {t.footer.cols.map((c, i) => (
            <div key={i}>
              <h4>{c.t}</h4>
              <ul>
                {c.items.map((it, j) => (
                  <li key={j}>
                    {it.h
                      ? <a href={it.h} {...(it.h.startsWith("http") ? { target: "_blank", rel: "noopener noreferrer" } : {})}>{it.l}</a>
                      : <span style={{ color: "var(--ink-2)" }}>{it.l}</span>
                    }
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div className="footer-legal">{t.footer.copyright}</div>
      </div>
    </footer>
  );
}

// ----------------------------------------------------------------------------
// Tweaks system removed — palette + font definitivi vivono in styles.css :root
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------
// Root App
// ----------------------------------------------------------------------------
function App() {
  const { lang, setLang, t } = useLang();
  useReveal();

  return (
    <>
      <Nav lang={lang} setLang={setLang} t={t} />
      <main id="main">
        <Hero t={t} />
        <SocialProof t={t} />
        <Problem t={t} />
        <Showcase t={t} />
        <Platform t={t} />
        <Architecture t={t} />
        <AI t={t} />
        <Security t={t} />
        <BI t={t} />
        <Compare t={t} />
        <Testimonials t={t} />
        <Stats t={t} />
        <FAQ t={t} />
        <FinalCTA t={t} />
      </main>
      <Footer t={t} />
      <StickyCTA t={t} />
      <CookieBanner t={t} />
    </>
  );
}

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