/* ============================================================================
   REBUILT LANDING — the data-driven template the site reconfigures into.
   Reads entirely from problem × lab. Hosts: dynamic nav, OS hero, solutions,
   "Do Nothing" timeline, "Your Company After AI" simulator, architect band,
   footer. A persistent re-diagnose control means the visitor is never trapped.
   ============================================================================ */
const { useState: useStateL, useRef: useRefL, useEffect: useEffectL } = React;

function smoothTo(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const y = el.getBoundingClientRect().top + window.pageYOffset - 64;
  window.scrollTo({ top: y, behavior: window.prefersReduced() ? "auto" : "smooth" });
}

function HeroVisual({ accent }) {
  // abstract system diagram — simple nodes + links, gently animated
  const nodes = [
    [50, 18], [20, 40], [80, 38], [34, 70], [66, 72], [50, 50],
  ];
  const links = [[5, 0], [5, 1], [5, 2], [5, 3], [5, 4], [0, 1], [0, 2], [1, 3], [2, 4], [3, 4]];
  return React.createElement(
    "div",
    { className: "hero-visual" },
    React.createElement(
      "svg",
      { viewBox: "0 0 100 90", className: "hv-svg" },
      links.map((l, i) =>
        React.createElement("line", {
          key: i, x1: nodes[l[0]][0], y1: nodes[l[0]][1], x2: nodes[l[1]][0], y2: nodes[l[1]][1],
          className: "hv-link", style: { "--d": `${i * 0.12}s` },
        })
      ),
      nodes.map((n, i) =>
        React.createElement("circle", {
          key: i, cx: n[0], cy: n[1], r: i === 5 ? 4.5 : 2.6,
          className: `hv-node ${i === 5 ? "core" : ""}`, style: { "--d": `${i * 0.15}s` },
        })
      )
    ),
    React.createElement("div", { className: "hv-grid" })
  );
}

function Landing({ problem, lab, pains, onRediagnose, onGoToLab }) {
  const { osFor, orderedSolutions, composePains } = window.TALYA_DATA;
  const info = osFor(problem, lab.key);
  const sols = orderedSolutions(lab.key, problem);
  const painInfo = composePains(pains || []);
  const { platformByName, builtOnFor } = window.TALYA_PLATFORMS;
  // elevation: Operator AI · Private GPU / Personal AI Model lead the solutions when pains call for it
  const elevated = [];
  if (painInfo.elevateGPU) {
    const g = platformByName("Operator AI · Private GPU");
    if (g) elevated.push({ name: g.name, desc: g.tagline, elevated: true });
  }
  if (painInfo.elevatePersonalAI && lab.key !== "personal-ai") {
    const pm = platformByName("Personal AI Training · Private Operator Model");
    if (pm) elevated.push({ name: pm.name, desc: pm.tagline, elevated: true });
  }
  const displaySols = elevated.concat(sols).slice(0, 4);
  const [inputs, setInputs] = useStateL({
    lab, problem: window.TALYA_DATA.PROBLEMS.find((p) => p.key === problem),
    revenue: 2000000, employees: 50,
  });
  const [scrolled, setScrolled] = useStateL(false);
  const [navOpen, setNavOpen] = useStateL(false);
  const [flashSol, setFlashSol] = useStateL(-1);
  const [tierId, setTierIdRaw] = useStateL(() => localStorage.getItem("ts_tier") || "t4");
  const [complexityId, setComplexityIdRaw] = useStateL(() => localStorage.getItem("ts_complexity") || "m");
  const [roi, setRoi] = useStateL({ turnover: 2000000, efficiency: 0.10, revenue: 0.05 });
  const [size, setSizeRaw] = useStateL(() => localStorage.getItem("ts_size") || "SME");
  const setSize = (v) => { setSizeRaw(v); try { localStorage.setItem("ts_size", v); } catch (e) {} };
  const setTierId = (v) => { setTierIdRaw(v); try { localStorage.setItem("ts_tier", v); } catch (e) {} };
  const setComplexityId = (v) => { setComplexityIdRaw(v); try { localStorage.setItem("ts_complexity", v); } catch (e) {} };

  function gotoSolution(i) {
    smoothTo(`sol-${i}`);
    setFlashSol(i);
    setTimeout(() => setFlashSol(-1), 1300);
  }

  useEffectL(() => {
    const onScroll = () => setScrolled(window.pageYOffset > 24);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // close the expanded menu on Escape
  useEffectL(() => {
    if (!navOpen) return;
    const onKey = (e) => { if (e.key === "Escape") setNavOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [navOpen]);

  function navJump(id) {
    setNavOpen(false);
    smoothTo(id);
  }

  // Full section map for the expanded "Explore" menu.
  const navSections = [
    { group: "Explore the platform", items: [
      { id: "solutions", label: "The OS, assembled", note: "Your four core systems" },
      { id: "pillars", label: "What Talya Smart is", note: "The four pillars" },
      { id: "behind", label: "Private-label engine", note: "Your brand, our build" },
      { id: "maturity", label: "AI maturity curve", note: "Where you sit today" },
    ] },
    { group: "Decide & build", items: [
      { id: "donothing", label: "The cost of waiting", note: "If you do nothing" },
      { id: "simulator", label: "Your company after AI", note: "Model the upside" },
      { id: "discovery", label: "Discover platforms", note: "Find your build" },
      { id: "pricing", label: "Price the build", note: "Tiers & ROI" },
      { id: "architect", label: "Three ways in", note: "Start the 8-week clock" },
    ] },
  ];

  // Curated, fixed nav — meaningful section anchors that don't shuffle per diagnosis.
  const navItems = [
    { id: "solutions", label: "The OS" },
    { id: "donothing", label: "Cost of waiting" },
    { id: "simulator", label: "After AI" },
    { id: "pricing", label: "Pricing" },
    { id: "architect", label: "Three ways in" },
  ];

  return React.createElement(
    "div",
    { className: "landing" },

    /* ---- top nav ---- */
    React.createElement(
      "header",
      { className: `topnav ${scrolled ? "is-scrolled" : ""}` },
      React.createElement(Logo, { size: 26, onClick: onRediagnose, variant: "lockup" }),
      React.createElement(
        "nav",
        { className: "topnav-labnav" },
        navItems.map((n) =>
          React.createElement("button", { key: n.id, type: "button", className: "topnav-link", onClick: () => smoothTo(n.id) }, n.label)
        )
      ),
      React.createElement(
        "div",
        { className: "topnav-right" },
        React.createElement("div", { className: "size-toggle" },
          ["SME", "Enterprise"].map((s) =>
            React.createElement("button", {
              key: s, type: "button", className: `size-opt ${size === s ? "on" : ""}`,
              onClick: () => setSize(s),
            }, s)
          )
        ),
        React.createElement("button", { type: "button", className: "topnav-link global", onClick: () => smoothTo("discovery") }, "Discover"),
        React.createElement("button", { type: "button", className: "topnav-link global", onClick: onRediagnose }, "Re-diagnose"),
        React.createElement("button", { type: "button", className: "btn btn-primary sm", onClick: () => smoothTo("architect") }, "Build my platform →"),
        React.createElement("button", {
          type: "button", className: `nav-explore ${navOpen ? "on" : ""}`,
          "aria-expanded": navOpen, "aria-label": "Explore all sections",
          onClick: () => setNavOpen((v) => !v),
        },
          React.createElement("span", { className: "nav-explore-bars" },
            React.createElement("span", null), React.createElement("span", null), React.createElement("span", null)),
          React.createElement("span", { className: "nav-explore-label" }, navOpen ? "Close" : "Explore")
        )
      )
    ),

    /* ---- expanded "Explore" menu (all screen sizes) ---- */
    navOpen && React.createElement("div", { className: "nav-menu-scrim", onClick: () => setNavOpen(false) }),
    navOpen && React.createElement(
      "div",
      { className: "nav-menu", role: "menu" },
      React.createElement("div", { className: "nav-menu-inner" },
        navSections.map((sec) =>
          React.createElement("div", { className: "nav-menu-col", key: sec.group },
            React.createElement("span", { className: "nav-menu-group mono" }, sec.group),
            sec.items.map((it) =>
              React.createElement("button", {
                key: it.id, type: "button", className: "nav-menu-item", role: "menuitem",
                onClick: () => navJump(it.id),
              },
                React.createElement("span", { className: "nav-menu-item-label" }, it.label),
                React.createElement("span", { className: "nav-menu-item-note" }, it.note),
                React.createElement("span", { className: "nav-menu-item-arrow" }, "\u2192")
              )
            )
          )
        ),
        React.createElement("div", { className: "nav-menu-col nav-menu-actions" },
          React.createElement("span", { className: "nav-menu-group mono" }, "Quick actions"),
          React.createElement("button", { type: "button", className: "nav-menu-action", onClick: () => { setNavOpen(false); onRediagnose(); } }, "\u27F2  Re-diagnose"),
          React.createElement("a", { className: "nav-menu-action", href: "Templates.html", onClick: () => setNavOpen(false) }, "\u2709  Message templates"),
          React.createElement("button", { type: "button", className: "nav-menu-action primary", onClick: () => navJump("architect") }, "Build my platform \u2192")
        )
      )
    ),

    /* ---- OS hero ---- */
    React.createElement(
      "section",
      { className: "os-hero", "data-screen-label": "OS Hero" },
      React.createElement(
        "div",
        { className: "os-hero-text" },
        React.createElement("div", { className: "os-chip-row reveal-now d0" },
          React.createElement(Chip, { accent: lab.accent, className: "solid os-chip" }, info.os),
          React.createElement("span", { className: "os-lab-name mono" }, lab.name)
        ),
        React.createElement("h1", { className: "os-headline reveal-now d1" }, info.hero),
        painInfo.topCopy &&
          React.createElement("p", { className: "os-pain reveal-now d2" },
            React.createElement("span", { className: "os-pain-quote" }, "“", painInfo.topCopy, "”"),
            React.createElement("span", { className: "os-pain-tag mono" }, "We heard you. The rebuild starts here.")
          ),
        React.createElement("p", { className: "os-vision reveal-now d2" },
          "By 2030, ", React.createElement("span", { className: "accent-text" }, info.lab.vision), "."),
        React.createElement(
          "div",
          { className: "os-cta reveal-now d3" },
          React.createElement("button", { type: "button", className: "btn btn-primary lg", onClick: () => smoothTo("simulator") }, "Build my company after AI"),
          React.createElement("button", { type: "button", className: "btn btn-ghost lg", onClick: () => smoothTo("donothing") }, "See what happens if you wait →")
        ),
        React.createElement(
          "div",
          { className: "os-exemplars reveal-now d4" },
          React.createElement("span", { className: "os-exemplars-label mono" }, "PROOF OF THE SHIFT"),
          React.createElement("span", { className: "os-exemplars-list" }, lab.exemplars.join("  ·  "))
        )
      ),
      React.createElement("div", { className: "os-hero-visual reveal-now d2" }, React.createElement(HeroVisual, { accent: lab.accent }))
    ),

    /* ---- solutions ---- */
    React.createElement(
      "section",
      { className: "section solutions", id: "solutions", "data-screen-label": "Solutions" },
      React.createElement(
        "div",
        { className: "section-head" },
        React.createElement("span", { className: "kicker" }, lab.short, " Intelligence"),
        React.createElement("h2", { className: "section-title" }, "The ", info.os, ", assembled"),
        React.createElement("p", { className: "section-lede" }, "Four systems, reordered around ", React.createElement("span", { className: "accent-text" }, info.problem.label.toLowerCase()), " — your fastest path to the future state.")
      ),
      React.createElement(
        "div",
        { className: "sol-grid" },
        displaySols.map((s, i) => {
          const built = builtOnFor(lab.key, i, { elevateName: s.elevated ? s.name : undefined });
          return React.createElement(
            Reveal,
            { key: s.name, id: `sol-${i}`, delay: i * 70, className: `sol-card ${flashSol === i ? "sol-flash" : ""} ${s.elevated ? "sol-elevated" : ""}` },
            s.elevated && React.createElement("span", { className: "sol-elevated-tag mono" }, "Recommended for you"),
            React.createElement("span", { className: "sol-num mono" }, String(i + 1).padStart(2, "0")),
            React.createElement("h3", { className: "sol-name" }, s.name),
            React.createElement("p", { className: "sol-desc" }, s.desc),
            built.length &&
              React.createElement(
                "div",
                { className: "built-on" },
                React.createElement("span", { className: "built-on-label mono" }, "Built on"),
                React.createElement(
                  "div",
                  { className: "built-on-list" },
                  built.map((p) =>
                    React.createElement("span", { className: "built-on-item", key: p.key },
                      React.createElement("span", { className: "bo-dot", style: { background: lab.accent } }),
                      p.name)
                  )
                )
              ),
            React.createElement("span", { className: "sol-arrow" }, "→")
          );
        })
      )
    ),

    /* ---- four pillars + platform-behind + maturity (proof) ---- */
    React.createElement(FourPillars, null),
    React.createElement(PlatformBehind, { lab, info }),
    React.createElement(MaturityCurve, { sme: size === "SME", lab }),

    /* ---- do nothing ---- */
    React.createElement("div", { id: "donothing", "data-screen-label": "Do Nothing" }, React.createElement(DoNothing, { lab })),

    /* ---- simulator ---- */
    React.createElement("div", { id: "simulator", "data-screen-label": "Simulator" }, React.createElement(Simulator, { inputs, setInputs, size })),

    /* ---- platform discovery engine ---- */
    React.createElement(DiscoveryEngine, { onGoToLab }),

    /* ---- price the build ---- */
    React.createElement(PriceTheBuild, { tierId, setTierId, complexityId, setComplexityId, roi, setRoi }),

    /* ---- three-path CTA (replaces single architect CTA) ---- */
    React.createElement(ThreePathCTA, { tierId, complexityId, lab, onRediagnose, soften: painInfo.soften }),

    /* ---- footer ---- */
    React.createElement(
      "footer",
      { className: "footer" },
      React.createElement("div", { className: "footer-motto" },
        React.createElement("span", null, "You are late. ", React.createElement("span", { className: "accent-text" }, "But not too late!")),
        React.createElement("span", { className: "footer-motto-sub" }, "The next decade is being written now.")
      ),
      React.createElement("div", { className: "footer-meta" },
        React.createElement(Logo, { size: 26, onClick: onRediagnose }),
        React.createElement("div", { className: "footer-locations mono" }, "Fair Lawn NJ · Toronto · Dusseldorf · Ljubljana · Dubai · İzmir"),
        React.createElement("a", { className: "footer-mail mono", href: "mailto:info@talyasmart.com" }, "info@talyasmart.com"),
        React.createElement("a", { className: "footer-mail mono footer-tpl", href: "Templates.html" }, "Message & validation templates →")
      )
    ),

    /* ---- mobile bottom bar ---- */
    React.createElement(
      "div",
      { className: "bottombar" },
      React.createElement("button", { type: "button", className: "bb-btn", onClick: onRediagnose },
        React.createElement("span", { className: "bb-ico" }, "⟲"), "Re-diagnose"),
      React.createElement("button", { type: "button", className: "bb-btn", onClick: () => smoothTo("simulator") },
        React.createElement("span", { className: "bb-ico" }, "▦"), "After AI"),
      React.createElement("button", { type: "button", className: "bb-btn primary", onClick: () => smoothTo("architect") },
        React.createElement("span", { className: "bb-ico" }, "→"), "Architect")
    )
  );
}

window.Landing = Landing;
