<section id="apromt-pricing" class="apromt-pricing">
  <div class="apromt-pricing__wrap">
    <header class="apromt-pricing__head">
      <h2>Тарифы АПРОМТ (виджеты F5 + внедрение)</h2>
      <p>Выберите пакет и параметры — калькулятор покажет ориентир. Финальная смета зависит от воронки и каналов.</p>
    </header>

    <div class="apromt-pricing__grid">
      <!-- LEFT: Controls -->
      <div class="apromt-pricing__card apromt-pricing__card--controls">
        <div class="apromt-field">
          <label class="apromt-label">Пакет</label>
          <div class="apromt-pack">
            <button type="button" class="apromt-pack__btn" data-pack="start">Start</button>
            <button type="button" class="apromt-pack__btn is-active" data-pack="business">Business <span class="apromt-badge">Хит</span></button>
            <button type="button" class="apromt-pack__btn" data-pack="premium">Premium</button>
          </div>
        </div>

        <div class="apromt-field">
          <label class="apromt-label" for="apromt-users">Пользователей amoCRM: <span id="apromt-users-val">3</span></label>
          <input id="apromt-users" type="range" min="1" max="5" step="1" value="3">
          <div class="apromt-hint">До 5 пользователей — ваш базовый сегмент.</div>
        </div>

        <div class="apromt-field">
          <label class="apromt-label">Доп. опции (усиление пакета)</label>
          <label class="apromt-check">
            <input type="checkbox" id="opt-docs" checked>
            <span>Документы (КП/счета/договоры)</span>
          </label>
          <label class="apromt-check">
            <input type="checkbox" id="opt-sheets" checked>
            <span>Отчетность в Google Sheets</span>
          </label>
          <label class="apromt-check">
            <input type="checkbox" id="opt-telegram" checked>
            <span>Уведомления/контроль в Telegram</span>
          </label>
          <div class="apromt-hint">Внутри пакетов часть опций уже включена — чекбоксы добавляют надстройки.</div>
        </div>

        <div class="apromt-field">
          <label class="apromt-label">Ориентир по внедрению (работы АПРОМТ)</label>
          <select id="impl-speed" class="apromt-select">
            <option value="basic" selected>Стандарт (запуск за 1–3 дня)</option>
            <option value="fast">Быстрый старт (за 1 день)</option>
            <option value="pro">Про (регламенты + обучение + контроль качества)</option>
          </select>
        </div>
      </div>

      <!-- RIGHT: Result -->
      <div class="apromt-pricing__card apromt-pricing__card--result">
        <div class="apromt-result">
          <div class="apromt-result__top">
            <div>
              <div class="apromt-kicker">Итого ориентир</div>
              <div class="apromt-total"><span id="apromt-total">0</span> ₽</div>
              <div class="apromt-sub">Включает: лицензии виджетов (оценочно) + внедрение/настройка.</div>
            </div>
            <div class="apromt-breakdown">
              <div class="apromt-line"><span>Виджеты (оценочно)</span><b><span id="apromt-widgets">0</span> ₽</b></div>
              <div class="apromt-line"><span>Работы АПРОМТ</span><b><span id="apromt-impl">0</span> ₽</b></div>
            </div>
          </div>

          <div class="apromt-includes">
            <h3>Что входит в пакет</h3>
            <ul id="apromt-includes-list"></ul>
          </div>

          <form class="apromt-form" onsubmit="return false;">
            <input type="hidden" id="lead-pack" name="pack" value="business">
            <input type="hidden" id="lead-users" name="users" value="3">
            <input type="hidden" id="lead-total" name="total" value="">
            <input type="hidden" id="lead-widgets" name="widgets" value="">
            <input type="hidden" id="lead-impl" name="impl" value="">
            <input type="hidden" id="lead-options" name="options" value="">

            <div class="apromt-form__row">
              <input class="apromt-input" type="text" name="name" placeholder="Имя" required>
              <input class="apromt-input" type="tel" name="phone" placeholder="Телефон" required>
            </div>

            <button type="button" class="apromt-btn" id="apromt-send">
              Получить расчет и список виджетов
            </button>
            <div class="apromt-hint">Кнопка сейчас формирует данные. Подключим отправку в amoCRM/форму на следующем шаге.</div>
          </form>

          <pre class="apromt-debug" id="apromt-debug" style="display:none;"></pre>
        </div>
      </div>
    </div>
  </div>

  <style>
    .apromt-pricing{padding:48px 0;font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial}
    .apromt-pricing__wrap{max-width:1100px;margin:0 auto;padding:0 16px}
    .apromt-pricing__head h2{margin:0 0 8px;font-size:32px;line-height:1.2}
    .apromt-pricing__head p{margin:0 0 22px;color:#444}
    .apromt-pricing__grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}
    .apromt-pricing__card{border:1px solid #e7e7e7;border-radius:14px;background:#fff;padding:18px}
    @media (max-width: 900px){.apromt-pricing__grid{grid-template-columns:1fr}}
    .apromt-field{margin-bottom:16px}
    .apromt-label{display:block;margin:0 0 8px;font-weight:600}
    .apromt-hint{margin-top:8px;color:#666;font-size:13px}
    .apromt-pack{display:flex;gap:8px;flex-wrap:wrap}
    .apromt-pack__btn{border:1px solid #ddd;background:#fafafa;padding:10px 12px;border-radius:10px;cursor:pointer}
    .apromt-pack__btn.is-active{border-color:#111;background:#111;color:#fff}
    .apromt-badge{display:inline-block;margin-left:6px;background:#fff;color:#111;border-radius:999px;padding:2px 8px;font-size:12px}
    .apromt-check{display:flex;gap:10px;align-items:center;margin:8px 0}
    .apromt-select,.apromt-input{width:100%;border:1px solid #ddd;border-radius:10px;padding:10px 12px}
    .apromt-result__top{display:flex;gap:16px;justify-content:space-between;align-items:flex-start;flex-wrap:wrap}
    .apromt-kicker{color:#666;font-size:13px}
    .apromt-total{font-size:34px;font-weight:800;margin-top:4px}
    .apromt-sub{color:#666;font-size:13px;max-width:420px}
    .apromt-breakdown{min-width:260px;border:1px solid #eee;border-radius:12px;padding:12px}
    .apromt-line{display:flex;justify-content:space-between;margin:6px 0;color:#333}
    .apromt-includes h3{margin:18px 0 8px;font-size:18px}
    .apromt-includes ul{margin:0;padding-left:18px;color:#333}
    .apromt-form{margin-top:14px}
    .apromt-form__row{display:grid;grid-template-columns:1fr 1fr;gap:10px}
    @media (max-width: 600px){.apromt-form__row{grid-template-columns:1fr}}
    .apromt-btn{width:100%;margin-top:10px;background:#111;color:#fff;border:0;border-radius:12px;padding:12px 14px;font-weight:700;cursor:pointer}
    .apromt-btn:hover{opacity:.92}
    .apromt-debug{margin-top:12px;background:#0b1020;color:#d5e3ff;border-radius:12px;padding:12px;overflow:auto;font-size:12px}
  </style>

  <script>
    (function(){
      const fmt = (n)=> new Intl.NumberFormat('ru-RU').format(Math.round(n));

      // ВАЖНО: это ориентировочный калькулятор.
      // Widgets = оценка "виджеты F5" за месяц * 12 * users.
      // Далее + работы АПРОМТ (фикс за внедрение).
      const packs = {
        start: {
          name: "АПРОМТ Start",
          // пример: 3-4 виджета по цене "как 1-2 кофе/день" — тут ставим условную ставку.
          widgetPerUserMonth: 900,
          includes: [
            "Антидубль (чистота базы, устранение дублей)",
            "DaData (быстрое заполнение реквизитов B2B)",
            "Базовое распределение заявок",
            "Платформа F5: базовые улучшения и контроль"
          ]
        },
        business: {
          name: "АПРОМТ Business (Хит)",
          widgetPerUserMonth: 1500,
          includes: [
            "Все из Start",
            "Триггеры: автозадачи, контроль регламентов, эскалации",
            "Telegram-уведомления руководителю/исполнителям",
            "Google Sheets Lite: контроль просрочек/качества",
            "Доп. уведомления (пуш/контроль событий)"
          ]
        },
        premium: {
          name: "АПРОМТ Premium",
          widgetPerUserMonth: 2400,
          includes: [
            "Все из Business",
            "Документы: КП/счета/договоры в 1 клик",
            "Полная выгрузка/синхронизация с Google Sheets",
            "Хранилище файлов (Google Диск) и порядок в документах"
          ]
        }
      };

      const opt = {
        docs: { addPerUserMonth: 400, label: "Документы" },
        sheets: { addPerUserMonth: 250, label: "Google Sheets" },
        telegram: { addPerUserMonth: 150, label: "Telegram" }
      };

      const impl = {
        basic:  { start: 19000, business: 29000, premium: 49000 },
        fast:   { start: 29000, business: 39000, premium: 65000 },
        pro:    { start: 39000, business: 59000, premium: 89000 }
      };

      let state = { pack: "business", users: 3 };

      const elUsers = document.getElementById("apromt-users");
      const elUsersVal = document.getElementById("apromt-users-val");
      const elIncludes = document.getElementById("apromt-includes-list");
      const elTotal = document.getElementById("apromt-total");
      const elWidgets = document.getElementById("apromt-widgets");
      const elImpl = document.getElementById("apromt-impl");

      const elDocs = document.getElementById("opt-docs");
      const elSheets = document.getElementById("opt-sheets");
      const elTelegram = document.getElementById("opt-telegram");
      const elImplSpeed = document.getElementById("impl-speed");

      const leadPack = document.getElementById("lead-pack");
      const leadUsers = document.getElementById("lead-users");
      const leadTotal = document.getElementById("lead-total");
      const leadWidgets = document.getElementById("lead-widgets");
      const leadImpl = document.getElementById("lead-impl");
      const leadOptions = document.getElementById("lead-options");

      function activePackBtn(pack){
        document.querySelectorAll(".apromt-pack__btn").forEach(b=>{
          b.classList.toggle("is-active", b.dataset.pack === pack);
        });
      }

      function calc(){
        const p = packs[state.pack];
        const users = state.users;

        const options = [];
        let add = 0;
        if(elDocs.checked){ add += opt.docs.addPerUserMonth; options.push(opt.docs.label); }
        if(elSheets.checked){ add += opt.sheets.addPerUserMonth; options.push(opt.sheets.label); }
        if(elTelegram.checked){ add += opt.telegram.addPerUserMonth; options.push(opt.telegram.label); }

        const widgetsYear = (p.widgetPerUserMonth + add) * 12 * users;
        const implFixed = impl[elImplSpeed.value][state.pack];
        const total = widgetsYear + implFixed;

        elUsersVal.textContent = users;
        elWidgets.textContent = fmt(widgetsYear);
        elImpl.textContent = fmt(implFixed);
        elTotal.textContent = fmt(total);

        elIncludes.innerHTML = "";
        p.includes.forEach(text=>{
          const li = document.createElement("li");
          li.textContent = text;
          elIncludes.appendChild(li);
        });

        leadPack.value = state.pack;
        leadUsers.value = users;
        leadTotal.value = Math.round(total);
        leadWidgets.value = Math.round(widgetsYear);
        leadImpl.value = Math.round(implFixed);
        leadOptions.value = options.join(", ");
      }

      // Events
      document.querySelectorAll(".apromt-pack__btn").forEach(btn=>{
        btn.addEventListener("click", ()=>{
          state.pack = btn.dataset.pack;
          activePackBtn(state.pack);
          calc();
        });
      });

      elUsers.addEventListener("input", ()=>{
        state.users = parseInt(elUsers.value, 10);
        calc();
      });

      [elDocs, elSheets, elTelegram, elImplSpeed].forEach(x=> x.addEventListener("change", calc));

      document.getElementById("apromt-send").addEventListener("click", ()=>{
        const payload = {
          pack: leadPack.value,
          users: leadUsers.value,
          total: leadTotal.value,
          widgets: leadWidgets.value,
          impl: leadImpl.value,
          options: leadOptions.value
        };
        // На следующем шаге заменим на отправку в вашу форму/в amoCRM.
        // Сейчас — просто покажем, какие данные улетают.
        const dbg = document.getElementById("apromt-debug");
        dbg.style.display = "block";
        dbg.textContent = "Данные заявки (пример):\n" + JSON.stringify(payload, null, 2);
      });

      // init
      activePackBtn(state.pack);
      calc();
    })();
  </script>
</section>