/* Krytz · Pricing calculator
 *
 * Slider for seats → animated total. Tier-aware pricing with
 * yearly discount. Tweens the displayed total smoothly.
 */

(function () {
  const { useState, useEffect, useRef } = React;

  const TIERS = {
    starter: { name: 'Starter', price: 0,  ai: 50,  maxSeats: 1 },
    pro:     { name: 'Pro',     price: 8,  ai: 1500, maxSeats: 1 },
    teams:   { name: 'Teams',   price: 15, ai: 3500, maxSeats: 200 },
  };

  function useCountUp(target, ms = 360) {
    const [val, setVal] = useState(target);
    const fromRef = useRef(target);
    const startRef = useRef(null);
    useEffect(() => {
      fromRef.current = val;
      startRef.current = performance.now();
      let raf;
      const step = (t) => {
        const elapsed = t - startRef.current;
        const k = Math.min(1, elapsed / ms);
        const e = 1 - Math.pow(1 - k, 3); // easeOutCubic
        setVal(fromRef.current + (target - fromRef.current) * e);
        if (k < 1) raf = requestAnimationFrame(step);
      };
      raf = requestAnimationFrame(step);
      return () => cancelAnimationFrame(raf);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [target]);
    return val;
  }

  function PricingCalc() {
    const [tier, setTier] = useState('teams');
    const [billing, setBilling] = useState('monthly');
    const [seats, setSeats] = useState(8);

    const t = TIERS[tier];
    const effectiveSeats = tier === 'teams' ? seats : 1;
    const baseMonthly = t.price * effectiveSeats;
    const yearlyDiscount = 0.2; // 20% off when billed annually
    const monthlyEffective = billing === 'yearly' ? baseMonthly * (1 - yearlyDiscount) : baseMonthly;
    const total = billing === 'yearly' ? monthlyEffective * 12 : monthlyEffective;
    const savings = billing === 'yearly' ? baseMonthly * 12 * yearlyDiscount : 0;

    const animatedTotal = useCountUp(total);
    const animatedSeats = useCountUp(effectiveSeats, 200);

    const dollarsPart = Math.floor(animatedTotal);
    const totalLabel = billing === 'yearly' ? '/year' : '/month';

    return (
      <div className="pc-wrap">
        <div className="pc-left">
          <div className="eyebrow">Pricing</div>
          <h3>Pay for <em>what you actually use.</em></h3>

          <div className="pc-tier-row">
            {Object.entries(TIERS).map(([key, def]) => (
              <button
                key={key}
                className={`pc-tier ${tier === key ? 'is-on' : ''}`}
                onClick={() => setTier(key)}
              >
                {def.name}
              </button>
            ))}
          </div>

          <div className="pc-billing">
            <button
              className={billing === 'monthly' ? 'is-on' : ''}
              onClick={() => setBilling('monthly')}
            >Monthly</button>
            <button
              className={billing === 'yearly' ? 'is-on' : ''}
              onClick={() => setBilling('yearly')}
            >Yearly · save 20%</button>
          </div>

          <div className="pc-slider-wrap">
            <div className="pc-slider-label">
              <span className="l">{tier === 'teams' ? 'Team size' : 'Seats'}</span>
              <span className="v">{Math.round(animatedSeats)} <span style={{ fontSize: 12, color: 'var(--ink-3)', letterSpacing: '0.06em' }}>seats</span></span>
            </div>
            <input
              type="range"
              min={tier === 'teams' ? 2 : 1}
              max={tier === 'teams' ? 80 : 1}
              step="1"
              value={seats}
              disabled={tier !== 'teams'}
              onChange={(e) => setSeats(parseInt(e.target.value, 10))}
              className="pr-slider"
              style={{ opacity: tier === 'teams' ? 1 : 0.4 }}
            />
            {tier === 'teams' && (
              <div className="pc-ticks">
                <span>2</span><span>20</span><span>40</span><span>60</span><span>80</span>
              </div>
            )}
          </div>
        </div>

        <div className="pc-right">
          <div className="pc-total-label">Your total</div>
          <div className="pc-total">
            <span className="currency">$</span>
            {dollarsPart}
            <span className="per">{totalLabel}</span>
          </div>

          <div className="pc-breakdown">
            <div className="b-row">
              <span className="l">{t.name} · {effectiveSeats} seat{effectiveSeats > 1 ? 's' : ''}</span>
              <span>${baseMonthly.toFixed(0)}/mo</span>
            </div>
            <div className="b-row">
              <span className="l">AI budget envelope</span>
              <span>{(t.ai * effectiveSeats).toLocaleString()} usage credits/day</span>
            </div>
            {billing === 'yearly' && (
              <div className="b-row">
                <span className="l">Annual discount</span>
                <span>− ${(savings).toFixed(0)}/yr</span>
              </div>
            )}
            <div className="b-row" style={{ paddingTop: 4, borderTop: '1px solid var(--line)', color: 'var(--ink)' }}>
              <span className="l">Effective per seat / month</span>
              <span>${(monthlyEffective / Math.max(effectiveSeats, 1)).toFixed(2)}</span>
            </div>
          </div>

          {billing === 'yearly' && savings > 0 && (
            <div className="pc-savings">✦ Saving ${savings.toFixed(0)} this year</div>
          )}
        </div>
      </div>
    );
  }

  window.PricingCalc = PricingCalc;
})();
