/* global React, ReactDOM */
const { useState, useMemo, useEffect, useCallback } = React;

// Safe fallbacks — if tweaks-panel.jsx fails to load (e.g. missing from
// the production deploy), expose no-op shims so the app still renders.
// In production, the Tweaks panel is just an in-page editor anyway, not
// part of the user-facing experience.
if (typeof window.useTweaks !== "function") {
  window.useTweaks    = (defaults) => [defaults, () => {}];
  window.TweaksPanel  = () => null;
  window.TweakSection = () => null;
  window.TweakNumber  = () => null;
}

/* ====================================================================
   DATA — pricing, tiers, variant definitions

   All pricing lives in the TWEAK_DEFAULTS block below. You can also edit
   prices live from the in-app Tweaks panel — changes there persist back
   into this block automatically.
   ==================================================================== */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "unit_national": 10200,
  "unit_poc": 1200,
  "unit_newsletter": 800,
  "unit_cirrus": 1800,
  "tier_legacy_base": 58400,
  "tier_growth_base": 38000,
  "tier_partner_a": 10200,
  "tier_partner_b": 7200,
  "tier_partner_c": 3200
}/*EDITMODE-END*/;

// Newsletter sponsorships are sold as a bundle: 1 advertisement + 1 polling
// question, sold together. Minimum 4 per vendor whenever included.
const NEWSLETTER_MIN = 4;

const UNIT = {
  national:   TWEAK_DEFAULTS.unit_national,
  poc:        TWEAK_DEFAULTS.unit_poc,
  newsletter: TWEAK_DEFAULTS.unit_newsletter,
  cirrus:     TWEAK_DEFAULTS.unit_cirrus,
};

const ITEM_META = {
  national: {
    name: "National webinar",
    desc: "Full hour, 15,000-contact mailing list, ~951 registrants & ~516 attendees.",
    unitLabel: (n) => n === 1 ? "national webinar" : "national webinars",
  },
  poc: {
    name: "POC group webinar",
    desc: "Two-hour conference-style session with a nation-wide point-of-care group.",
    unitLabel: (n) => n === 1 ? "POC group webinar" : "POC group webinars",
  },
  newsletter: {
    name: "Newsletter sponsorship",
    desc: "Bundled advertisement + polling question in Whitehat Point of Care Insights — paired so you reach readers and collect first-party insight in the same drop. Sold in minimums of 4.",
    unitLabel: (n) => n === 1 ? "newsletter sponsorship (ad + poll)" : "newsletter sponsorships (ad + poll)",
  },
};

const TIERS = {
  legacy: {
    id: "legacy",
    rank: "Tier 01",
    name: "Whitehat Legacy",
    tagline: "Your strongest marketing vehicle. A steady pipeline of leads, and market category leadership.",
    short: "High-powered market reach, voice leadership among your buyers, customized large language model follow-up strategies.",
    rail: "var(--navy-500)",
    pillFill: "#14508C",
    price: TWEAK_DEFAULTS.tier_legacy_base,
    cirrusIncluded: true,
    discount: "7% bundle discount applied",
    discountPct: 0.07,
    base: { national: 4, poc: 12, newsletter: 4 },
    minimums: { national: 4, poc: 12, newsletter: 4 },
    summary: [
      { n: 4, t: "national webinars", note: "or more" },
      { n: 12, t: "POC group webinars", note: "or more" },
      { n: 4, t: "newsletter sponsorships", note: "or more — ad + poll in each drop" },
      { n: 1, t: "Whitehat Cirrus", note: "included", badge: true },
    ],
  },
  growth: {
    id: "growth",
    rank: "Tier 02",
    name: "Whitehat Growth",
    tagline: "Bring your voice to the market. Growth offers high-value exposure to the buyers of your products.",
    short: "Reliable presence with room to focus your spend.",
    rail: "var(--sky-500)",
    pillFill: "#1AB5DC",
    price: TWEAK_DEFAULTS.tier_growth_base,
    cirrusIncluded: false,
    discount: "5% bundle discount applied",
    discountPct: 0.05,
    base: { national: 2, poc: 12, newsletter: 4 },
    minimums: { national: 2, poc: 12, newsletter: 4 },
    summary: [
      { n: 2, t: "national webinars", note: "or more" },
      { n: 12, t: "POC group webinars", note: "or more" },
      { n: 4, t: "newsletter sponsorships", note: "or more — ad + poll in each drop" },
    ],
  },
  partner: {
    id: "partner",
    rank: "Tier 03",
    name: "Whitehat Partner",
    tagline: "Smaller reach. A few targeted leads. The right hello.",
    short: "Focused, single-channel partnerships to start a relationship.",
    rail: "var(--sky-300)",
    pillFill: "#78D4EB",
    get priceLabel() { return `Starting from $${Math.min(TWEAK_DEFAULTS.tier_partner_a, TWEAK_DEFAULTS.tier_partner_b, TWEAK_DEFAULTS.tier_partner_c).toLocaleString()}`; },
    cirrusIncluded: false,
    variants: [
      {
        id: "a",
        title: "Single national webinar",
        items: "1 national webinar — full mailing list, ~516 attendees.",
        base: { national: 1, poc: 0, newsletter: 0 },
        minimums: { national: 1, poc: 0, newsletter: 0 },
        priceOverride: TWEAK_DEFAULTS.tier_partner_a,
      },
      {
        id: "b",
        title: "POC community presence",
        items: "6 POC group webinars — community goodwill at scale.",
        base: { national: 0, poc: 6, newsletter: 0 },
        minimums: { national: 0, poc: 6, newsletter: 0 },
        priceOverride: TWEAK_DEFAULTS.tier_partner_b,
      },
      {
        id: "c",
        title: "Newsletter starter",
        items: "4 newsletter sponsorships — each pairs an ad with a polling question in Point of Care Insights.",
        base: { national: 0, poc: 0, newsletter: 4 },
        minimums: { national: 0, poc: 0, newsletter: 4 },
        priceOverride: TWEAK_DEFAULTS.tier_partner_c,
      },
    ],
    summary: [
      { n: 1, t: "channel of your choice", note: "national, POC, or newsletter" },
    ],
  },
};

/* ====================================================================
   ICONS — Lucide-style inline SVGs (only what we need)
   ==================================================================== */

const Icon = ({ name, size = 18, strokeWidth = 1.75, style }) => {
  const paths = {
    "arrow-right": <><line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" /></>,
    "arrow-left":  <><line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" /></>,
    plus:    <><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></>,
    minus:   <line x1="5" y1="12" x2="19" y2="12" />,
    x:       <><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></>,
    check:   <polyline points="20 6 9 17 4 12" />,
    sparkles:<path d="M12 2 L13.4 10.6 L22 12 L13.4 13.4 L12 22 L10.6 13.4 L2 12 L10.6 10.6 Z" fill="currentColor" stroke="none" />,
    cpu:     <><rect x="4" y="4" width="16" height="16" rx="2" /><rect x="9" y="9" width="6" height="6" /><line x1="9" y1="1" x2="9" y2="4" /><line x1="15" y1="1" x2="15" y2="4" /><line x1="9" y1="20" x2="9" y2="23" /><line x1="15" y1="20" x2="15" y2="23" /><line x1="20" y1="9" x2="23" y2="9" /><line x1="20" y1="14" x2="23" y2="14" /><line x1="1" y1="9" x2="4" y2="9" /><line x1="1" y1="14" x2="4" y2="14" /></>,
    brain:   <><path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 1.98-3A2.5 2.5 0 0 1 9.5 2Z" /><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-1.98-3A2.5 2.5 0 0 0 14.5 2Z" /></>,
    chart:   <><line x1="18" y1="20" x2="18" y2="10" /><line x1="12" y1="20" x2="12" y2="4" /><line x1="6" y1="20" x2="6" y2="14" /></>,
    target:  <><circle cx="12" cy="12" r="10" /><circle cx="12" cy="12" r="6" /><circle cx="12" cy="12" r="2" /></>,
    eye:     <><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z" /><circle cx="12" cy="12" r="3" /></>,
    layers:  <><polygon points="12 2 2 7 12 12 22 7 12 2" /><polyline points="2 17 12 22 22 17" /><polyline points="2 12 12 17 22 12" /></>,
    "message-square": <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />,
    pen:     <><path d="M12 20h9" /><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z" /></>,
    "broadcast": <><circle cx="12" cy="12" r="2" /><path d="M16.24 7.76a6 6 0 0 1 0 8.49M7.76 16.24a6 6 0 0 1 0-8.49M20.49 3.51a12 12 0 0 1 0 16.97M3.51 20.49a12 12 0 0 1 0-16.97" /></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
         stroke="currentColor" strokeWidth={strokeWidth}
         strokeLinecap="round" strokeLinejoin="round" style={style}>
      {paths[name]}
    </svg>
  );
};

/* ====================================================================
   ATOMS — Counter, Toggle, Button
   ==================================================================== */

function Counter({ value, onChange, min = 0, max = 99, minLabel }) {
  return (
    <div className="counter">
      <button type="button" className="counter__btn"
              onClick={() => onChange(Math.max(min, value - 1))}
              disabled={value <= min}
              aria-label="Decrease">
        <Icon name="minus" />
      </button>
      <span className="counter__value">{value}</span>
      <button type="button" className="counter__btn"
              onClick={() => onChange(Math.min(max, value + 1))}
              disabled={value >= max}
              aria-label="Increase">
        <Icon name="plus" />
      </button>
    </div>
  );
}

function Toggle({ on, onChange, disabled }) {
  return (
    <button type="button"
            className={`toggle${on ? " is-on" : ""}`}
            disabled={disabled}
            onClick={() => onChange(!on)}
            aria-pressed={on}
            aria-label="Toggle Whitehat Cirrus" />
  );
}

/* ====================================================================
   STAGE 1 — Tier selection
   ==================================================================== */

function StageSelect({ onPick }) {
  return (
    <div className="stage-enter">
      <div className="page__intro">
        <div className="page__eyebrow">Build your partnership</div>
        <h1 className="page__title">
          Three ways to partner in 2026.
        </h1>
        <p className="page__lede">
          Pick the level of presence that fits your year. We'll shape the details together — and you can adjust the mix on the next screen.
        </p>
      </div>

      <div className="tier-grid">
        {Object.values(TIERS).map((tier) => (
          <button key={tier.id} className="tier-card" onClick={() => onPick(tier.id)}
                  style={{ "--rail": tier.rail }}>
            <div className="tier-card__rail" />
            <div className="tier-card__halo" />
            <div className="tier-card__rank">{tier.rank}</div>
            <h2 className="tier-card__name">{tier.name}</h2>
            <p className="tier-card__tagline">{tier.tagline}</p>
            <div className="tier-card__divider" />
            <ul className="tier-card__incl">
              {tier.summary.map((s, i) => (
                <li key={i}>
                  <span className="num">{s.badge ? "+" : `${s.n}+`}</span>
                  <span>
                    {s.t}
                    {s.note && <span style={{ color: "var(--fg-3)", fontSize: 14, fontWeight: 400 }}> · {s.note}</span>}
                  </span>
                </li>
              ))}
            </ul>
            {tier.discount && (
              <p className="tier-card__discount">
                <span className="tier-card__discount-dot" aria-hidden="true" />
                {tier.discount}
              </p>
            )}
            <span className="tier-card__cta">
              Configure {tier.name.replace("Whitehat ", "")}
              <Icon name="arrow-right" />
            </span>
          </button>
        ))}
      </div>

      {/* Hera — coming soon */}
      <div className="hera-card" aria-disabled="true">
        <div className="hera-card__rail" />
        <div className="hera-card__body">
          <div className="hera-card__brand">
            <img
              src="assets/hera-logo.png"
              alt="Hera"
              className="hera-card__logo"
              onError={(e) => { if (!e.target.dataset.fb) { e.target.dataset.fb = "1"; e.target.src = "hera-logo.png"; } }}
            />
          </div>
          <div className="hera-card__copy">
            <div className="hera-card__rank">Whitehat Hera</div>
            <h3 className="hera-card__tagline">Consulting, <em>reimagined.</em></h3>
            <div className="hera-card__badge-row">
              <span className="hera-card__badge">Coming soon</span>
            </div>
            <p className="hera-card__desc">
              Whitehat's singular consultant service, capable of producing longitudinal, temporally extended reports across Whitehat's proprietary webinar database — patterns, drift, and signal that emerge only over years.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ====================================================================
   STAGE 2 — Variant pick (only for tiers with variants)
   ==================================================================== */

function StageVariant({ tier, onPick, onBack }) {
  return (
    <div className="stage-enter" style={{ maxWidth: 760 }}>
      <button className="back-link" onClick={onBack}>
        <Icon name="arrow-left" /> Choose a different tier
      </button>

      <div className="page__intro" style={{ marginBottom: 32 }}>
        <div className="page__eyebrow">{tier.name} · pick your path</div>
        <h1 className="page__title" style={{ fontSize: "clamp(32px, 4vw, 44px)" }}>
          {tier.id === "growth"
            ? <>Two ways to run a <em>Growth</em> year.</>
            : <>Where would you like to <em>start</em>?</>
          }
        </h1>
        <p className="page__lede" style={{ fontSize: 17 }}>
          {tier.id === "growth"
            ? "Both options land at the same price. Pick the one that matches how your audience prefers to hear from you."
            : "Pick the channel that matters most this year. You can layer on more in the next step."
          }
        </p>
      </div>

      <div className="variant-grid">
        {tier.variants.map((v, idx) => (
          <React.Fragment key={v.id}>
            {idx > 0 && <div className="or-divider">or</div>}
            <button className="variant-card" onClick={() => onPick(v.id)}>
              <div className="variant-card__letter">{String.fromCharCode(65 + idx)}</div>
              <div className="variant-card__body">
                <h3 className="variant-card__title">{v.title}</h3>
                <p className="variant-card__items">{v.items}</p>
              </div>
              <Icon name="arrow-right" style={{ color: "var(--fg-3)" }} />
            </button>
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

/* ====================================================================
   STAGE 3 — Configurator: counters + Cirrus toggle + live package card
   ==================================================================== */

function priceFor({ tier, variant, items, cirrus }) {
  // Start at the tier base, then add the cost of items above the minimums.
  let base;
  let mins;
  if (variant && variant.priceOverride != null) {
    base = variant.priceOverride;
    mins = variant.minimums;
  } else if (variant) {
    base = tier.price;
    mins = variant.minimums;
  } else {
    base = tier.price;
    mins = tier.minimums;
  }

  let extra = 0;
  Object.keys(UNIT).forEach((k) => {
    if (k === "cirrus") return;
    const baseN = mins[k] || 0;
    const have = items[k] || 0;
    const over = Math.max(0, have - baseN);
    extra += over * UNIT[k];
  });

  let cirrusCost = 0;
  if (cirrus && !tier.cirrusIncluded) cirrusCost = UNIT.cirrus;

  // Bundle discount (Legacy, Growth) — applies to base + extras, not Cirrus.
  const discountPct = tier.discountPct || 0;
  const discount = Math.round((base + extra) * discountPct);

  return {
    base, extra, cirrusCost,
    discountPct, discount,
    total: base + extra - discount + cirrusCost,
  };
}

function StageConfigure({ tier, variant, items, setItems, cirrus, setCirrus, onBack, onNext, onShowCirrus }) {
  const mins = variant ? variant.minimums : tier.minimums;
  const { base, extra, cirrusCost, discount, discountPct, total } = priceFor({ tier, variant, items, cirrus });

  const update = (key, n) => setItems({ ...items, [key]: n });

  const itemRows = [
    { key: "national",   label: "National webinars" },
    { key: "poc",        label: "POC group webinars" },
    { key: "newsletter", label: "Newsletter sponsorships" },
  ];

  // Lines shown on the package card (only items with qty > 0)
  const packageLines = itemRows
    .filter((r) => items[r.key] > 0)
    .map((r) => ({
      key: r.key,
      qty: items[r.key],
      name: ITEM_META[r.key].unitLabel(items[r.key]),
      price: items[r.key] > mins[r.key]
        ? `+ $${((items[r.key] - mins[r.key]) * UNIT[r.key]).toLocaleString()}`
        : "Included",
    }));

  return (
    <div className="stage-enter">
      <button className="back-link" onClick={onBack}>
        <Icon name="arrow-left" /> Back
      </button>

      <div className="page__intro" style={{ marginBottom: 32 }}>
        <div className="page__eyebrow">Step 2 · Customize</div>
        <h1 className="page__title" style={{ fontSize: "clamp(34px, 4.4vw, 48px)" }}>
          Shape your <em>{tier.name.replace("Whitehat ", "")}</em> package.
        </h1>
        <p className="page__lede" style={{ fontSize: 17 }}>
          Each tier comes with a baseline you can grow from. Add more of what matters; pricing updates as you go.
        </p>
      </div>

      <div className="configurator">
        {/* LEFT: live package card */}
        <div className="package-card">
          <div className="package-card__band">
            <div className="package-card__band-eyebrow">{tier.rank} · your build</div>
            <h2 className="package-card__band-name">{tier.name}</h2>
            <div className="package-card__band-sub">{tier.short}</div>
            <img src="assets/logo-mark.png" alt="" className="package-card__band-mark" />
          </div>

          <div className="package-card__body">
            {packageLines.length === 0 && (
              <p style={{ color: "var(--fg-3)", fontSize: 14, margin: "8px 0 0", fontStyle: "italic" }}>
                Add a few items on the right to start your build.
              </p>
            )}
            {packageLines.map((line) => (
              <div className="package-line" key={line.key}>
                <span className="package-line__qty">×{line.qty}</span>
                <div className="package-line__name">
                  {line.name}
                  {line.qty > mins[line.key] && mins[line.key] > 0 && (
                    <span className="package-line__note">{mins[line.key]} included, +{line.qty - mins[line.key]} added</span>
                  )}
                </div>
                <span className="package-line__price">{line.price}</span>
              </div>
            ))}

            {cirrus && (
              <div className="package-line package-line--cirrus">
                <span className="package-line__qty">+</span>
                <div className="package-line__name">
                  Whitehat Cirrus <span className="cirrus-badge">LLM</span>
                  <span className="package-line__note">
                    {tier.cirrusIncluded ? "Bundled with Legacy" : "Optional add-on"}
                  </span>
                </div>
                <span className="package-line__price">
                  {tier.cirrusIncluded ? "Included" : `+ $${UNIT.cirrus.toLocaleString()}`}
                </span>
              </div>
            )}
          </div>

          <div className="package-card__total">
            {discount > 0 && (
              <div className="package-line package-line--discount">
                <span className="package-line__qty">–</span>
                <div className="package-line__name">
                  Bundle discount
                  <span className="package-line__note">{Math.round(discountPct * 100)}% off bundle subtotal</span>
                </div>
                <span className="package-line__price">– ${discount.toLocaleString()}</span>
              </div>
            )}
            <div className="package-card__total-label">Total · annual</div>
            <div className="package-card__total-value">${total.toLocaleString()}</div>
          </div>

          <div className="package-card__cta">
            <button className="btn btn--primary btn--lg btn--block" onClick={onNext}
                    disabled={packageLines.length === 0}>
              Continue to quote
              <Icon name="arrow-right" />
            </button>
          </div>
        </div>

        {/* RIGHT: controls */}
        <div className="controls">
          <section className="control-section">
            <div className="control-section__head">
              <h3 className="control-section__title">Webinars</h3>
              <span className="control-section__hint">{tier.cirrusIncluded ? "3+ national, 6+ POC" : variant ? "minimums set by your path" : ""}</span>
            </div>

            <div className="item-row">
              <div className="item-row__body">
                <p className="item-row__name">National webinars</p>
                <p className="item-row__desc">{ITEM_META.national.desc}</p>
                <p className="item-row__price">${UNIT.national.toLocaleString()} per additional · {mins.national || 0} included</p>
              </div>
              <Counter value={items.national} min={mins.national} onChange={(n) => update("national", n)} />
            </div>

            <div className="item-row">
              <div className="item-row__body">
                <p className="item-row__name">POC group webinars</p>
                <p className="item-row__desc">{ITEM_META.poc.desc}</p>
                <p className="item-row__price">${UNIT.poc.toLocaleString()} per additional · {mins.poc || 0} included</p>
              </div>
              <Counter value={items.poc} min={mins.poc} onChange={(n) => update("poc", n)} />
            </div>
          </section>

          <section className="control-section">
            <div className="control-section__head">
              <h3 className="control-section__title">Newsletter — Point of Care Insights</h3>
            </div>

            <div className="item-row">
              <div className="item-row__body">
                <p className="item-row__name">Newsletter sponsorships</p>
                <p className="item-row__desc">{ITEM_META.newsletter.desc}</p>
                <p className="item-row__price">${UNIT.newsletter.toLocaleString()} per additional · {mins.newsletter || 0} included · sold in minimums of {NEWSLETTER_MIN}</p>
              </div>
              <Counter
                value={items.newsletter}
                min={mins.newsletter || 0}
                onChange={(n) => {
                  const tierMin = mins.newsletter || 0;
                  let next = n;
                  if (next > 0 && next < NEWSLETTER_MIN) {
                    // Below the bundle floor: snap up if growing into the bundle,
                    // or all the way to the tier minimum (0 for optional) if shrinking out.
                    next = next > items.newsletter ? NEWSLETTER_MIN : tierMin;
                  }
                  update("newsletter", next);
                }}
              />
            </div>
          </section>

          <section className="cirrus-card">
            <div className="cirrus-card__head">
              <div className="cirrus-card__icon">
                <Icon name="sparkles" size={22} />
              </div>
              <div className="cirrus-card__title-wrap">
                <h3 className="cirrus-card__title">
                  Whitehat Cirrus
                  <span className="cirrus-badge">LLM</span>
                </h3>
                <p className="cirrus-card__sub">Proprietary LLM inference over your registrant & survey data.</p>
              </div>
              <Toggle on={cirrus} onChange={setCirrus} disabled={tier.cirrusIncluded} />
            </div>
            <p className="cirrus-card__copy">
              Cirrus reads your registration and post-event survey responses and surfaces the marketing inferences a human analyst would take days to write — segments, intent signals, follow-up suggestions, all clinically literate. <button className="linklike" onClick={onShowCirrus}>Learn what it does →</button>
            </p>
            <div className="cirrus-card__foot">
              <span className={`cirrus-card__price${tier.cirrusIncluded ? " cirrus-card__price--included" : ""}`}>
                {tier.cirrusIncluded ? "✓ Included with Legacy" : `+ $${UNIT.cirrus.toLocaleString()} add-on`}
              </span>
            </div>
          </section>
        </div>
      </div>
    </div>
  );
}

/* ====================================================================
   Cirrus modal
   ==================================================================== */

const CIRRUS_CAPABILITIES = [
  { icon: "target",   t: "Audience inference",      d: "Generate narrative analysis, in the voice of a marketing manager, from your attendee demographics." },
  { icon: "chart",    t: "Registration & survey inference", d: "Receive advanced implications that follow from responses to your pre- and post-webinar questions. Singular, consultant-like analysis." },
  { icon: "message-square", t: "Open-response sense", d: "Read every open-ended survey answer the way a senior clinician would — pull themes, objections, requests." },
  { icon: "broadcast",t: "Next-touch suggestions",  d: "Get a recommended next-action for each attendee segment, written for medical marketers." },
];

function CirrusModal({ onClose, onAdd, included, isOn }) {
  // Close on Esc
  useEffect(() => {
    const h = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", h);
    return () => document.removeEventListener("keydown", h);
  }, [onClose]);

  return (
    <div className="scrim" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal__hero">
          <div className="modal__hero-content">
            <div className="modal__hero-eyebrow">
              <span className="cirrus-spark" aria-hidden="true">
                <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
                  <path d="M12 0 L13.6 10.4 L24 12 L13.6 13.6 L12 24 L10.4 13.6 L0 12 L10.4 10.4 Z" />
                </svg>
              </span>
              Whitehat Cirrus
            </div>
            <h2 className="modal__hero-title">What if your data had a voice?</h2>
            <p className="modal__hero-sub">
              Welcome to Whitehat Cirrus. Using some of the most advanced large language models available, Cirrus delivers narrative inferences — all based on your webinar registration, attendance, and survey data — to help you spot trends, build marketing strategies, and advise you on how to reach out to prospective leads.
            </p>
          </div>
          <button className="modal__close" onClick={onClose} aria-label="Close">
            <Icon name="x" />
          </button>
        </div>

        <div className="modal__body">
          <div className="modal__capabilities">
            {CIRRUS_CAPABILITIES.map((c) => (
              <div key={c.t} className="capability">
                <div className="capability__icon"><Icon name={c.icon} /></div>
                <h4 className="capability__title">{c.t}</h4>
                <p className="capability__desc">{c.d}</p>
              </div>
            ))}
          </div>

          <div className="modal__example">
            <div className="modal__example-label">What you'd actually see</div>
            <p className="modal__example-text">
              "37 of your registrants run high-complexity labs at IDN-affiliated hospitals, and 14 of them flagged 'budget cycle starting Q1' in the post-event survey — your fastest path to revenue this quarter starts here. Across the broader registration set, 'turnaround time' beat 'cost per test' as a top concern by a 3-to-1 margin, suggesting your next campaign should lead with speed, not price. Sample outreach copy, segmented by role and care setting, is attached."
            </p>
          </div>
        </div>

        <div className="modal__foot">
          <div className="modal__foot-price">
            {included
              ? <><strong>Included</strong> with Whitehat Legacy.</>
              : <><strong>${UNIT.cirrus.toLocaleString()}</strong> annual add-on.</>
            }
          </div>
          {included ? (
            <button className="btn btn--primary" onClick={onClose}>Got it</button>
          ) : (
            <button className={`btn ${isOn ? "btn--secondary" : "btn--primary"}`}
                    onClick={() => { onAdd(!isOn); onClose(); }}>
              {isOn ? "Remove from package" : "Add Cirrus to my package"}
              {!isOn && <Icon name="arrow-right" />}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

/* ====================================================================
   STAGE 4 — Summary / lead capture
   ==================================================================== */

function StageSummary({ tier, variant, items, cirrus, onBack, onSubmit, submitted }) {
  const { discount, discountPct, total } = priceFor({ tier, variant, items, cirrus });
  const [form, setForm] = useState({ name: "", email: "", company: "", role: "", notes: "" });
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  if (submitted) {
    return (
      <div className="stage-enter" style={{ maxWidth: 720, margin: "0 auto" }}>
        <div className="confirm">
          <div className="confirm__icon"><Icon name="check" size={28} strokeWidth={2.5} /></div>
          <h2 style={{ fontSize: 28, fontWeight: 700, margin: "0 0 8px", letterSpacing: "-0.02em" }}>
            We have it — thank you.
          </h2>
          <p style={{ fontSize: 16, color: "var(--fg-2)", margin: "0 0 24px", lineHeight: 1.55 }}>
            A Whitehat partnership lead will be in touch within one business day to confirm the details of your <strong>{tier.name}</strong> build and walk through next steps.
          </p>
          <button className="btn btn--secondary" onClick={() => window.location.reload()}>
            Build another package
          </button>
        </div>
      </div>
    );
  }

  const itemRows = [
    { key: "national",   label: "National webinars" },
    { key: "poc",        label: "POC group webinars" },
    { key: "newsletter", label: "Newsletter sponsorships" },
  ].filter((r) => items[r.key] > 0);

  return (
    <div className="stage-enter">
      <button className="back-link" onClick={onBack}>
        <Icon name="arrow-left" /> Keep customizing
      </button>

      <div className="page__intro" style={{ marginBottom: 32 }}>
        <div className="page__eyebrow">Step 3 · Confirm</div>
        <h1 className="page__title" style={{ fontSize: "clamp(34px, 4.4vw, 48px)" }}>
          Send this to a <em>Whitehat partner lead</em>.
        </h1>
        <p className="page__lede" style={{ fontSize: 17 }}>
          We'll review your build, confirm scheduling against the calendar, and respond within one business day with a formal quote.
        </p>
      </div>

      <div className="summary-grid">
        {/* Recap card */}
        <div className="package-card" style={{ position: "static" }}>
          <div className="package-card__band">
            <div className="package-card__band-eyebrow">{tier.rank} · your build</div>
            <h2 className="package-card__band-name">{tier.name}</h2>
            <div className="package-card__band-sub">{tier.short}</div>
            <img src="assets/logo-mark.png" alt="" className="package-card__band-mark" />
          </div>
          <div className="package-card__body">
            {itemRows.map((r) => (
              <div className="package-line" key={r.key}>
                <span className="package-line__qty">×{items[r.key]}</span>
                <div className="package-line__name">{ITEM_META[r.key].unitLabel(items[r.key])}</div>
              </div>
            ))}
            {cirrus && (
              <div className="package-line package-line--cirrus">
                <span className="package-line__qty">+</span>
                <div className="package-line__name">
                  Whitehat Cirrus <span className="cirrus-badge">LLM</span>
                </div>
                <span className="package-line__price">{tier.cirrusIncluded ? "Included" : `+ $${UNIT.cirrus.toLocaleString()}`}</span>
              </div>
            )}
          </div>
          <div className="package-card__total">
            {discount > 0 && (
              <div className="package-line package-line--discount">
                <span className="package-line__qty">–</span>
                <div className="package-line__name">
                  Bundle discount
                  <span className="package-line__note">{Math.round(discountPct * 100)}% off bundle subtotal</span>
                </div>
                <span className="package-line__price">– ${discount.toLocaleString()}</span>
              </div>
            )}
            <div className="package-card__total-label">Indicative total · annual</div>
            <div className="package-card__total-value">${total.toLocaleString()}</div>
          </div>
        </div>

        {/* Lead form */}
        <form className="lead-form" onSubmit={(e) => { e.preventDefault(); onSubmit(form); }}>
          <h3 className="lead-form__title">Your details</h3>
          <p className="lead-form__sub">All fields are required except notes.</p>

          <div className="field">
            <label htmlFor="name">Full name</label>
            <input id="name" className="input" required value={form.name} onChange={set("name")} />
          </div>
          <div className="field">
            <label htmlFor="email">Work email</label>
            <input id="email" type="email" className="input" required value={form.email} onChange={set("email")} />
          </div>
          <div className="field">
            <label htmlFor="company">Company</label>
            <input id="company" className="input" required value={form.company} onChange={set("company")} />
          </div>
          <div className="field">
            <label htmlFor="role">Role</label>
            <input id="role" className="input" required value={form.role} onChange={set("role")} />
          </div>
          <div className="field">
            <label htmlFor="notes">Anything we should know? <span style={{ color: "var(--fg-3)", fontWeight: 400 }}>(optional)</span></label>
            <textarea id="notes" rows={3} value={form.notes} onChange={set("notes")} />
          </div>

          <button type="submit" className="btn btn--primary btn--lg btn--block" style={{ marginTop: 8 }}>
            Send my build to Whitehat
            <Icon name="arrow-right" />
          </button>
          <p className="meta" style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 12, textAlign: "center" }}>
            Indicative pricing — final quote confirmed in writing.
          </p>
        </form>
      </div>
    </div>
  );
}

/* ====================================================================
   APP — orchestrates stages
   ==================================================================== */

function App() {
  // Live-editable prices (synced to UNIT/TIERS on every render so all pricing
  // throughout the app reflects the current tweaks)
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  UNIT.national   = tweaks.unit_national;
  UNIT.poc        = tweaks.unit_poc;
  UNIT.newsletter = tweaks.unit_newsletter;
  UNIT.cirrus     = tweaks.unit_cirrus;
  TIERS.legacy.price = tweaks.tier_legacy_base;
  TIERS.growth.price = tweaks.tier_growth_base;
  TIERS.partner.variants[0].priceOverride = tweaks.tier_partner_a;
  TIERS.partner.variants[1].priceOverride = tweaks.tier_partner_b;
  TIERS.partner.variants[2].priceOverride = tweaks.tier_partner_c;

  const [stage, setStage] = useState("select");      // select | variant | configure | summary
  const [tierId, setTierId] = useState(null);
  const [variantId, setVariantId] = useState(null);
  const [items, setItems] = useState({ national: 0, poc: 0, newsletter: 0 });
  const [cirrus, setCirrus] = useState(false);
  const [cirrusOpen, setCirrusOpen] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  const tier = tierId ? TIERS[tierId] : null;
  const variant = tier && tier.variants && variantId
    ? tier.variants.find((v) => v.id === variantId)
    : null;

  // Move on after picking tier
  const pickTier = useCallback((id) => {
    const t = TIERS[id];
    setTierId(id);
    if (t.variants) {
      setStage("variant");
      setVariantId(null);
    } else {
      // Legacy — straight to configure
      setItems({ ...t.base });
      setCirrus(!!t.cirrusIncluded);
      setStage("configure");
    }
  }, []);

  const pickVariant = useCallback((vid) => {
    const v = tier.variants.find((x) => x.id === vid);
    setVariantId(vid);
    setItems({ ...v.base });
    setCirrus(false);
    setStage("configure");
  }, [tier]);

  const stepIndex = stage === "select" ? 0
                  : stage === "variant" ? 0
                  : stage === "configure" ? 1
                  : 2;

  // Reset scroll on stage change — and tell the parent (Squarespace) about new height
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: "smooth" });
    // Slight delay so the new stage has laid out before we measure
    const t = setTimeout(() => {
      const h = Math.max(
        document.body.scrollHeight,
        document.documentElement.scrollHeight
      );
      try { window.parent.postMessage({ type: "whitehat:height", height: h }, "*"); } catch (e) {}
    }, 350);
    return () => clearTimeout(t);
  }, [stage, submitted]);

  // Keep parent in sync as content grows (e.g. counter changes, modal opens)
  useEffect(() => {
    if (typeof ResizeObserver === "undefined") return;
    const post = () => {
      const h = Math.max(
        document.body.scrollHeight,
        document.documentElement.scrollHeight
      );
      try { window.parent.postMessage({ type: "whitehat:height", height: h }, "*"); } catch (e) {}
    };
    const ro = new ResizeObserver(post);
    ro.observe(document.body);
    post();
    return () => ro.disconnect();
  }, []);

  return (
    <>
      <header className="topbar">
        <div className="topbar__inner">
          <div className="brand">
            <img src="assets/logo-mark.png" alt="Whitehat" />
            <span className="brand__name">Whitehat</span>
            <span className="brand__sep" />
            <span className="brand__product">Partnership Builder</span>
          </div>

          <div className="stepper" role="navigation" aria-label="Progress">
            {["Choose tier", "Customize", "Quote"].map((label, i) => (
              <React.Fragment key={label}>
                {i > 0 && <span className="step__line" />}
                <div className={`step${stepIndex === i ? " is-active" : stepIndex > i ? " is-done" : ""}`}>
                  <span className="step__num">{stepIndex > i ? <Icon name="check" size={12} strokeWidth={2.5} /> : i + 1}</span>
                  <span>{label}</span>
                </div>
              </React.Fragment>
            ))}
          </div>
        </div>
      </header>

      <main className="page">
        {stage === "select" && <StageSelect onPick={pickTier} />}
        {stage === "variant" && tier && (
          <StageVariant tier={tier} onPick={pickVariant} onBack={() => { setStage("select"); setTierId(null); }} />
        )}
        {stage === "configure" && tier && (
          <StageConfigure
            tier={tier}
            variant={variant}
            items={items}
            setItems={setItems}
            cirrus={cirrus}
            setCirrus={setCirrus}
            onBack={() => {
              if (tier.variants) setStage("variant");
              else { setStage("select"); setTierId(null); }
            }}
            onNext={() => setStage("summary")}
            onShowCirrus={() => setCirrusOpen(true)}
          />
        )}
        {stage === "summary" && tier && (
          <StageSummary
            tier={tier}
            variant={variant}
            items={items}
            cirrus={cirrus}
            onBack={() => setStage("configure")}
            onSubmit={() => setSubmitted(true)}
            submitted={submitted}
          />
        )}
      </main>

      {cirrusOpen && tier && (
        <CirrusModal
          onClose={() => setCirrusOpen(false)}
          onAdd={(on) => setCirrus(on)}
          included={tier.cirrusIncluded}
          isOn={cirrus}
        />
      )}

      <TweaksPanel title="Pricing">
        <TweakSection label="Per-additional unit prices" />
        <TweakNumber label="National webinar"      value={tweaks.unit_national}     min={0} step={500} unit="$" onChange={(v) => setTweak("unit_national", v)} />
        <TweakNumber label="POC group webinar"     value={tweaks.unit_poc}          min={0} step={500} unit="$" onChange={(v) => setTweak("unit_poc", v)} />
        <TweakNumber label="Newsletter sponsorship" value={tweaks.unit_newsletter}  min={0} step={500} unit="$" onChange={(v) => setTweak("unit_newsletter", v)} />
        <TweakNumber label="Cirrus LLM add-on"     value={tweaks.unit_cirrus}       min={0} step={500} unit="$" onChange={(v) => setTweak("unit_cirrus", v)} />

        <TweakSection label="Tier base prices" />
        <TweakNumber label="Legacy (annual)"       value={tweaks.tier_legacy_base}  min={0} step={500} unit="$" onChange={(v) => setTweak("tier_legacy_base", v)} />
        <TweakNumber label="Growth (annual)"       value={tweaks.tier_growth_base}  min={0} step={500} unit="$" onChange={(v) => setTweak("tier_growth_base", v)} />

        <TweakSection label="Partner — single-channel prices" />
        <TweakNumber label="Single national"       value={tweaks.tier_partner_a}    min={0} step={500} unit="$" onChange={(v) => setTweak("tier_partner_a", v)} />
        <TweakNumber label="POC community (6)"     value={tweaks.tier_partner_b}    min={0} step={500} unit="$" onChange={(v) => setTweak("tier_partner_b", v)} />
        <TweakNumber label="Newsletter starter"    value={tweaks.tier_partner_c}    min={0} step={500} unit="$" onChange={(v) => setTweak("tier_partner_c", v)} />
      </TweaksPanel>
    </>
  );
}

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