// Section 6 — ROI calculator (interactive), Section 7 — Rollout, Section 8 — Final CTA, Header, Footer

// ---------- ROI CALCULATOR ----------
const fmtRub = (n) => {
  if (n >= 1_000_000_000) return (n/1_000_000_000).toFixed(1).replace(".",",") + " млрд ₽";
  if (n >= 1_000_000) return (n/1_000_000).toFixed(1).replace(".",",") + " млн ₽";
  if (n >= 1_000) return (n/1_000).toFixed(0) + " тыс ₽";
  return n.toLocaleString("ru-RU") + " ₽";
};
const fmtM = (n) => (n/1_000_000).toFixed(1).replace(".",",");

const Slider = ({ label, value, min, max, step, onChange, display, helper, minLabel, maxLabel }) => (
  <div>
    <div className="flex items-baseline justify-between mb-2">
      <label className="text-[13px] font-medium">{label}</label>
      <span className="text-[15px] tabular font-semibold font-display">{display}</span>
    </div>
    <input type="range" className="k" min={min} max={max} step={step} value={value}
      onChange={e=>onChange(Number(e.target.value))} />
    {(minLabel != null || maxLabel != null) && (
      <div className="mt-1.5 flex justify-between text-[11px] text-muted-foreground/80 tabular">
        <span>{minLabel}</span>
        <span>{maxLabel}</span>
      </div>
    )}
    {helper && <div className="mt-1 text-[12px] text-muted-foreground tabular">{helper}</div>}
  </div>
);

const pluralRu = (n, one, few, many) => {
  const mod10 = n % 10, mod100 = n % 100;
  if (mod10 === 1 && mod100 !== 11) return one;
  if (mod10 >= 2 && mod10 <= 4 && (mod100 < 10 || mod100 >= 20)) return few;
  return many;
};

const ROISection = () => {
  const [turnover, setTurnover] = React.useState(800_000_000);     // ₽ per year
  const [arShare, setArShare]   = React.useState(22);              // %
  const [odShare, setOdShare]   = React.useState(15);              // % of AR overdue
  const [team, setTeam]         = React.useState(3);               // people

  // derived
  const ar = turnover * arShare/100;
  const overdue = ar * odShare/100;
  const recover = overdue * 0.30;                                    // 30% via auto-claims/escalation
  const prevent = turnover * 0.02;                                   // 2% prevented shipments
  const salary = 1_200_000;   // avg all-in yearly per AR person
  const timeSave = team * salary * 0.40;
  const teamSaveText = Math.round(timeSave/1000) + " тыс ₽/год";

  const total = recover + prevent + timeSave;

  const [resRef, resIn] = useReveal();
  return (
    <section id="roi" aria-labelledby="roi-h" className="border-b border-border bg-muted/30">
      <div className="mx-auto max-w-7xl px-6 lg:px-10 py-24 md:py-32">
        <div className="text-center">
          <Badge icon={I.Calculator}>Калькулятор эффекта</Badge>
          <h2 id="roi-h" className="mt-5 font-display text-4xl md:text-5xl font-semibold tracking-tight text-balance">
            Калькулятор эффекта
          </h2>
          <p className="mt-5 text-base md:text-lg text-muted-foreground mx-auto max-w-2xl leading-relaxed">
            Прикиньте эффект Компаса на своих цифрах. Без обязательств — просто инструмент самопроверки.
          </p>
        </div>

        <div className="mt-14 grid lg:grid-cols-[1fr_1.1fr] gap-8 items-start">
          <div className="rounded-2xl border border-border bg-card p-7 space-y-6">
            <Slider label="Годовой оборот, ₽" value={turnover} min={100_000_000} max={5_000_000_000} step={50_000_000}
              onChange={setTurnover} display={fmtRub(turnover)}
              minLabel="100 млн ₽" maxLabel="5 млрд ₽" />
            <Slider label="Доля дебиторки в обороте" value={arShare} min={5} max={60} step={1}
              onChange={setArShare} display={arShare+"%"} helper={`${fmtRub(ar)} в моменте`}
              minLabel="5%" maxLabel="60%" />
            <Slider label="Доля просрочки в дебиторке" value={odShare} min={1} max={50} step={1}
              onChange={setOdShare} display={odShare+"%"} helper={`${fmtRub(overdue)} просрочено сейчас`}
              minLabel="1%" maxLabel="50%" />
            <Slider label="Команда по дебиторке" value={team} min={1} max={15} step={1}
              onChange={setTeam} display={team+" "+pluralRu(team,"человек","человека","человек")}
              helper={`Экономия ~${teamSaveText}`}
              minLabel={"1 человек"} maxLabel={"15 человек"} />
          </div>

          <div className="space-y-4" ref={resRef}>
            <div className="rounded-2xl border border-border bg-card p-7 relative overflow-hidden">
              <div className="absolute -top-24 -right-24 h-48 w-48 rounded-full bg-emerald-500/10 blur-3xl pointer-events-none" aria-hidden="true" />
              <div className="flex items-center gap-2">
                <span className="inline-flex items-center gap-1.5 rounded-md bg-emerald-500/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-wider text-emerald-700 dark:text-emerald-400">
                  <I.TrendUp size={12} /> Ваш эффект с Компасом за год
                </span>
              </div>
              <div className="mt-4 font-display text-5xl md:text-6xl tabular font-semibold tracking-tight text-emerald-600 dark:text-emerald-400 relative">
                <span className="tabular">{fmtM(total)}</span> млн ₽
              </div>
              <div className="mt-3 text-[12.5px] text-muted-foreground leading-relaxed">
                Оценка сверху: возвращённая просрочка + предотвращённые отгрузки + высвобожденные часы команды. Без обещаний по срокам оплаты — их диктует договор.
              </div>
            </div>

            <div className="grid sm:grid-cols-1 gap-3">
              <BreakdownCard icon={I.TrendUp} label="Возврат просрочки" value={`${fmtM(recover)} млн ₽`}
                note="30% текущей просрочки возвращается автопретензиями и эскалациями" />
              <BreakdownCard icon={I.Shield} label="Предотвращено отгрузок" value={`${fmtM(prevent)} млн ₽`}
                note="Стоп-правила: ~2% оборота, который бы ушёл должникам" />
              <BreakdownCard icon={I.Zap} label="Экономия времени" value={`${fmtM(timeSave)} млн ₽`}
                note={`${team} ${pluralRu(team,"сотрудник","сотрудника","сотрудников")} × 40% рутины`} />
            </div>

            <div className="rounded-2xl border border-border bg-card p-5 flex flex-col sm:flex-row sm:items-center gap-4">
              <div className="flex-1">
                <div className="text-[14px] font-semibold">Хотите конкретный расчёт по вашим цифрам?</div>
                <p className="mt-1 text-[12.5px] text-muted-foreground leading-relaxed">
                  Пришлём вам персонализированный отчёт с анализом срока оплаты, просрочки и потенциала на основе реальных данных вашей 1С.
                </p>
              </div>
              <Button variant="outline" href="/dashboard" icon={I.ArrowRight}>Посмотреть пример в демо</Button>
            </div>

            <div className="flex justify-center pt-2">
              <MagneticCTA>
                <Button variant="primary" size="lg" href="/dashboard" icon={I.ArrowRight}>
                  Обсудить ваш случай с экспертом
                </Button>
              </MagneticCTA>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

const BreakdownCard = ({ icon: IconCmp, label, value, note }) => (
  <div className="rounded-xl border border-border bg-card p-5">
    <div className="flex items-center gap-2">
      <div className="grid h-8 w-8 place-items-center rounded-md bg-primary/10 text-primary">
        <IconCmp size={15} />
      </div>
      <div className="text-[12px] font-medium uppercase tracking-wider text-muted-foreground">{label}</div>
    </div>
    <div className="mt-3 font-display text-2xl tabular font-semibold tracking-tight">{value}</div>
    <p className="mt-1.5 text-[12px] text-muted-foreground leading-relaxed">{note}</p>
  </div>
);

// ---------- ROLLOUT ----------
const TimelineRow = ({ period, content, arrow, tone="neutral", emphasis=false }) => {
  const borderTone = tone === "emerald" ? "border-emerald-500/50" : tone === "primary" ? "border-primary/50" : "border-border";
  const arrowTone  = tone === "emerald" ? "text-emerald-600 dark:text-emerald-400" : tone === "primary" ? "text-primary" : "text-muted-foreground";
  return (
    <div className="grid grid-cols-[90px_1fr] gap-5 items-start">
      <div className="text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground pt-1 tabular">{period}</div>
      <div className={`border-l-2 pl-4 pb-1 ${borderTone}`}>
        <div className={`text-[14px] leading-snug ${emphasis?"font-semibold":""}`}>{content}</div>
        {arrow && <div className={`mt-1.5 text-[12.5px] ${arrowTone}`}>{arrow}</div>}
      </div>
    </div>
  );
};

const TimelineCard = ({ title, subtitle, tone, weeks, highlight, children }) => {
  const iconBg = tone==="emerald" ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400" : "bg-primary/10 text-primary";
  return (
    <div className="rounded-2xl border border-border bg-card p-7">
      <div className="flex items-start justify-between mb-5">
        <div>
          <div className="text-[17px] font-semibold">{title}</div>
          <div className="mt-1 text-[12.5px] text-muted-foreground">{subtitle}</div>
        </div>
        <div className={`grid h-10 w-10 place-items-center rounded-md ${iconBg}`}>
          <I.Clock size={18} />
        </div>
      </div>
      {weeks && (
        <div className="mb-5 rounded-lg border border-border bg-muted/40 p-3">
          <div className="flex items-baseline justify-between mb-2">
            <span className="text-[10px] font-medium uppercase tracking-[0.16em] text-muted-foreground">Шкала внедрения
            </span>
            <span className="text-[11px] tabular text-muted-foreground">{weeks} нед.</span>
          </div>
          <WeekProgress weeks={weeks} highlight={highlight||[]} color={tone}/>
        </div>
      )}
      <div className="space-y-5">{children}</div>
    </div>
  );
};

const RolloutSection = () => (
  <section id="rollout" aria-labelledby="rollout-h" className="border-b border-border">
    <div className="mx-auto max-w-7xl px-6 lg:px-10 py-24 md:py-32">
      <div className="text-center">
        <Badge icon={I.Clock}>График внедрения</Badge>
        <h2 id="rollout-h" className="mt-5 font-display text-4xl md:text-5xl font-semibold tracking-tight text-balance max-w-3xl mx-auto">
          Как выглядит внедрение
        </h2>
        <p className="mt-5 text-base md:text-lg text-muted-foreground mx-auto max-w-2xl leading-relaxed">
          Для стандартной 1С — 2 недели до работы в продуктиве. Для кастомной — до 8 недель с индивидуальным маппингом. Без «сюрпризов» и без полугодовых проектов.
        </p>
      </div>

      <Reveal className="mt-14 grid lg:grid-cols-2 gap-5" stagger>
        <TimelineCard title="Простая интеграция" subtitle="Типовая 1С · 2 недели" tone="emerald" weeks={2} highlight={[1,2]}>
          <TimelineRow period="Неделя 1"
            content="Коннекторы к 1С, банку, Диадок/СБИС. Проверка данных на тестовом контуре."
            arrow="→ Первая утренняя сводка финансового директора." tone="emerald" />
          <TimelineRow period="Неделя 2"
            content="Настройка правил, ролей, уведомлений. Ввод в бой на одном юрлице."
            arrow="Результат: Компас работает в продуктиве." tone="emerald" emphasis />
        </TimelineCard>

        <TimelineCard title="Сложная интеграция" subtitle="Кастомная 1С, несколько юрлиц · до 8 недель" tone="primary" weeks={8} highlight={[1,2,3,4,5,6,7,8]}>
          <TimelineRow period="Недели 1–2"
            content="Маппинг кастомной конфигурации 1С. Аудит данных."
            arrow="→ Техническая карта миграции." tone="primary" />
          <TimelineRow period="Недели 3–4"
            content="Коннекторы, валидация, миграция."
            arrow="→ Первые данные в Компасе." tone="primary" />
          <TimelineRow period="Недели 5–6"
            content="Правила, роли, обучение команды."
            arrow="→ Первые автоматические действия." tone="primary" />
          <TimelineRow period="Недели 7–8"
            content="Ввод в бой, сопровождение."
            arrow="Результат: Компас работает в продуктиве." tone="emerald" emphasis />
        </TimelineCard>
      </Reveal>

      <div className="mt-8 rounded-2xl border border-border bg-card p-6 md:p-7 flex flex-col md:flex-row md:items-center gap-5">
        <div className="grid h-10 w-10 place-items-center rounded-md bg-primary/10 text-primary flex-shrink-0">
          <I.Shield size={18} />
        </div>
        <div className="flex-1">
          <div className="text-[15px] font-semibold">Пилот 3 недели за 1,5–2 млн ₽ с гарантией возврата</div>
          <p className="mt-1.5 text-[13px] text-muted-foreground leading-relaxed max-w-3xl">
            Если за пилот не увидите подтверждаемого эффекта по сроку оплаты или предотвращённым отгрузкам — возвращаем 100%. Полное внедрение — отдельным этапом после согласования пилота.
          </p>
        </div>
        <MagneticCTA><Button variant="primary" icon={I.ArrowRight} href="/dashboard">Записаться на консультацию</Button></MagneticCTA>
      </div>
    </div>
  </section>
);

// ---------- FINAL CTA ----------
const FinalCTA = () => (
  <section id="cta" aria-labelledby="cta-h" className="relative overflow-hidden">
    <div className="absolute inset-0 bg-gradient-to-b from-primary/10 to-transparent" aria-hidden="true" />
    <div className="relative mx-auto max-w-4xl px-6 py-24 md:py-32 text-center">
      <h2 id="cta-h" className="font-display text-4xl md:text-5xl font-semibold tracking-tight text-balance leading-[1.05]">
        30 минут разговора — <span className="text-primary">и вы поймёте</span>, подходит ли Компас
      </h2>
      <p className="mt-5 text-base md:text-lg text-muted-foreground max-w-2xl mx-auto leading-relaxed">
        Покажем продукт на ваших данных или на публичном демо-доступе. Предложим формат пилота или скажем, что нам не стоит работать. Честно и без давления.
      </p>
      <div className="mt-8 flex flex-wrap items-center justify-center gap-3">
        <MagneticCTA>
          <Button variant="primary" size="lg" icon={I.Calendar} iconRight={false} href="/dashboard">
            <span className="inline-flex items-center gap-1.5 whitespace-nowrap">
              Записаться на консультацию
              <I.ArrowRight size={16} />
            </span>
          </Button>
        </MagneticCTA>
        <Button variant="outline" size="lg" href="/dashboard" icon={null}>Зайти в демо-доступ</Button>
      </div>
      <div className="mt-6 text-[12px] text-muted-foreground tabular">
        В вашей инфраструктуре · 30+ интеграций · Консультация за 30 минут
      </div>
      <div className="mt-14 monogram text-primary/60 text-3xl" aria-hidden="true">
        <span className="mono-spin inline-block">К.</span>
      </div>
    </div>
  </section>
);

Object.assign(window, { ROISection, RolloutSection, FinalCTA });
