/* ============================================================================
   CHECKPOINT 3 — Price the Build (tier ladder + complexity + ROI) and the
   Three-path CTA. Data-driven; all numbers from window.TALYA_PRICING.
   No SaaS-bro CTA language anywhere.
   ============================================================================ */
const { useState: useStatePr, useEffect: useEffectPr, useRef: useRefPr } = React;

/* tween a number from its previous value to the new value; counts up on mount */
function useTweenNum(value, dur = 650) {
  const [v, setV] = useStatePr(0);
  const fromRef = useRefPr(0);
  useEffectPr(() => {
    if (window.prefersReduced() || document.documentElement.classList.contains("no-anim")) {
      setV(value); fromRef.current = value; return;
    }
    const from = fromRef.current, start = performance.now();
    let raf;
    function step(t) {
      const k = Math.min(1, (t - start) / dur);
      const e = 1 - Math.pow(1 - k, 3);
      setV(from + (value - from) * e);
      if (k < 1) raf = requestAnimationFrame(step);
      else fromRef.current = value;
    }
    raf = requestAnimationFrame(step);
    const safety = setTimeout(() => { setV(value); fromRef.current = value; }, dur + 160);
    return () => { cancelAnimationFrame(raf); clearTimeout(safety); };
  }, [value]);
  return v;
}

function TierPrice({ value }) {
  const tv = useTweenNum(value);
  const [flash, setFlash] = useStatePr(false);
  const first = useRefPr(true);
  useEffectPr(() => {
    if (first.current) { first.current = false; return; }
    setFlash(true);
    const t = setTimeout(() => setFlash(false), 260);
    return () => clearTimeout(t);
  }, [value]);
  return React.createElement("div", { className: `tier-price ${flash ? "flash" : ""}` }, window.fmtMoney(tv));
}

function PriceTheBuild({ tierId, setTierId, complexityId, setComplexityId, roi, setRoi }) {
  const { PRICING, tierPrice, roiModel, roiSubline } = window.TALYA_PRICING;

  const model = roiModel({
    turnover: roi.turnover, efficiencyGain: roi.efficiency, revenueLift: roi.revenue,
    tierId, complexityId,
  });
  const tBenefit = useTweenNum(model.annualBenefit);
  const tPayback = useTweenNum(model.paybackMonths);
  const tRoi = useTweenNum(model.roi3yr);
  const [wiggle, setWiggle] = useStatePr(false);
  const prevRoi = useRefPr(model.roi3yr);
  useEffectPr(() => {
    if (prevRoi.current < 5 && model.roi3yr >= 5) { setWiggle(true); setTimeout(() => setWiggle(false), 520); }
    prevRoi.current = model.roi3yr;
  }, [model.roi3yr]);

  const turnoverOpts = [["$500K", 500000], ["$2M", 2000000], ["$10M", 10000000], ["$50M", 50000000], ["$250M+", 250000000]];
  const effOpts = [["5%", 0.05], ["10%", 0.10], ["20%", 0.20], ["35%", 0.35]];
  const revOpts = [["0%", 0], ["5%", 0.05], ["15%", 0.15], ["30%", 0.30]];

  return React.createElement(
    "section",
    { className: "section price-build", id: "pricing", "data-screen-label": "Price the Build" },
    React.createElement("div", { className: "section-head" },
      React.createElement("span", { className: "kicker" }, "Price the build"),
      React.createElement("h2", { className: "section-title" }, "Price the build"),
      React.createElement("p", { className: "section-lede" }, "Fixed tiers, scaled by complexity. No hourly mystery — pick the deliverable, size the engagement.")
    ),

    /* complexity selector */
    React.createElement("div", { className: "complexity" },
      React.createElement("div", { className: "complexity-pills" },
        PRICING.complexity.map((c) =>
          React.createElement("button", {
            key: c.id, type: "button",
            className: `cx-pill ${complexityId === c.id ? "on" : ""}`,
            onClick: () => setComplexityId(c.id),
          },
            React.createElement("span", { className: "cx-label" }, c.label),
            React.createElement("span", { className: "cx-range mono" }, c.range)
          )
        )
      ),
      React.createElement("p", { className: "complexity-note" }, "Price scales with complexity, not with hours. Difficulty and lines-of-code adjust the tier; the deliverable doesn't.")
    ),

    /* tier cards */
    React.createElement("div", { className: "tier-grid" },
      PRICING.tiers.map((t) =>
        React.createElement("div", {
          key: t.id,
          className: `tier-card ${tierId === t.id ? "tier-sel" : ""} ${wiggle && tierId === t.id ? "tier-wiggle" : ""}`,
        },
          React.createElement("div", { className: "tier-head" },
            React.createElement("span", { className: "tier-tag mono" }, "T" + t.n),
            React.createElement("span", { className: "tier-name" }, t.name)
          ),
          React.createElement(TierPrice, { value: tierPrice(t.id, complexityId) }),
          React.createElement("ul", { className: "tier-includes" },
            t.includes.map((inc) =>
              React.createElement("li", { key: inc }, React.createElement("span", { className: "tier-check" }, "✓"), inc)
            )
          ),
          React.createElement("button", {
            type: "button",
            className: `btn ${tierId === t.id ? "btn-primary" : "btn-ghost"} tier-choose`,
            onClick: () => setTierId(t.id),
          }, tierId === t.id ? "Selected" : "Choose this tier →")
        )
      )
    ),

    /* backend-only alt track */
    React.createElement("div", { className: "backend-chip" },
      React.createElement("span", { className: "be-dot" }),
      "Backend only · from ", React.createElement("span", { className: "be-price" }, window.fmtMoney(PRICING.backendOnly.price)),
      React.createElement("span", { className: "be-note mono" }, "same complexity multiplier applies")
    ),

    /* ROI calculator */
    React.createElement("div", { className: "roi" },
      React.createElement("div", { className: "roi-head" },
        React.createElement("span", { className: "panel-title" }, "What it earns you"),
        React.createElement("span", { className: "panel-year mono" }, "live")
      ),
      React.createElement("div", { className: "roi-inputs" },
        roiInputRow("Your annual turnover", turnoverOpts, roi.turnover, (v) => setRoi({ ...roi, turnover: v })),
        roiInputRow("Efficiency gain you expect", effOpts, roi.efficiency, (v) => setRoi({ ...roi, efficiency: v })),
        roiInputRow("Revenue lift you expect", revOpts, roi.revenue, (v) => setRoi({ ...roi, revenue: v }))
      ),
      React.createElement("div", { className: "roi-out" },
        roiStat("ANNUAL BENEFIT", window.fmtMoney(tBenefit)),
        roiStat("PAYBACK", Math.round(tPayback) + " mo"),
        roiStat("3-YEAR ROI", tRoi.toFixed(1) + "×", true)
      ),
      React.createElement("p", { className: "roi-subline" },
        roiSubline(model.roi3yr, model.paybackMonths),
        wiggle && React.createElement("span", { className: "roi-quip" }, " Yeah, that's the one.")
      )
    )
  );
}

function roiInputRow(label, opts, value, onChange) {
  return React.createElement("div", { className: "sim-input-row", key: label },
    React.createElement("span", { className: "sim-input-label" }, label),
    React.createElement("div", { className: "seg" },
      opts.map(([lbl, val]) =>
        React.createElement("button", {
          key: lbl, type: "button",
          className: `seg-btn ${value === val ? "on" : ""}`,
          onClick: () => onChange(val),
        }, lbl)
      )
    )
  );
}
function roiStat(label, value, accent) {
  return React.createElement("div", { className: `roi-stat ${accent ? "accent" : ""}` },
    React.createElement("div", { className: "roi-stat-label mono" }, label),
    React.createElement("div", { className: "roi-stat-value" }, value)
  );
}

/* ---- Three-path CTA — redesigned: a recommended featured path + two alternatives ---- */
function ThreePathCTA({ tierId, complexityId, lab, onRediagnose, soften }) {
  const { tierById, tierPrice, complexityById, PRICING } = window.TALYA_PRICING;
  const tier = tierById(tierId);
  const cx = complexityById(complexityId);
  const price = tierPrice(tierId, complexityId);
  const t1 = PRICING.tiers[0].price;

  const featureChips = ["Live in 8 weeks", "Your brand, your IP", cx.label + " complexity"];

  const alts = [
    {
      key: "venture", n: "02", title: "Build It With Me", sub: "Venture studio",
      desc: "We co-found and co-operate the venture with you — shared build, shared upside.",
      price: "Custom venture terms",
      cta: "Pitch a venture →", accentVar: "#F59E0B",
    },
    {
      key: "license", n: "03", title: "License The Engine", sub: "SaaS factory",
      desc: "Run our orchestrator inside your own stack and ship verticals yourself.",
      price: "From " + window.fmtMoney(t1) + " / mo",
      cta: "Run it under my brand →", accentVar: "#4A76F6",
    },
  ];

  return React.createElement("section", { className: "section three-path", id: "architect", "data-screen-label": "Three-path CTA" },
    React.createElement("div", { className: "section-head center" },
      React.createElement("span", { className: "kicker" }, "Three ways in"),
      React.createElement("h2", { className: "section-title" }, soften ? "You're not late. Let's build the next version of your company." : "Pick how you want to build."),
      React.createElement("p", { className: "section-lede" }, "200+ production builds. 2 years. 12 industry verticals. First platform live in 8 weeks.")
    ),

    React.createElement("div", { className: "decision" },

      /* ---- featured / recommended path ---- */
      React.createElement("div", { className: "path-feature" },
        React.createElement("div", { className: "path-feature-head" },
          React.createElement("span", { className: "path-index mono" }, "01"),
          React.createElement("span", { className: "path-flag mono" }, "Recommended for you")
        ),
        React.createElement("div", { className: "path-feature-grid" },
          React.createElement("div", { className: "path-feature-copy" },
            React.createElement("span", { className: "path-sub mono" }, "Private-label platform"),
            React.createElement("h3", { className: "path-title feature" }, "Build It For Me"),
            React.createElement("p", { className: "path-desc" }, "First platform live under your brand in eight weeks. We architect, build, and hand you the keys — no excuses."),
            React.createElement("div", { className: "path-feature-meta" },
              featureChips.map((c) =>
                React.createElement("span", { className: "path-chip", key: c },
                  React.createElement("span", { className: "pc-dot" }), c)
              )
            )
          ),
          React.createElement("div", { className: "path-feature-action" },
            React.createElement("div", { className: "recap" },
              React.createElement("span", { className: "recap-label mono" }, "Your configured build"),
              React.createElement("div", { className: "recap-price" }, window.fmtMoney(price)),
              React.createElement("div", { className: "recap-sub mono" }, "T" + tier.n + " · " + tier.name)
            ),
            React.createElement("button", { type: "button", className: "btn path-cta feature" }, "Build my platform →")
          )
        )
      ),

      /* ---- alternative paths ---- */
      React.createElement("div", { className: "path-alt-head" },
        React.createElement("span", { className: "path-alt-label mono" }, "Or come in another way"),
        React.createElement("span", { className: "path-alt-rule" })
      ),
      React.createElement("div", { className: "path-alt-grid" },
        alts.map((p) =>
          React.createElement("div", { key: p.key, className: "path-card alt", style: { "--path": p.accentVar } },
            React.createElement("div", { className: "path-card-top" },
              React.createElement("span", { className: "path-index mono" }, p.n),
              React.createElement("span", { className: "path-sub mono" }, p.sub)
            ),
            React.createElement("h3", { className: "path-title" }, p.title),
            React.createElement("p", { className: "path-desc" }, p.desc),
            React.createElement("div", { className: "path-price" }, p.price),
            React.createElement("button", { type: "button", className: "btn path-cta ghost" }, p.cta)
          )
        )
      )
    ),

    React.createElement("div", { className: "human-row" },
      React.createElement("button", { type: "button", className: "human-btn", onClick: onRediagnose }, "Fine, show me the human →")
    )
  );
}

Object.assign(window, { PriceTheBuild, ThreePathCTA });
