/* Earnings Calculator — dead simple.
 * Two sliders. One recurring number. No tiers, no events, no jargon.
 */

const VENUE_PICKER = [
  { slug: "hair-salons", label: "Hair Salon" },
  { slug: "yoga-studios", label: "Yoga / Pilates Studio" },
  { slug: "chiropractors", label: "Chiropractic Practice" },
  { slug: "gyms", label: "Gym / PT Studio" },
  { slug: "boutique-fitness", label: "Boutique Fitness Chain" },
];

function fmtMoney(n) {
  if (n >= 1000) return "$" + Math.round(n).toLocaleString();
  return "$" + Math.round(n);
}
function fmtBig(n) {
  return "$" + Math.round(n).toLocaleString();
}

window.PartnerCalculator = function PartnerCalculator({ slug: initialSlug, compact = false }) {
  const [slug, setSlug] = React.useState(initialSlug || "hair-salons");
  const data = window.PARTNER_DATA[slug];
  const accent = data ? data.accent : "#a3793a";
  const accentSoft = data ? data.accentSoft : "#f1e6d2";
  const defaults = data ? data.calc.defaults : null;

  const [clientCount, setClientCount] = React.useState(defaults ? defaults.clientCount : 600);
  const [conversionPct, setConversionPct] = React.useState(defaults ? defaults.memberConversionPct : 0.05);
  const [emailGated, setEmailGated] = React.useState(false);
  const [email, setEmail] = React.useState("");
  const [submitted, setSubmitted] = React.useState(false);

  React.useEffect(() => {
    if (defaults) {
      setClientCount(defaults.clientCount);
      setConversionPct(defaults.memberConversionPct);
    }
  }, [slug]);

  if (!defaults) return null;

  const patientsConverting = Math.round(clientCount * conversionPct);
  const monthlyRecurring = patientsConverting * defaults.feePerPatientPerMonth;
  const annualRecurring = monthlyRecurring * 12;

  function submitEmail(e) {
    e.preventDefault();
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return;
    setSubmitted(true);
    try {
      sessionStorage.setItem(
        "partner_calc_lead",
        JSON.stringify({ slug, clientCount, conversionPct, email, ts: Date.now() })
      );
    } catch (e) {}
  }

  return (
    <div className="partner-calc" style={{ borderColor: accent, "--calc-accent": accent, "--calc-accent-soft": accentSoft }}>
      <div className="partner-calc-eyebrow">★ EARNINGS CALCULATOR</div>
      <div className="partner-calc-headline">Run your numbers.</div>
      <div className="partner-calc-sub">Two questions. One recurring number.</div>

      {!initialSlug && (
        <div className="partner-calc-row">
          <label className="partner-calc-label">Your venue type</label>
          <div className="partner-calc-pills">
            {VENUE_PICKER.map((v) => (
              <button
                key={v.slug}
                onClick={() => setSlug(v.slug)}
                className={"partner-calc-pill" + (slug === v.slug ? " active" : "")}
              >
                {v.label}
              </button>
            ))}
          </div>
        </div>
      )}

      <div className="partner-calc-grid">
        <div className="partner-calc-input">
          <div className="partner-calc-label">
            How many {defaults.venueLabel.toLowerCase()} clients / members do you have?
          </div>
          <input
            type="range"
            min={50}
            max={2000}
            step={25}
            value={clientCount}
            onChange={(e) => setClientCount(Number(e.target.value))}
          />
          <div className="partner-calc-value">{clientCount.toLocaleString()}</div>
        </div>

        <div className="partner-calc-input">
          <div className="partner-calc-label">
            What % of them do you think will start taking peptides?
          </div>
          <input
            type="range"
            min={2}
            max={20}
            step={1}
            value={Math.round(conversionPct * 100)}
            onChange={(e) => setConversionPct(Number(e.target.value) / 100)}
          />
          <div className="partner-calc-value">{Math.round(conversionPct * 100)}%</div>
        </div>
      </div>

      <div className="partner-calc-output">
        <div className="partner-calc-output-grid" style={{ gridTemplateColumns: "1fr" }}>
          <div className="partner-calc-stat highlight">
            <div className="partner-calc-stat-label">{patientsConverting} of your members on a protocol → you earn</div>
            <div className="partner-calc-stat-value-big">{fmtMoney(monthlyRecurring)}<span style={{ fontSize: 20 }}>/mo</span></div>
            <div className="partner-calc-stat-sub">{fmtBig(annualRecurring)}/yr · paid every month · zero risk</div>
          </div>
        </div>
      </div>

      {!compact && (
        <div className="partner-calc-cta">
          {!emailGated ? (
            <button className="partner-calc-cta-btn" onClick={() => setEmailGated(true)}>
              Email me the full breakdown PDF →
            </button>
          ) : !submitted ? (
            <form className="partner-calc-cta-form" onSubmit={submitEmail}>
              <input
                type="email"
                placeholder="you@yourbusiness.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              />
              <button type="submit">Send it →</button>
            </form>
          ) : (
            <div className="partner-calc-cta-done">
              ★ Sent. Check {email} — full breakdown + the partner playbook PDF inside.
            </div>
          )}
        </div>
      )}
    </div>
  );
};
