const { useState: useStateCalc, useMemo } = React;

const SETUP_COST = 0;
const ACCURACY = 80;

function Calculator() {
  const [ops, setOps] = useStateCalc(5);
  const [salary, setSalary] = useStateCalc(45);
  const [requests, setRequests] = useStateCalc(200);
  const [typical, setTypical] = useStateCalc(65);
  const [hasNight, setHasNight] = useStateCalc(false);

  const calc = useMemo(() => {
    const totalMsgMonth = requests * 30;
    const typicalMsg = totalMsgMonth * typical / 100;
    const botMsgMonth = Math.round(typicalMsg * ACCURACY / 100);

    let botCost;
    if (botMsgMonth <= 2000) botCost = 10000;
    else if (botMsgMonth <= 10000) botCost = 30000;
    else if (botMsgMonth <= 50000) botCost = 50000;
    else botCost = Math.min(100000, 50000 + (botMsgMonth - 50000) * 1);

    const freedOps = +(ops * (typical / 100) * (ACCURACY / 100)).toFixed(1);
    const savingOps = Math.round(freedOps * salary * 1000);

    const nightSaving = hasNight
      ? 0
      : Math.round(ops * 0.25 * (typical / 100) * (ACCURACY / 100) * salary * 1000);

    const grossSaving = savingOps + nightSaving;
    const netSaving = Math.max(0, grossSaving - botCost - SETUP_COST);

    const nightMsgMonth = hasNight ? 0 : Math.round(requests * 0.20 * 30);

    let roiLabel;
    const roiDaysRaw = grossSaving > 0
      ? Math.round((botCost + SETUP_COST) / grossSaving * 30)
      : 999;
    if (netSaving <= 0) roiLabel = '—';
    else if (roiDaysRaw < 30) roiLabel = `~${roiDaysRaw} дней`;
    else if (roiDaysRaw <= 90) roiLabel = `~${Math.round(roiDaysRaw / 30)} мес`;
    else roiLabel = '—';

    return { botMsgMonth, totalMsgMonth, nightMsgMonth, freedOps, grossSaving, netSaving, botCost, roiLabel };
  }, [ops, salary, requests, typical, hasNight]);

  const h = { big: calc.grossSaving.toLocaleString('ru-RU'), unit: '₽ в месяц', label: 'Высвобождено от типовых запросов' };

  const formatNum = (n) => n.toLocaleString('ru-RU');

  return (
    <section className="bg-alt" id="calc">
      <div className="wrap">
        <div className="section-head">
          <div className="eyebrow-plain">Сколько ресурса высвободит бот</div>
          <h2>Подставьте свои цифры и посмотрите, что получится.</h2>
        </div>
        <div className="calc-grid">
          <div className="calc-inputs">
            <label className="calc-toggle-card">
              <span className="calc-toggle-card-label">Есть ночная смена поддержки?</span>
              <span className="calc-switch">
                <input type="checkbox" checked={hasNight} onChange={e => setHasNight(e.target.checked)} />
                <span className="calc-switch-track" />
                <span className="calc-switch-thumb" />
              </span>
            </label>
            <div className="calc-field">
              <div className="calc-field-head">
                <span className="calc-field-label">Операторов поддержки</span>
                <span className="calc-field-value">{ops}</span>
              </div>
              <input type="range" min="1" max="20" value={ops} onChange={e => setOps(+e.target.value)} className="calc-slider"/>
            </div>
            <div className="calc-field">
              <div className="calc-field-head">
                <span className="calc-field-label">Зарплата оператора, ₽/мес</span>
                <span className="calc-field-value">{formatNum(salary * 1000)} ₽</span>
              </div>
              <input type="range" min="30" max="120" step="5" value={salary} onChange={e => setSalary(+e.target.value)} className="calc-slider"/>
            </div>
            <div className="calc-field">
              <div className="calc-field-head">
                <span className="calc-field-label">Сообщений в день</span>
                <span className="calc-field-value">{requests}</span>
              </div>
              <input type="range" min="50" max="3000" step="50" value={requests} onChange={e => setRequests(+e.target.value)} className="calc-slider"/>
            </div>
            <div className="calc-field">
              <div className="calc-field-head">
                <span className="calc-field-label">% типовых вопросов</span>
                <span className="calc-field-value">{typical}%</span>
              </div>
              <input type="range" min="0" max="100" step="5" value={typical} onChange={e => setTypical(+e.target.value)} className="calc-slider"/>
            </div>
          </div>
          <div className="calc-output">
            <div className="calc-cards">
              <div className="calc-rcard">
                <div className="calc-rcard-eyebrow">Бот закроет в месяц</div>
                <div className="calc-rcard-num">{formatNum(calc.botMsgMonth)}</div>
                <div className="calc-rcard-sub">сообщений из {formatNum(calc.totalMsgMonth)} в месяц</div>
              </div>

              <div className="calc-rcard calc-rcard-primary">
                <div className="calc-rcard-eyebrow">{h.label}</div>
                <div className="calc-rcard-num">{h.big} <span className="calc-rcard-unit">{h.unit}</span></div>
                <div className="calc-rcard-sub">с учётом подписки · высвобождение ~{calc.freedOps} операторов</div>
              </div>

              <div className="calc-rcard">
                <div className="calc-rcard-eyebrow">Окупаемость</div>
                <div className="calc-rcard-num">{calc.roiLabel}</div>
                {!hasNight && (
                  <div className="calc-rcard-sub">+{formatNum(calc.nightMsgMonth)} ночных обращений теперь получат ответ</div>
                )}
              </div>
            </div>

            <a href="#cta" className="calc-cta-btn">Получить детальный расчёт</a>
          </div>        </div>
      </div>
    </section>
  );
}

window.Calculator = Calculator;
