/* =========================================================
   Pricing — shared parts
   Hooks (reveal, tween), buttons, nav, and the signature
   interactive net-effective-rate calculator.
   Pricing model (from brief):
     base = $2,495 / agent / month
     bundle: 2+ agents => 20% off (auto)
     commitment: m2m 0 / 3mo 5 / 6mo 10 / 12mo 15 / 12mo upfront 20
     discounts are ADDITIVE off the SAME base (never compound)
     net = base * (1 - (bundlePct + commitmentPct)/100)
   ========================================================= */
const { useState, useEffect, useRef } = React;

const BASE_PRICE = 2495;
const DEMO = "https://calendly.com/charles-cardealer/30min";

const COMMIT_OPTIONS = [
  { id: "m2m",      label: "Month-to-month", short: "M2M",        pct: 0 },
  { id: "3mo",      label: "3 months",       short: "3 mo",       pct: 5 },
  { id: "6mo",      label: "6 months",       short: "6 mo",       pct: 10 },
  { id: "12mo",     label: "12 months",      short: "12 mo",      pct: 15 },
  { id: "12up",     label: "12 mo, upfront", short: "12 mo · upfront", pct: 20 },
];

const prefersReducedMotion =
  typeof window !== "undefined" &&
  window.matchMedia &&
  window.matchMedia("(prefers-reduced-motion: reduce)").matches;

const fmt = (n) => "$" + Math.round(n).toLocaleString("en-US");

/* ---------- Reveal ---------- */
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el || prefersReducedMotion) return;
    let revealed = false;
    const show = () => {
      if (revealed) return;
      revealed = true;
      el.style.transition = "opacity 600ms cubic-bezier(0.2,0,0,1), transform 600ms cubic-bezier(0.2,0,0,1)";
      el.style.opacity = "1"; el.style.transform = "translateY(0)";
    };
    el.style.opacity = "0"; el.style.transform = "translateY(16px)";
    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight && r.bottom > 0) requestAnimationFrame(() => requestAnimationFrame(show));
    const io = new IntersectionObserver((es) => es.forEach((e) => { if (e.isIntersecting) { show(); io.disconnect(); } }), { threshold: 0.15 });
    io.observe(el);
    const t = setTimeout(show, 1200);
    return () => { io.disconnect(); clearTimeout(t); };
  }, []);
  return ref;
}

/* ---------- Tween a number toward `value` whenever it changes ---------- */
function useTween(value, duration = 480) {
  const [display, setDisplay] = useState(value);
  const from = useRef(value);
  const raf = useRef(0);
  useEffect(() => {
    if (prefersReducedMotion) { setDisplay(value); from.current = value; return; }
    const start = from.current;
    const delta = value - start;
    if (delta === 0) return;
    const t0 = performance.now();
    cancelAnimationFrame(raf.current);
    const tick = (now) => {
      const p = Math.min(1, (now - t0) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      const cur = start + delta * eased;
      setDisplay(cur);
      if (p < 1) raf.current = requestAnimationFrame(tick);
      else { setDisplay(value); from.current = value; }
    };
    raf.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf.current);
  }, [value, duration]);
  useEffect(() => { from.current = display; });
  return display;
}

/* ---------- Button ---------- */
function PriceBtn({ children, variant = "primary", href, onClick, icon, pulse }) {
  const base = {
    display: "inline-flex", alignItems: "center", gap: 10,
    padding: "16px 26px", borderRadius: 14, cursor: "pointer",
    fontFamily: "var(--font-body)", fontSize: 16, fontWeight: 700, letterSpacing: "-0.01em",
    border: "1.5px solid transparent", whiteSpace: "nowrap", position: "relative",
    transition: "transform 140ms ease, background 140ms ease, border-color 140ms ease",
  };
  const variants = {
    primary:   { background: "var(--cobalt-500)", color: "#fff" },
    secondary: { background: "transparent", color: "var(--ink)", borderColor: "var(--line)" },
    dark:      { background: "#fff", color: "var(--ink)" },
    "dark-ghost": { background: "rgba(255,255,255,0.06)", color: "#fff", borderColor: "rgba(255,255,255,0.22)" },
  };
  const hoverBg = { primary: "var(--cobalt-600)", secondary: "var(--bg-alt)", dark: "#EEF0F3", "dark-ghost": "rgba(255,255,255,0.12)" };
  const [hover, setHover] = useState(false);
  const style = { ...base, ...variants[variant], ...(hover ? { transform: "translateY(-1px)", background: hoverBg[variant] } : {}) };
  const inner = (
    <React.Fragment>
      {pulse && !prefersReducedMotion ? (
        <span aria-hidden style={{ position: "absolute", inset: -2, borderRadius: 16, border: "2px solid var(--cobalt-400)", opacity: 0.55, animation: "pvPulse 2.2s ease-out infinite", pointerEvents: "none" }}></span>
      ) : null}
      {icon === "arrow" ? (
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
      ) : null}
      {children}
    </React.Fragment>
  );
  const handlers = { onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false) };
  if (href) return <a href={href} target="_blank" rel="noopener" style={style} {...handlers}>{inner}</a>;
  return <button onClick={onClick} style={style} {...handlers}>{inner}</button>;
}

/* ---------- Nav ---------- */
function PricingNav() {
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50,
      background: "rgba(255,255,255,0.82)", backdropFilter: "saturate(180%) blur(12px)",
      WebkitBackdropFilter: "saturate(180%) blur(12px)", borderBottom: "1px solid var(--line)",
    }}>
      <div className="page" style={{ display: "flex", alignItems: "center", height: 68, gap: 20 }}>
        <a href="Home.html" style={{ display: "flex", alignItems: "center" }}>
          <img src="logo-exports/horizontal/horizontal-full-color.png" alt="CarDealer.ai" style={{ height: 26 }} />
        </a>
        <div style={{ flex: 1 }}></div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <a href="AI Employees Overview.html" style={{ fontSize: 14.5, fontWeight: 600, color: "var(--ink)", padding: "8px 12px" }}>The Agents</a>
          <PriceBtn variant="primary" href={DEMO} icon="arrow">Book a Demo</PriceBtn>
        </div>
      </div>
    </header>
  );
}

/* ---------- Segmented control ---------- */
function Segmented({ options, value, onChange, ariaLabel }) {
  return (
    <div role="radiogroup" aria-label={ariaLabel} style={{
      display: "inline-flex", flexWrap: "wrap", gap: 6, padding: 6,
      background: "var(--bg-alt)", borderRadius: 14, border: "1px solid var(--line)",
    }}>
      {options.map((o) => {
        const active = o.value === value;
        return (
          <button
            key={o.value} role="radio" aria-checked={active}
            onClick={() => onChange(o.value)}
            style={{
              display: "inline-flex", alignItems: "center", gap: 8,
              padding: "11px 16px", borderRadius: 10, cursor: "pointer",
              border: "1px solid " + (active ? "var(--cobalt-500)" : "transparent"),
              background: active ? "var(--bg)" : "transparent",
              color: active ? "var(--ink)" : "var(--body)",
              fontFamily: "var(--font-body)", fontSize: 14.5, fontWeight: 700, letterSpacing: "-0.01em",
              boxShadow: active ? "var(--e-2)" : "none",
              transition: "background 140ms ease, color 140ms ease, border-color 140ms ease",
            }}>
            {o.label}
            {o.note ? (
              <span style={{
                fontSize: 11, fontWeight: 700, padding: "2px 7px", borderRadius: 999,
                background: active ? "var(--cobalt-50)" : "var(--line-soft)",
                color: active ? "var(--cobalt-700)" : "var(--body-dim)",
              }}>{o.note}</span>
            ) : null}
          </button>
        );
      })}
    </div>
  );
}

/* ---------- THE signature calculator ---------- */
function PricingCalculator() {
  const [agents, setAgents] = useState(2);     // default to the common 2-agent bundle
  const [commit, setCommit] = useState("12mo"); // a sensible mid commitment

  const bundlePct = agents >= 2 ? 20 : 0;
  const commitPct = COMMIT_OPTIONS.find((c) => c.id === commit).pct;
  const totalPct = bundlePct + commitPct;

  const bundleAmt = BASE_PRICE * (bundlePct / 100);
  const commitAmt = BASE_PRICE * (commitPct / 100);
  const perAgentNet = BASE_PRICE * (1 - totalPct / 100);
  const monthlyTotal = perAgentNet * agents;

  const dNet = useTween(perAgentNet);
  const dTotal = useTween(monthlyTotal);
  const dBundle = useTween(bundleAmt);
  const dCommit = useTween(commitAmt);

  const agentOpts = [1, 2, 3, 4, 5, 6].map((n) => ({
    value: n, label: String(n), note: n === 2 ? "bundle" : undefined,
  }));
  const commitOpts = COMMIT_OPTIONS.map((c) => ({ value: c.id, label: c.short, note: c.pct ? `${c.pct}%` : undefined }));

  const Row = ({ label, sub, amount, tone }) => (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, padding: "14px 0", borderBottom: "1px solid rgba(255,255,255,0.10)" }}>
      <div>
        <div style={{ fontSize: 15, fontWeight: 600, color: "rgba(255,255,255,0.92)" }}>{label}</div>
        {sub ? <div style={{ fontSize: 12.5, color: "rgba(255,255,255,0.5)", marginTop: 2 }}>{sub}</div> : null}
      </div>
      <div className="tnum" style={{
        fontSize: 18, fontWeight: 800, letterSpacing: "-0.02em", whiteSpace: "nowrap",
        color: tone === "minus" ? "var(--cobalt-300)" : "#fff",
      }}>{amount}</div>
    </div>
  );

  return (
    <div style={{
      display: "grid", gridTemplateColumns: "1fr 1fr", gap: 0,
      borderRadius: 28, overflow: "hidden", border: "1px solid var(--line)", boxShadow: "var(--e-4)",
      background: "var(--bg)",
    }}>
      {/* Controls */}
      <div style={{ padding: "40px 40px 44px" }}>
        <div style={{ marginBottom: 32 }}>
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 14, gap: 12 }}>
            <span style={{ fontSize: 13, fontWeight: 700, letterSpacing: "0.10em", textTransform: "uppercase", color: "var(--body-dim)" }}>How many agents?</span>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: bundlePct ? "var(--cobalt-600)" : "var(--body-dim)" }}>
              {bundlePct ? "20% bundle applied" : "Add a 2nd for 20% off"}
            </span>
          </div>
          <Segmented options={agentOpts} value={agents} onChange={setAgents} ariaLabel="Number of agents" />
        </div>

        <div>
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 14, gap: 12 }}>
            <span style={{ fontSize: 13, fontWeight: 700, letterSpacing: "0.10em", textTransform: "uppercase", color: "var(--body-dim)" }}>Commitment</span>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: commitPct ? "var(--cobalt-600)" : "var(--body-dim)" }}>
              {commitPct ? `${commitPct}% commitment off` : "Longer term, bigger savings"}
            </span>
          </div>
          <Segmented options={commitOpts} value={commit} onChange={setCommit} ariaLabel="Commitment term" />
        </div>

        <div style={{ marginTop: 36, display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
          <PriceBtn variant="primary" href={DEMO} icon="arrow">Book a Demo</PriceBtn>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 13.5, color: "var(--body)", fontWeight: 600 }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--positive)" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5L20 7"/></svg>
            No setup fee
          </div>
        </div>
      </div>

      {/* Breakdown — ink panel */}
      <div style={{ background: "var(--ink)", color: "#fff", padding: "40px 40px 44px", position: "relative", overflow: "hidden" }}>
        <div aria-hidden style={{ position: "absolute", inset: 0, background: "radial-gradient(circle at 80% 0%, rgba(31,93,255,0.22), transparent 55%)", pointerEvents: "none" }}></div>
        <div style={{ position: "relative" }}>
          <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: "0.10em", textTransform: "uppercase", color: "var(--cobalt-300)", marginBottom: 6 }}>Your net effective rate</div>

          <Row label="Base price" sub="Per agent / month" amount={<span className="tnum">{fmt(BASE_PRICE)}</span>} />
          <Row label="Bundle discount" sub={bundlePct ? `${bundlePct}% · 2+ agents` : "Add a 2nd agent"} amount={bundlePct ? "– " + fmt(dBundle) : "—"} tone={bundlePct ? "minus" : ""} />
          <Row label="Commitment discount" sub={commitPct ? `${commitPct}% · ${COMMIT_OPTIONS.find(c=>c.id===commit).label}` : "Month-to-month"} amount={commitPct ? "– " + fmt(dCommit) : "—"} tone={commitPct ? "minus" : ""} />

          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, marginTop: 22 }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: "rgba(255,255,255,0.66)" }}>Net effective rate</div>
              <div style={{ fontSize: 12.5, color: "rgba(255,255,255,0.45)", marginTop: 3 }}>per agent / month{totalPct ? ` · ${totalPct}% off` : ""}</div>
            </div>
            <div className="tnum" style={{ fontSize: "clamp(40px, 5vw, 56px)", fontWeight: 900, letterSpacing: "-0.04em", color: "#fff", lineHeight: 0.9 }}>
              {fmt(dNet)}
            </div>
          </div>

          {agents >= 2 ? (
            <div style={{
              marginTop: 22, padding: "16px 18px", borderRadius: 14,
              background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.12)",
              display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
            }}>
              <span style={{ fontSize: 14, fontWeight: 600, color: "rgba(255,255,255,0.82)" }}>
                {agents} agents <span style={{ color: "rgba(255,255,255,0.5)" }}>× {fmt(perAgentNet)}</span>
              </span>
              <span className="tnum" style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.02em" }}>{fmt(dTotal)}<span style={{ fontSize: 13, fontWeight: 600, color: "rgba(255,255,255,0.5)" }}> /mo</span></span>
            </div>
          ) : null}

          <div style={{ marginTop: 18, fontSize: 12, color: "rgba(255,255,255,0.5)", lineHeight: 1.5 }}>
            Both discounts come off the same {fmt(BASE_PRICE)} base — they never compound. The full price stays visible on purpose.
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- FAQ accordion ---------- */
function FAQItem({ q, a, open, onToggle }) {
  const bodyRef = useRef(null);
  return (
    <div style={{ borderTop: "1px solid var(--line)" }}>
      <button
        onClick={onToggle} aria-expanded={open}
        style={{
          width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20,
          padding: "24px 0", background: "none", border: "none", cursor: "pointer", textAlign: "left",
          fontFamily: "var(--font-body)", fontSize: 19, fontWeight: 700, color: "var(--ink)", letterSpacing: "-0.015em",
        }}>
        {q}
        <span style={{
          width: 30, height: 30, flexShrink: 0, borderRadius: 999, background: open ? "var(--cobalt-500)" : "var(--bg-alt)",
          color: open ? "#fff" : "var(--ink)", display: "inline-flex", alignItems: "center", justifyContent: "center",
          transition: "background 160ms ease",
        }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? "rotate(45deg)" : "none", transition: "transform 200ms ease" }}><path d="M12 5v14M5 12h14"/></svg>
        </span>
      </button>
      <div style={{
        maxHeight: open ? (bodyRef.current ? bodyRef.current.scrollHeight + 4 : 300) : 0,
        overflow: "hidden", transition: "max-height 280ms cubic-bezier(0.2,0,0,1)",
      }}>
        <div ref={bodyRef} style={{ paddingBottom: 24, fontSize: 16.5, lineHeight: 1.6, color: "var(--body)", maxWidth: 760 }}>{a}</div>
      </div>
    </div>
  );
}

Object.assign(window, {
  BASE_PRICE, DEMO, COMMIT_OPTIONS, fmt, prefersReducedMotion,
  useReveal, useTween, PriceBtn, PricingNav, Segmented, PricingCalculator, FAQItem,
});
