// Sections 1 (Hero), 2 (Pains), 3 (Values)

// ----- HERO -----
const HeroTickerLine = () => {
  const events = [
    ["rose",    "21:14", "ЕФРСБ: новое дело — ООО «Техпром-МСК»"],
    ["emerald", "21:12", "Автосверка: разнесено 12 платежей · 4,8 М ₽"],
    ["amber",   "21:09", "Просрочка 14 дн — отправлена претензия через Диадок"],
    ["rose",    "21:04", "Стоп-правило · заблокирована отгрузка должнику"],
    ["emerald", "20:58", "Контур.Фокус: скоринг Ромашка B → A"],
  ];
  return (
    <div className="hero-ticker relative h-6 overflow-hidden">
      <div className="absolute inset-x-0" style={{animation:"ticker 14s linear infinite"}}>
        {[...events, ...events].map((e,i)=>(
          <div key={i} className="h-6 flex items-center gap-2 text-[12px]">
            <Dot tone={e[0]} />
            <span className="tabular text-muted-foreground">{e[1]}</span>
            <span className="text-foreground/85">{e[2]}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

const HeroSection = () => (
  <section id="hero" aria-labelledby="hero-h" className="relative overflow-hidden border-b border-border">
    <div className="absolute inset-0 radial-primary pointer-events-none" aria-hidden="true" />
    <div className="absolute inset-0 hero-grid opacity-70" aria-hidden="true" />
    {/* scanline accent */}
    <div className="absolute inset-y-0 right-0 w-px bg-gradient-to-b from-transparent via-primary/40 to-transparent hidden lg:block" aria-hidden="true" />

    <div className="relative mx-auto max-w-7xl px-6 lg:px-10 pt-16 pb-8 md:pt-20">
      {/* Eyebrow byline */}
      <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-[11px] font-medium uppercase tracking-[0.18em] text-muted-foreground border-b border-border pb-4">
        <span className="inline-flex items-center gap-2">
          <span className="h-1.5 w-1.5 rounded-full bg-primary" />
          <span className="text-foreground">Компас · выпуск 2026.04</span>
        </span>
        <span className="hidden md:inline">Для финансовых директоров и собственников · B2B, ₽0,5–5 млрд</span>
        <span className="hidden lg:inline ml-auto">Русский · 30+ интеграций</span>
      </div>
    </div>

    <div className="relative mx-auto max-w-7xl px-6 lg:px-10 pt-8 md:pt-10 pb-10">
      <div className="grid md:grid-cols-[1.05fr_1fr] gap-10 md:gap-12 lg:gap-16 items-start">
        {/* LEFT: typography-first */}
        <div className="relative">
          <div className="inline-flex items-center gap-2 rounded-full border border-border bg-background/80 backdrop-blur px-3 py-1 text-[11px]">
            <span className="relative flex h-2 w-2">
              <span className="absolute inline-flex h-full w-full rounded-full bg-primary opacity-75" style={{animation:"pulseDot 2s ease-out infinite"}} />
              <span className="relative inline-flex rounded-full h-2 w-2 bg-primary" />
            </span>
            <span className="font-medium">Работает на ваших данных 1С — мы их не видим</span>
          </div>

          <h1 id="hero-h" className="mt-6 font-display font-semibold tracking-[-0.035em] text-balance"
              style={{fontSize:"clamp(40px, 5.4vw, 76px)", lineHeight:"0.98"}}>
            <span className="block">Контроль</span>
            <span className="block"><span className="hl-gradient">дебиторки</span>, который</span>
            <span className="block">работает <span className="underline decoration-primary decoration-[3px] underline-offset-8">без вас</span>.</span>
          </h1>

          <p className="mt-7 text-[16px] md:text-[17px] text-muted-foreground leading-relaxed text-pretty max-w-xl">
            От первой красной отгрузки до подачи в суд — всё в одном окне. Для финансового директора, собственника и всего отдела дебиторки. Работает на копии ваших данных 1С, без доработки типовой конфигурации.
          </p>

          {/* Inline KPI strip — 3 facts at a glance */}
          <div className="mt-8 grid grid-cols-3 gap-0 border-y border-border divide-x divide-border">
            {[
              ["2 нед.", "до боевого запуска"],
              ["96%", "платежей разносятся сами"],
              ["−11 дн", "срок оплаты ↓"],
            ].map(([v,l])=>(
              <div key={l} className="py-4 px-1 first:pl-0">
                <div className="font-display text-[28px] md:text-[32px] font-semibold tabular tracking-tight text-foreground">{v}</div>
                <div className="mt-0.5 text-[11px] uppercase tracking-wider text-muted-foreground leading-tight">{l}</div>
              </div>
            ))}
          </div>

          <div className="mt-8 flex flex-wrap items-center gap-3">
            <MagneticCTA><Button variant="primary" size="lg" icon={I.ArrowRight} href="/dashboard">Записаться на консультацию</Button></MagneticCTA>
            <Button variant="outline" size="lg" href="/dashboard" icon={null}>Зайти в демо-доступ</Button>
          </div>
          <div className="mt-3 text-[12px] text-muted-foreground tabular">30 минут · на ваших данных · без обязательств</div>
        </div>

        {/* RIGHT: mission-control compass */}
        <div className="relative">
          <div className="relative flex justify-center">
            <div className="absolute -inset-12 bg-gradient-to-br from-primary/15 via-transparent to-transparent blur-3xl pointer-events-none" aria-hidden="true" />
            <div className="relative w-full max-w-[480px] aspect-square">
              {/* corner crosshair marks */}
              <span className="absolute top-0 left-0 h-3 w-3 border-t border-l border-primary/60 z-10" aria-hidden="true" />
              <span className="absolute top-0 right-0 h-3 w-3 border-t border-r border-primary/60 z-10" aria-hidden="true" />
              <span className="absolute bottom-0 left-0 h-3 w-3 border-b border-l border-primary/60 z-10" aria-hidden="true" />
              <span className="absolute bottom-0 right-0 h-3 w-3 border-b border-r border-primary/60 z-10" aria-hidden="true" />

              {/* compass */}
              <div className="absolute inset-0 flex items-center justify-center">
                <CompassLive size={480}/>
              </div>

              {/* rotating toast notifications */}
              <HeroToasts/>

              {/* central achievement flash */}
              <HeroAchievements/>
            </div>
          </div>
        </div>
      </div>

      {/* Live ticker — feels like the product is running */}
      <div className="mt-10 rounded-xl border border-border bg-card/70 backdrop-blur px-4 md:px-5 py-3 flex items-center gap-4">
        <span className="inline-flex items-center gap-2 text-[10px] font-semibold uppercase tracking-[0.18em] text-emerald-600 dark:text-emerald-400 whitespace-nowrap">
          <span className="live-dot h-1.5 w-1.5 rounded-full bg-emerald-500 inline-block" />
          лента событий
        </span>
        <span className="h-4 w-px bg-border" />
        <div className="flex-1 min-w-0">
          <HeroTickerLine />
        </div>
      </div>
    </div>

    {/* Dashboard hero — below compass, more room */}
    <div className="relative mx-auto max-w-7xl px-6 lg:px-10 pb-16 md:pb-20">
      <div className="flex items-baseline justify-between mb-3">
        <div className="text-[11px] font-medium uppercase tracking-[0.18em] text-muted-foreground">Как это выглядит в продукте</div>
        <a href="#features" className="text-[12px] text-primary hover:underline underline-offset-4 inline-flex items-center gap-1">
          смотреть все 8 экранов <I.ArrowRight size={12}/>
        </a>
      </div>
      <div className="relative">
        <HeroDashboardMock />
      </div>
    </div>

    {/* Integrations ticker strip */}
    <div className="relative border-t border-border bg-muted/40">
      <div className="mx-auto max-w-7xl px-6 lg:px-10 py-5 flex items-center gap-6">
        <span className="text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground whitespace-nowrap">
          Читает и пишет в
        </span>
        <div className="flex-1 min-w-0">
          <IntegrationsTicker />
        </div>
      </div>
    </div>
  </section>
);

// ----- PAINS -----
const PainCard = ({ title, body, size="lg", visual }) => {
  if (size === "sm") {
    return (
      <div className="rounded-lg border border-border bg-muted/30 p-4 transition-colors hover:border-primary/40">
        <div className="text-sm font-semibold">{title}</div>
        <p className="mt-1 text-[12.5px] text-muted-foreground leading-relaxed">{body}</p>
      </div>
    );
  }
  return (
    <div className="group relative rounded-xl border border-border bg-card transition-all hover:border-primary/40 hover:-translate-y-0.5 overflow-hidden">
      {/* Editorial illustration fills top band */}
      {visual && (
        <div className="relative h-[160px] overflow-hidden border-b border-border bg-gradient-to-br from-muted/40 via-muted/10 to-transparent">
          {/* subtle grid overlay */}
          <div className="absolute inset-0 opacity-[0.08]" style={{backgroundImage:"linear-gradient(to right, currentColor 1px, transparent 1px), linear-gradient(to bottom, currentColor 1px, transparent 1px)", backgroundSize:"16px 16px"}}/>
          <div className="absolute inset-0 flex items-center justify-center text-foreground">
            {visual}
          </div>
          <div className="absolute top-3 left-3 text-[9px] font-semibold uppercase tracking-[0.18em] text-muted-foreground/80">Симптом</div>
          <div className="absolute top-3 right-3 flex items-center gap-1.5 text-[9px] font-semibold uppercase tracking-[0.18em] text-rose-600/80 dark:text-rose-400/80">
            <span className="h-1.5 w-1.5 rounded-full bg-rose-500 inline-block live-dot"/>
            сейчас
          </div>
        </div>
      )}
      <div className="p-6">
        <div className="text-[15px] font-semibold">{title}</div>
        <p className="mt-2 text-[13.5px] text-muted-foreground leading-relaxed text-pretty">{body}</p>
      </div>
    </div>
  );
};

const PainsSection = () => (
  <section id="pains" aria-labelledby="pains-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.AlertTriangle}>Боли руководителя</Badge>
        <h2 id="pains-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>

      <Reveal className="mt-14 grid md:grid-cols-2 gap-4" stagger>
        <PainCard visual={<PainIcon.TiedControl/>} title="Контроль держится на вас"
          body="Пока вы занимаетесь дебиторкой лично — всё работает. Отвлеклись на сделку или уехали в командировку — отдел просел, и вы узнаёте об этом через месяц." />
        <PainCard visual={<PainIcon.Postfactum/>} title="Проблему видно постфактум"
          body="Срок оплаты, просроченная дебиторка, банкротства контрагентов, смена директора — всё это проявляется тогда, когда тушить уже поздно и дорого." />
        <PainCard visual={<PainIcon.HistoryGone/>} title="Уволился специалист — ушла история"
          body="История переговоров, договорённости по рассрочкам, компромат на неплательщиков живут в Outlook, WhatsApp и голове сотрудника. Уволился — и три месяца вы собираете пазл заново." />
        <PainCard visual={<PainIcon.TeamChaos/>} title="Не видно, что делает команда"
          body="Один клиент висит у трёх сотрудников, по другому — тишина неделю. У всех в отделе свои таблички, свои правила, свой язык." />
      </Reveal>

      <div className="mt-12 text-center text-[11px] font-medium uppercase tracking-[0.18em] text-muted-foreground">
        И то, что узнаёт только бухгалтерия
      </div>
      <Reveal className="mt-6 grid md:grid-cols-2 gap-3 max-w-4xl mx-auto" stagger>
        <PainCard size="sm" title="Ручная сверка съедает отдел"
          body="Сверки, разноска платежей, акты сверки — 30–40% времени отдела уходит в ручной труд." />
        <PainCard size="sm" title="Сейл отгружает должнику"
          body="В 1С нет стоп-светофора — или он есть, но его никто не смотрит. Отгрузка идёт клиенту, про которого служба безопасности уже знает." />
      </Reveal>
    </div>
  </section>
);

// ----- VALUES -----
const ValueCard = ({ num, title, body, mech, icon }) => (
  <div className="group relative flex flex-col rounded-xl border border-border bg-card p-6 h-full transition-all hover:border-primary/40 hover:-translate-y-0.5 overflow-hidden">
    <div className="absolute -top-8 -right-8 h-24 w-24 rounded-full bg-primary/5 opacity-0 group-hover:opacity-100 transition-opacity duration-500" aria-hidden="true" />
    <div className="flex items-start justify-between gap-3">
      <div className="val-num font-display text-[44px] leading-none tabular font-semibold text-primary tracking-tighter">{num}</div>
      {icon && <div className="opacity-90">{icon}</div>}
    </div>
    <div className="mt-5 text-[17px] font-semibold leading-snug text-balance">{title}</div>
    <p className="mt-2 text-[13.5px] text-muted-foreground leading-relaxed text-pretty">{body}</p>
    <div className="mt-5 pt-4 border-t border-border">
      <div className="text-[10px] font-medium uppercase tracking-[0.16em] text-muted-foreground">Механика</div>
      <div className="mt-2 text-[12.5px] leading-relaxed">{mech}</div>
    </div>
  </div>
);

const ValuesSection = () => (
  <section id="values" aria-labelledby="values-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.Sparkles}>Что получает руководитель</Badge>
        <h2 id="values-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">
          Каждая ценность подкреплена механикой — конкретным модулем или интеграцией. Без обещаний чуда.
        </p>
      </div>

      <Reveal className="mt-14 grid md:grid-cols-2 lg:grid-cols-3 gap-4" stagger>
        <ValueCard num="01" icon={<ValueIcon.Shield247/>} title="Контроль 24/7 без вашего участия"
          body="Правила работают, пока вы в отпуске, в командировке или на совещании."
          mech="Триггеры в 1С + ЕФРСБ + банк + арбитраж + Контур.Фокус. Действие — стоп проводки, претензия, эскалация, алерт." />
        <ValueCard num="02" icon={<ValueIcon.Digest/>} title="Пять минут утром вместо часа"
          body="Компас собирает всё важное сам — вам остаётся прочитать одну сводку и принять 5 решений."
          mech="Панель руководителя + утренняя сводка в PDF или в почту в 8:30." />
        <ValueCard num="03" icon={<ValueIcon.TeamChart/>} title="Отдел в 2–3 раза эффективнее без роста ФОТ"
          body="Те же люди делают больше. Освобождённое время уходит на работу с живыми клиентами."
          mech="Автосверка (−14 ч/мес бухгалтера), претензия за минуты вместо часов, скоринг (−27 мин на контрагента)." />
        <ValueCard num="04" icon={<ValueIcon.Dossier/>} title="Компания не в заложниках у одного сотрудника"
          body="Болезнь, отпуск, увольнение специалиста — работа не встаёт. Новый сотрудник видит всю историю за секунды."
          mech="Карточка должника: переговоры, решения, документы, переписка, аудит — всё внутри Компаса, не в Outlook." />
        <ValueCard num="05" icon={<ValueIcon.Calendar28/>} title="Работает через 2–8 недель, не через полгода"
          body="Компас читает типовую 1С как есть и не требует доработки конфигурации."
          mech="Для стандартных (УТ, Бухгалтерия, УНФ, ERP) — 2 недели. Для кастомных — до 8 недель с индивидуальным маппингом." />
        {/* 6th tile — a discreet signature filler */}
        <div className="hidden lg:flex relative rounded-xl border border-dashed border-border p-6 items-end">
          <div className="text-[11px] font-medium uppercase tracking-[0.18em] text-muted-foreground">
            Шесть? <br/>Пяти достаточно.
          </div>
          <div className="absolute top-6 right-6 monogram text-primary text-2xl">
            <span className="mono-spin inline-block">К.</span>
          </div>
        </div>
      </Reveal>
    </div>
  </section>
);

Object.assign(window, { HeroSection, PainsSection, ValuesSection });
