// Calculator v3 — feature-based flat-rate pricing.
// User picks features → fixed monthly subscription. No volume sliders, no per-call billing.
// Bundle discounts auto-apply when user selects all features in a discount group.
const { useState: useStateCalc, useMemo: useMemoCalc } = React;

function fmtMoney(n) {
  if (n === 0) return "0 ₽";
  return Math.round(n).toLocaleString("ru-RU") + " ₽";
}

function CalcIcon({ name }) {
  const p = { width: 20, height: 20, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "suggest": return <svg {...p}><path d="M3 6h14M3 12h10M3 18h7" /><circle cx="20" cy="18" r="3" stroke="var(--accent)" /></svg>;
    case "iploc":   return <svg {...p}><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M3 9h18M7 14h4M14 14h3" stroke="var(--accent)" /></svg>;
    case "fuzzy":   return <svg {...p}><circle cx="11" cy="11" r="7" /><path d="m17 17 4 4" stroke="var(--accent)" /></svg>;
    case "pin":     return <svg {...p}><circle cx="12" cy="10" r="4" stroke="var(--accent)" /><path d="M12 14v8M6 22h12" /></svg>;
    case "reverse": return <svg {...p}><path d="M3 12h14M14 8l4 4-4 4" stroke="var(--accent)" /><path d="M21 4v16" /></svg>;
    case "tree":    return <svg {...p}><rect x="3" y="3" width="6" height="6" /><rect x="15" y="3" width="6" height="6" stroke="var(--accent)" /><rect x="9" y="15" width="6" height="6" /><path d="M6 9v3h12V9M12 12v3" /></svg>;
    case "parse":   return <svg {...p}><path d="M4 6h16M4 12h10M4 18h16" /><circle cx="18" cy="12" r="3" stroke="var(--accent)" /></svg>;
    case "batch":   return <svg {...p}><rect x="3" y="4" width="18" height="4" /><rect x="3" y="10" width="18" height="4" stroke="var(--accent)" /><rect x="3" y="16" width="18" height="4" /></svg>;
    case "webhook": return <svg {...p}><circle cx="6" cy="18" r="2.5" stroke="var(--accent)" /><circle cx="18" cy="6" r="2.5" /><circle cx="6" cy="6" r="2.5" /><path d="M6 8v8M16 7l-8 9" /></svg>;
    case "sla":     return <svg {...p}><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" stroke="var(--accent)" /></svg>;
    default: return null;
  }
}

function Calculator() {
  const { CALC_FEATURES, CALC_BUNDLES } = window.__DATA;
  const [selected, setSelected] = useStateCalc(new Set(["suggest"])); // suggest is default-on

  function toggle(id) {
    const next = new Set(selected);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    setSelected(next);
  }

  // Group features by their group label, preserving order
  const grouped = useMemoCalc(() => {
    const groups = [];
    const map = new Map();
    CALC_FEATURES.forEach((f) => {
      if (!map.has(f.group)) {
        const g = { label: f.group, items: [] };
        map.set(f.group, g);
        groups.push(g);
      }
      map.get(f.group).items.push(f);
    });
    return groups;
  }, [CALC_FEATURES]);

  // Compute subtotal, applicable bundles, total
  const subtotal = useMemoCalc(() => {
    return CALC_FEATURES.filter((f) => selected.has(f.id)).reduce((s, f) => s + f.price, 0);
  }, [selected, CALC_FEATURES]);

  const activeBundles = useMemoCalc(() => {
    return CALC_BUNDLES.filter((b) => b.requires.every((r) => selected.has(r)));
  }, [selected, CALC_BUNDLES]);

  const discount = activeBundles.reduce((s, b) => s + b.discount, 0);
  const total = Math.max(0, subtotal - discount);

  // Plan recommendation
  let plan;
  const sel = selected.size;
  if (sel === 0) plan = { name: "Старт", note: "Бесплатно · 10 000 запросов в сутки", hint: "Подходит для тестирования и пет-проектов" };
  else if (sel <= 3 && total < 4000) plan = { name: "Базовый", note: `${fmtMoney(total)} / мес`, hint: "Для команд до 5 человек, без SLA" };
  else if (selected.has("sla") || total >= 8000) plan = { name: "Прод", note: `${fmtMoney(total)} / мес · SLA 99.95%`, hint: "Боевой продакшен с поддержкой 24/7" };
  else plan = { name: "Команда", note: `${fmtMoney(total)} / мес`, hint: "Стандартная нагрузка, поддержка в рабочие часы" };

  const selectedList = CALC_FEATURES.filter((f) => selected.has(f.id));

  return (
    <div className="calc" id="pricing">
      {/* Left — feature cards by group */}
      <div className="calc-features">
        {grouped.map((g) => (
          <div key={g.label} className="calc-group">
            <div className="calc-group-head">
              <span className="calc-group-title">{g.label}</span>
              <span className="calc-group-line"></span>
              <span className="calc-group-count mono">
                {g.items.filter((it) => selected.has(it.id)).length} / {g.items.length}
              </span>
            </div>
            <div className="calc-cards">
              {g.items.map((f) => {
                const on = selected.has(f.id);
                return (
                  <button
                    key={f.id}
                    type="button"
                    className={`calc-card ${on ? "on" : "off"}`}
                    onClick={() => toggle(f.id)}
                    aria-pressed={on}
                  >
                    <div className="calc-card-row">
                      <span className="calc-card-icon"><CalcIcon name={f.icon} /></span>
                      {f.badge && <span className="calc-card-badge">{f.badge}</span>}
                      <span className="calc-card-check" aria-hidden="true">
                        <svg width="11" height="11" viewBox="0 0 10 10"><path d="M1.5 5.5L4 8L8.5 2" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
                      </span>
                    </div>
                    <div className="calc-card-name">{f.name}</div>
                    <div className="calc-card-desc">{f.desc}</div>
                    <div className="calc-card-price">
                      <span className="calc-card-price-amount">{f.price.toLocaleString("ru-RU")} ₽</span>
                      <span className="calc-card-price-per">/ мес</span>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        ))}

        <div className="calc-api-note">
          <span className="calc-api-note-tag mono">API</span>
          <div>
            <strong>Все фичи доступны через единый REST API.</strong>{" "}
            <span style={{ color: "var(--ink-2)" }}>API для интеграции и тестирования — отдельно не оплачивается, входит в любую фичу.</span>
          </div>
        </div>
      </div>

      {/* Right — summary panel */}
      <aside className="calc-summary">
        <div className="calc-summary-inner">
          <div className="calc-summary-label">ИТОГО В МЕСЯЦ</div>
          <div className="calc-summary-total">
            <span className="amount">{fmtMoney(total)}</span>
          </div>
          {discount > 0 && (
            <div className="calc-summary-saving mono">
              экономия <span style={{ color: "var(--accent)" }}>{fmtMoney(discount)}</span> по наборам
            </div>
          )}

          {selectedList.length > 0 ? (
            <ul className="calc-selected">
              {selectedList.map((f) => (
                <li key={f.id} className="calc-selected-item">
                  <span className="calc-selected-name">{f.name}</span>
                  <span className="calc-selected-price mono">{f.price.toLocaleString("ru-RU")} ₽</span>
                </li>
              ))}
              {activeBundles.map((b) => (
                <li key={b.id} className="calc-selected-item bundle">
                  <span className="calc-selected-name">↘ {b.name}</span>
                  <span className="calc-selected-price mono" style={{ color: "var(--accent)" }}>−{b.discount.toLocaleString("ru-RU")} ₽</span>
                </li>
              ))}
            </ul>
          ) : (
            <div className="calc-empty">
              Выберите фичи слева — здесь появится итог.
            </div>
          )}

          <div className="calc-divider" />

          <div className="calc-plan">
            <div className="calc-plan-tag mono">Рекомендованный план</div>
            <div className="calc-plan-name">{plan.name}</div>
            <div className="calc-plan-note mono">{plan.note}</div>
            <p className="calc-plan-hint">{plan.hint}</p>
          </div>

          <div className="calc-actions">
            <a href="cabinet.html" className="btn btn-primary btn-lg" style={{ width: "100%", justifyContent: "center" }}>
              {total > 0 ? "Подключить →" : "Начать бесплатно →"}
            </a>
            <a href="#" className="btn btn-ghost" style={{ width: "100%", justifyContent: "center" }}>
              Связаться по Энтерпрайзу
            </a>
          </div>

          <ul className="calc-bullets">
            <li>Оплата помесячно · можно остановить в любой момент</li>
            <li>Юр.лицо РФ · акты, НДС, безнал</li>
            <li>14 дней триал · без привязки карты</li>
          </ul>
        </div>
      </aside>
    </div>
  );
}

Object.assign(window, { Calculator });
