// Buyout calculator — per-agency estimate of contract buyout credit.
// 3 inputs (current ATS, seats, months remaining) → output: months of free
// Caliber Pro + total dollar value. CTA routes to the demo booking flow via
// window.CaliberOnboarding.startBuyout (defined in sections.jsx).
//
// Business rule (per ONBOARDING-PLAN.md Part 5): buyout cap is 12 months of
// Caliber Pro equivalent. Anything beyond is a founder conversation.

/* Estimated incumbent cost per seat per month, by currency.
   Authored from competitor pricing on the Compare pages — real number is
   confirmed on the demo call. Numbers intentionally conservative so the
   on-page estimate is credible, not inflated. */
const BUYOUT_INCUMBENT_COSTS = {
  bullhorn:   { label: 'Bullhorn',         NZD: 245, AUD: 245, GBP: 130, USD: 165 },
  jobadder:   { label: 'JobAdder',         NZD: 245, AUD: 245, GBP: 130, USD: 165 },
  vincere:    { label: 'Vincere',          NZD: 220, AUD: 220, GBP: 115, USD: 150 },
  loxo:       { label: 'Loxo',             NZD: 350, AUD: 350, GBP: 185, USD: 235 },
  crelate:    { label: 'Crelate',          NZD: 200, AUD: 200, GBP: 105, USD: 135 },
  teamtailor: { label: 'TeamTailor',       NZD: 390, AUD: 390, GBP: 210, USD: 260 },
  other:      { label: 'Something else',   NZD: 245, AUD: 245, GBP: 130, USD: 165 },
};

/* Caliber Pro monthly rate (annual billing), by currency.
   Mirrors CALIBER_TIERS → Caliber Pro → prices[cur].annual in sections.jsx.
   If pricing changes there, update here too. */
const BUYOUT_CALIBER_PRO_RATE = { NZD: 299, AUD: 299, GBP: 159, USD: 199 };

const BUYOUT_MAX_MONTHS = 12;

function BuyoutCalculator() {
  const [ats, setAts] = React.useState('bullhorn');
  const [seats, setSeats] = React.useState(5);
  const [months, setMonths] = React.useState(12);
  const [cur] = useCaliberCurrency();
  const curObj = CAL_CUR_MAP[cur];

  const clampedSeats = Math.max(1, Math.min(500, Number(seats) || 1));
  const clampedMonths = Math.max(1, Math.min(36, Number(months) || 1));

  const incumbentMoRate = BUYOUT_INCUMBENT_COSTS[ats][cur];
  const totalIncumbent = incumbentMoRate * clampedSeats * clampedMonths;

  const caliberMoRate = BUYOUT_CALIBER_PRO_RATE[cur];
  const caliberMoPerTeam = caliberMoRate * clampedSeats;
  const monthsPossible = caliberMoPerTeam > 0 ? Math.floor(totalIncumbent / caliberMoPerTeam) : 0;
  const monthsCredited = Math.min(BUYOUT_MAX_MONTHS, Math.max(1, monthsPossible));
  const totalCredit = monthsCredited * caliberMoPerTeam;

  const fmt = (n) => `${curObj.symbol}${Math.round(n).toLocaleString()}`;

  const onSubmit = () => {
    if (window.CaliberOnboarding && window.CaliberOnboarding.startBuyout) {
      window.CaliberOnboarding.startBuyout(ats, clampedSeats, clampedMonths);
    }
  };

  const inputStyle = {
    width: '100%',
    padding: '10px 12px',
    fontSize: 14,
    fontWeight: 500,
    fontFamily: 'inherit',
    background: '#fff',
    color: 'var(--cal-ink)',
    border: '1px solid var(--cal-line)',
    borderRadius: 10,
    outline: 'none',
    appearance: 'none',
    WebkitAppearance: 'none',
    boxSizing: 'border-box',
  };

  return (
    <div style={{
      background: 'var(--cal-bg-cool)',
      border: '1px solid var(--cal-line)',
      borderRadius: 24,
      padding: '36px 32px',
      marginBottom: 56,
    }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'minmax(280px, 340px) 1fr',
        gap: 40,
        alignItems: 'center',
      }} className="cal-buyout-calc-grid">
        {/* Left: framing */}
        <div>
          <div className="cal-eyebrow" style={{ marginBottom: 14 }}>
            <CalStar size={11} grad={false} style={{ color: 'var(--cal-blue-ink)' }} />
            Buyout estimator
          </div>
          <h3 style={{
            fontSize: 28,
            fontWeight: 500,
            letterSpacing: '-0.02em',
            margin: '0 0 10px',
            color: 'var(--cal-ink)',
            lineHeight: 1.15,
          }}>
            Locked into a contract?{' '}
            <span style={EMPH_BLUE}>We&rsquo;ll cover it.</span>
          </h3>
          <p style={{
            fontSize: 14,
            lineHeight: 1.55,
            color: 'var(--cal-body)',
            margin: 0,
          }}>
            Caliber free for up to {BUYOUT_MAX_MONTHS} months while your incumbent contract runs out the clock. Estimate below, exact number confirmed on the demo call.
          </p>
        </div>

        {/* Right: inputs */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(3, minmax(130px, 1fr))',
          gap: 12,
        }}>
          <BuyoutField label="Current ATS">
            <select value={ats} onChange={(e) => setAts(e.target.value)} style={inputStyle}>
              {Object.entries(BUYOUT_INCUMBENT_COSTS).map(([k, v]) => (
                <option key={k} value={k}>{v.label}</option>
              ))}
            </select>
          </BuyoutField>
          <BuyoutField label="Seats">
            <input
              type="number" inputMode="numeric" min="1" max="500"
              value={seats}
              onChange={(e) => setSeats(e.target.value)}
              style={inputStyle}
            />
          </BuyoutField>
          <BuyoutField label="Months remaining">
            <input
              type="number" inputMode="numeric" min="1" max="36"
              value={months}
              onChange={(e) => setMonths(e.target.value)}
              style={inputStyle}
            />
          </BuyoutField>
        </div>
      </div>

      {/* Output + CTA */}
      <div style={{
        marginTop: 28,
        paddingTop: 24,
        borderTop: '1px solid var(--cal-line-2)',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        gap: 20,
        flexWrap: 'wrap',
      }}>
        <div>
          <div style={{
            fontSize: 12,
            fontWeight: 600,
            letterSpacing: '0.08em',
            textTransform: 'uppercase',
            color: 'var(--cal-muted)',
            marginBottom: 8,
          }}>
            You&rsquo;d get
          </div>
          <div style={{
            fontSize: 22,
            fontWeight: 500,
            letterSpacing: '-0.01em',
            color: 'var(--cal-ink)',
            lineHeight: 1.3,
          }}>
            <span style={{ color: 'var(--cal-blue-ink)', fontWeight: 600 }}>
              {monthsCredited} month{monthsCredited === 1 ? '' : 's'}
            </span>{' '}of Caliber Pro, worth{' '}
            <span style={{ color: 'var(--cal-blue-ink)', fontWeight: 600 }}>
              {fmt(totalCredit)}
            </span>.
          </div>
          {monthsPossible > BUYOUT_MAX_MONTHS && (
            <div style={{ fontSize: 12, color: 'var(--cal-muted)', marginTop: 6 }}>
              Capped at {BUYOUT_MAX_MONTHS} months. Anything beyond is a founder conversation.
            </div>
          )}
        </div>
        <button
          className="cal-btn cal-btn--blue"
          onClick={onSubmit}
          style={{
            padding: '12px 22px',
            fontSize: 14,
            fontWeight: 500,
            whiteSpace: 'nowrap',
            display: 'inline-flex',
            alignItems: 'center',
            gap: 8,
          }}
        >
          Start my buyout {Icon.arrowR({ size: 13, color: 'currentColor' })}
        </button>
      </div>
    </div>
  );
}

function BuyoutField({ label, children }) {
  return (
    <label style={{ display: 'block' }}>
      <span style={{
        display: 'block',
        fontSize: 11,
        fontWeight: 600,
        letterSpacing: '0.08em',
        textTransform: 'uppercase',
        color: 'var(--cal-muted)',
        marginBottom: 6,
      }}>{label}</span>
      {children}
    </label>
  );
}

Object.assign(window, { BuyoutCalculator, BuyoutField });
