// SR SOFT — App shell: Navbar + Hero + page composition
// (Sections live in sections.jsx)

const { useState, useEffect, useRef, useMemo } = React;

// ── Reveal hook (IntersectionObserver) ──────────────────────────
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.in)");
    if (!("IntersectionObserver" in window)) {
      els.forEach((el) => el.classList.add("in"));
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -40px 0px" }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

// ── Navbar ───────────────────────────────────────────────────────
const NAV_LINKS = [
  { href: "#home", label: "Home" },
  { href: "#servizi", label: "Servizi" },
  { href: "#metodo", label: "Metodo" },
  { href: "#soluzioni", label: "Soluzioni" },
  { href: "#tecnologie", label: "Tecnologie" },
  { href: "#contatti", label: "Contatti" },
];

function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
  }, [open]);

  const close = () => setOpen(false);

  return (
    <React.Fragment>
      <nav className={"nav" + (scrolled ? " scrolled" : "")}>
        <div className="container nav-inner">
          <a href="#home" className="logo" onClick={close}>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 420 100" height="38" role="img" aria-label="SR SOFT">
              <g fill="none" stroke="#e94f37" strokeWidth="13" strokeLinecap="square" strokeLinejoin="miter">
                <path d="M 92 24 L 36 24 C 28 24 22 30 22 38 C 22 46 28 50 36 50 L 64 50 C 72 50 78 56 78 64 C 78 72 72 76 64 76 L 8 76" />
              </g>
              <path d="M 80 10 L 98 24 L 80 38 Z" fill="#e94f37" />
              <path d="M 20 62 L 2 76 L 20 90 Z" fill="#e94f37" />
              <text x="130" y="62" fontFamily="Inter,'Helvetica Neue',Arial,sans-serif" fontSize="44" fontWeight="700" letterSpacing="-1.5" fill="#ffffff">SR SOFT</text>
              <text x="130" y="84" fontFamily="ui-monospace,'Courier New',monospace" fontSize="11" fontWeight="400" letterSpacing="2.4" fill="#ffffff" fillOpacity="0.55">S.R.L.</text>
            </svg>
          </a>
          <ul className="nav-links">
            {NAV_LINKS.map((l) => (
              <li key={l.href}><a href={l.href}>{l.label}</a></li>
            ))}
          </ul>
          <div className="nav-cta-wrap">
            <a href="#contatti" className="btn btn-sm">
              Parliamo del tuo progetto
              <Arrow />
            </a>
            <button
              className={"hamburger" + (open ? " open" : "")}
              aria-label="Menu"
              aria-expanded={open}
              onClick={() => setOpen((v) => !v)}
            >
              <span></span>
            </button>
          </div>
        </div>
      </nav>
      <div className={"mobile-menu" + (open ? " open" : "")}>
        {NAV_LINKS.map((l) => (
          <a key={l.href} href={l.href} onClick={close}>
            <span>{l.label}</span>
            <Arrow />
          </a>
        ))}
        <a href="#contatti" className="btn" onClick={close}>
          Parliamo del tuo progetto
          <Arrow />
        </a>
      </div>
    </React.Fragment>
  );
}

function Arrow({ size = 14 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ── Hero ─────────────────────────────────────────────────────────
function Hero({ headline }) {
  const words = headline.split(" ");
  return (
    <section className="hero" id="home" data-screen-label="01 Home">
      <Aurora />
      <div className="hero-grid-bg"></div>
      <div className="hero-glow"></div>
      <div className="container hero-inner">
        <div className="hero-copy">
          <div className="eyebrow reveal" style={{ "--delay": "0ms" }}>
            <span>Consulenza · Sviluppo · Integrazione</span>
          </div>
          <h1 className="h-display hero-title">
            {words.map((w, i) => (
              <React.Fragment key={i}>
                <span
                  className="word"
                  style={{ animationDelay: `${0.05 * i + 0.1}s` }}
                >{w}</span>
                {i < words.length - 1 ? " " : ""}
              </React.Fragment>
            ))}
          </h1>
          <p className="lead reveal" style={{ "--delay": "500ms" }}>
            SR SOFT affianca le aziende nell'analisi, progettazione e sviluppo di
            soluzioni digitali personalizzate: gestionali, piattaforme web, app
            mobile, integrazioni API e automazioni per rendere il lavoro più
            efficiente, controllabile e scalabile.
          </p>
          <div className="hero-ctas reveal" style={{ "--delay": "650ms" }}>
            <MagneticBtn href="#contatti" className="btn">
              Raccontaci il tuo progetto
              <Arrow />
            </MagneticBtn>
            <MagneticBtn href="#servizi" className="btn btn-ghost">
              Scopri cosa realizziamo
              <Arrow />
            </MagneticBtn>
          </div>
          <div className="hero-ticker reveal" style={{ "--delay": "800ms" }}>
            <span><span style={{display:"inline-block",width:6,height:6,borderRadius:"50%",background:"var(--accent)",boxShadow:"0 0 10px var(--accent)",marginRight:8,verticalAlign:"middle"}}></span>Disponibili Q2 2026</span>
            <span>Progetti attivi <b>11</b></span>
            <span>Tempo medio analisi <b>2 settimane</b></span>
            <span>Uptime medio <b>99.4%</b></span>
          </div>
        </div>

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

function HeroVisual() {
  const ref = useRef(null);
  usePointerParallax(ref, 16);
  return (
    <div ref={ref} className="hero-visual reveal" style={{ "--delay": "300ms" }}>
      {/* Rotating rings */}
      <div className="hv-ring"></div>
      <div className="hv-ring inner"></div>

      {/* Network lines + nodes + packets */}
      <svg className="hv-net" viewBox="0 0 500 480" preserveAspectRatio="none" data-depth="0.4">
        <defs>
          <path id="path-a" d="M 80 100 C 180 80, 280 200, 420 180" />
          <path id="path-b" d="M 60 300 C 180 320, 300 240, 440 320" />
          <path id="path-c" d="M 250 60 C 240 180, 260 280, 250 420" />
          <path id="path-d" d="M 80 100 C 180 200, 340 240, 440 320" />
        </defs>
        <use href="#path-a" className="line" />
        <use href="#path-b" className="line" />
        <use href="#path-c" className="line" />
        <use href="#path-d" className="line" style={{ opacity: 0.2 }} />

        <circle className="node" cx="80" cy="100" r="4" />
        <circle className="node" cx="420" cy="180" r="4" />
        <circle className="node" cx="60" cy="300" r="4" />
        <circle className="node" cx="440" cy="320" r="4" />
        <circle className="node" cx="250" cy="60" r="4" />
        <circle className="node" cx="250" cy="420" r="4" />

        <circle className="pulse" cx="250" cy="240" r="3" />
        <circle className="pulse" cx="170" cy="160" r="3" style={{ animationDelay: "1s" }} />
        <circle className="pulse" cx="340" cy="280" r="3" style={{ animationDelay: "2s" }} />

        <circle className="packet" r="3.5">
          <animateMotion dur="4s" repeatCount="indefinite" rotate="auto">
            <mpath href="#path-a" />
          </animateMotion>
        </circle>
        <circle className="packet packet-2" r="3">
          <animateMotion dur="5.5s" repeatCount="indefinite" begin="-1.5s">
            <mpath href="#path-b" />
          </animateMotion>
        </circle>
        <circle className="packet" r="2.5">
          <animateMotion dur="6s" repeatCount="indefinite" begin="-2s">
            <mpath href="#path-c" />
          </animateMotion>
        </circle>
        <circle className="packet packet-2" r="3.5">
          <animateMotion dur="7s" repeatCount="indefinite" begin="-0.8s">
            <mpath href="#path-d" />
          </animateMotion>
        </circle>
      </svg>

      {/* Terminal card */}
      <div className="hv-layer" data-depth="1">
        <div className="hv-card hv-terminal">
          <div className="tt-bar">
            <span className="dots"><i></i><i></i><i></i></span>
            <span>~/srsoft/analyze.ts</span>
          </div>
          <div className="tt-line"><span className="c">// analisi processo cliente</span></div>
          <div className="tt-line"><span className="k">const</span> flow = <span className="p">await</span> analyze(</div>
          <div className="tt-line">&nbsp;&nbsp;<span className="s">"ordini → magazzino → fatturazione"</span></div>
          <div className="tt-line">)</div>
          <div className="tt-line"><span className="k">return</span> flow.optimize().<span className="p">automate</span>()<span className="cursor"></span></div>
        </div>
      </div>

      {/* Dashboard card */}
      <div className="hv-layer" data-depth="1.2">
        <div className="hv-card hv-dash">
          <div className="dh-hd">
            <span className="dh-title">Operativo · Real-time</span>
            <span className="dh-sub">↑ 24%</span>
          </div>
          <div className="dh-stats">
            <div className="dh-stat">
              <div className="v"><AnimatedCounter to={1842} /></div>
              <div className="l">Processi</div>
            </div>
            <div className="dh-stat">
              <div className="v"><AnimatedCounter to={99.4} decimals={1} suffix="%" /></div>
              <div className="l">Uptime</div>
            </div>
            <div className="dh-stat">
              <div className="v"><AnimatedCounter to={38} prefix="−" suffix="%" /></div>
              <div className="l">Manuale</div>
            </div>
          </div>
          <Sparkline />
        </div>
      </div>

      {/* Floating chips */}
      <div className="hv-layer" data-depth="1.6">
        <div className="hv-chip hv-chip-1">
          <span className="dot"></span>
          Integrazione API · OK
        </div>
      </div>
      <div className="hv-layer" data-depth="1.8">
        <div className="hv-chip hv-chip-2">
          <span className="dot"></span>
          Build #214 · passed
        </div>
      </div>
    </div>
  );
}

function Sparkline() {
  const path = "M 0 40 L 28 32 L 56 36 L 84 22 L 112 28 L 140 14 L 168 20 L 196 8 L 224 16 L 252 4";
  return (
    <svg className="spark" viewBox="0 0 252 50" preserveAspectRatio="none">
      <defs>
        <linearGradient id="spark-grad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.4" />
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={path + " L 252 50 L 0 50 Z"} fill="url(#spark-grad)" />
      <path d={path} fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ── App composition ─────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#e94f37",
  "headline": "Progettiamo e sviluppiamo sistemi digitali su misura per far evolvere la tua azienda.",
  "density": "regular",
  "showGrid": true,
  "aurora": true,
  "spotlight": true
}/*EDITMODE-END*/;

const HEADLINES = [
  "Progettiamo e sviluppiamo sistemi digitali su misura per far evolvere la tua azienda.",
  "Trasformiamo processi complessi in soluzioni digitali semplici, scalabili e potenti.",
  "Consulenza informatica e software su misura per aziende che vogliono crescere.",
];

const ACCENTS = ["#e94f37", "#ff8c73", "#f59e0b", "#34d399", "#a78bfa"];

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useReveal();

  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--accent", t.accent);
    root.style.setProperty("--accent-glow", hexA(t.accent, 0.32));
    document.body.dataset.density = t.density;
    document.body.dataset.aurora = t.aurora ? "on" : "off";
    document.body.dataset.spot = t.spotlight ? "on" : "off";
  }, [t.accent, t.density, t.aurora, t.spotlight]);

  useEffect(() => {
    const grid = document.querySelector(".hero-grid-bg");
    if (grid) grid.style.display = t.showGrid ? "" : "none";
  }, [t.showGrid]);

  useMethodProgress();

  return (
    <React.Fragment>
      <CursorSpot />
      <Navbar />
      <main>
        <Hero headline={t.headline} />
        <About />
        <Services />
        <WhyUs />
        <Method />
        <Solutions />
        <Technologies />
        <ConsultingApproach />
        <FinalCTA />
      </main>
      <Footer />

      <TweaksPanel>
        <TweakSection label="Brand" />
        <TweakColor
          label="Accento"
          value={t.accent}
          options={ACCENTS}
          onChange={(v) => setTweak("accent", v)}
        />
        <TweakSection label="Hero" />
        <TweakSelect
          label="Titolo"
          value={t.headline}
          options={HEADLINES.map((h, i) => ({ value: h, label: `Variante ${i + 1}` }))}
          onChange={(v) => setTweak("headline", v)}
        />
        <TweakToggle
          label="Grid background"
          value={t.showGrid}
          onChange={(v) => setTweak("showGrid", v)}
        />
        <TweakToggle
          label="Aurora animata"
          value={t.aurora}
          onChange={(v) => setTweak("aurora", v)}
        />
        <TweakToggle
          label="Spotlight cursore"
          value={t.spotlight}
          onChange={(v) => setTweak("spotlight", v)}
        />
        <TweakSection label="Layout" />
        <TweakRadio
          label="Densità"
          value={t.density}
          options={["compact", "regular", "airy"]}
          onChange={(v) => setTweak("density", v)}
        />
      </TweaksPanel>
    </React.Fragment>
  );
}

// ── helpers ──────────────────────────────────────────────────────
function hexA(hex, a) {
  const m = hex.replace("#", "");
  const n = m.length === 3 ? m.split("").map((c) => c + c).join("") : m;
  const r = parseInt(n.slice(0, 2), 16);
  const g = parseInt(n.slice(2, 4), 16);
  const b = parseInt(n.slice(4, 6), 16);
  return `rgba(${r}, ${g}, ${b}, ${a})`;
}

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