// Payment AI — wide hero animation (2400x900, 28s loop)
// Style: flat, smooth ease-in-out, no bouncy physics. Single accent: brand green.

const HA = {
  bg:        '#07090f',
  bgSoft:    '#0c1220',
  ink:       '#f4f6fb',
  inkMute:   'rgba(244,246,251,0.62)',
  inkDim:    'rgba(244,246,251,0.36)',
  rule:      'rgba(244,246,251,0.10)',
  accent:    '#1ab877',
  accentSoft:'rgba(26,184,119,0.14)',
  accentDeep:'#0e6b46',
  font:      "'Inter', system-ui, -apple-system, sans-serif",
  mono:      "'JetBrains Mono', ui-monospace, monospace",
};

const HERO_W = 2400;
const HERO_H = 900;
const CX = HERO_W / 2;
const CY = HERO_H / 2;

// Soft easing — no overshoot
const eOut = Easing.easeOutCubic;
const eInOut = Easing.easeInOutCubic;

// Flat brand mark — no gradient, just solid green tile
function HeroLogo({ size = 64, radius = 14 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: radius,
      background: HA.accent,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: '#04140d', fontFamily: HA.font, fontWeight: 700,
      fontSize: size * 0.5, letterSpacing: '-0.04em',
    }}>P</div>
  );
}

// ── Flat SVG icons (clean line/fill) ───────────────────────────────────────
const Icons = {
  bolt: (color) => (
    <svg viewBox="0 0 64 64" width="100%" height="100%" fill="none">
      <path d="M36 6 L14 36 L30 36 L26 58 L50 28 L34 28 Z"
        fill={color} stroke={color} strokeWidth="2" strokeLinejoin="round"/>
    </svg>
  ),
  lock: (color) => (
    <svg viewBox="0 0 64 64" width="100%" height="100%" fill="none">
      <rect x="12" y="28" width="40" height="28" rx="4" stroke={color} strokeWidth="3"/>
      <path d="M20 28 V20 a12 12 0 0 1 24 0 v8" stroke={color} strokeWidth="3" strokeLinecap="round"/>
      <circle cx="32" cy="42" r="3" fill={color}/>
    </svg>
  ),
  wallet: (color) => (
    <svg viewBox="0 0 64 64" width="100%" height="100%" fill="none">
      <rect x="8" y="16" width="48" height="36" rx="5" stroke={color} strokeWidth="3"/>
      <path d="M8 26 H46 a4 4 0 0 1 4 4 v8 a4 4 0 0 1 -4 4 H8 Z" fill={color} fillOpacity="0.12" stroke={color} strokeWidth="3"/>
      <circle cx="44" cy="34" r="3" fill={color}/>
    </svg>
  ),
  chat: (color) => (
    <svg viewBox="0 0 64 64" width="100%" height="100%" fill="none">
      <path d="M10 14 h44 a4 4 0 0 1 4 4 v24 a4 4 0 0 1 -4 4 H26 L14 56 V46 H10 a4 4 0 0 1 -4 -4 V18 a4 4 0 0 1 4 -4 Z"
        stroke={color} strokeWidth="3" strokeLinejoin="round"/>
      <circle cx="22" cy="30" r="2.5" fill={color}/>
      <circle cx="32" cy="30" r="2.5" fill={color}/>
      <circle cx="42" cy="30" r="2.5" fill={color}/>
    </svg>
  ),
};

// ── Decorative wide background (very subtle, slow drift) ───────────────────
function HeroBackdrop() {
  const t = useTime();
  // Slow horizontal drift on a faint dot grid + a soft accent glow
  const drift = t * 18;
  return (
    <>
      {/* dot grid */}
      <div style={{
        position: 'absolute', inset: -60,
        backgroundImage: `radial-gradient(${HA.rule} 1.4px, transparent 1.6px)`,
        backgroundSize: '54px 54px',
        backgroundPosition: `${drift}px ${-drift / 3}px`,
        opacity: 0.55,
        maskImage: 'radial-gradient(ellipse 70% 70% at center, #000 30%, transparent 85%)',
        WebkitMaskImage: 'radial-gradient(ellipse 70% 70% at center, #000 30%, transparent 85%)',
      }}/>
      {/* hairline rules */}
      <div style={{
        position: 'absolute', left: 0, right: 0, top: 120,
        height: 1, background: HA.rule,
      }}/>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 120,
        height: 1, background: HA.rule,
      }}/>
    </>
  );
}

// ── Scene 1 — Logo + hook (0..3.5s) ────────────────────────────────────────
function HeroIntro() {
  const { localTime, duration } = useSprite();

  const eLogo = eOut(clamp(localTime / 0.55, 0, 1));
  const eName = eOut(clamp((localTime - 0.18) / 0.55, 0, 1));
  const eHook = eOut(clamp((localTime - 0.7) / 0.6, 0, 1));
  const exitT = clamp((localTime - (duration - 0.5)) / 0.5, 0, 1);
  const exitOp = 1 - eInOut(exitT);

  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexDirection: 'column', gap: 36,
      fontFamily: HA.font, opacity: exitOp,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 28,
        opacity: eLogo,
        transform: `translateY(${(1 - eLogo) * 16}px)`,
      }}>
        <div style={{ opacity: eLogo, transform: `scale(${0.85 + eLogo * 0.15})` }}>
          <HeroLogo size={120} radius={26} />
        </div>
        <div style={{
          opacity: eName,
          transform: `translateX(${(1 - eName) * 18}px)`,
          fontSize: 168, fontWeight: 600, color: HA.ink,
          letterSpacing: '-0.04em', lineHeight: 1,
        }}>
          Payment <span style={{ color: HA.accent }}>ai</span>
        </div>
      </div>

      <div style={{
        opacity: eHook,
        transform: `translateY(${(1 - eHook) * 14}px)`,
        fontSize: 44, color: HA.inkMute, fontWeight: 400,
        letterSpacing: '-0.01em',
        textAlign: 'center',
      }}>
        Все цифровые товары в одном месте
      </div>
    </div>
  );
}

// ── Reusable benefit panel ─────────────────────────────────────────────────
function Benefit({ icon, label, headline, description, footnote }) {
  const { localTime, duration } = useSprite();

  // 200ms slide-up + fade-in for label, icon pops 150ms earlier
  const eIcon = eOut(clamp((localTime - 0.05) / 0.45, 0, 1));
  const eLabel = eOut(clamp((localTime - 0.20) / 0.40, 0, 1));
  const eHead = eOut(clamp((localTime - 0.45) / 0.55, 0, 1));
  const eDesc = eOut(clamp((localTime - 0.75) / 0.55, 0, 1));
  const eFoot = eOut(clamp((localTime - 1.05) / 0.55, 0, 1));

  const exitT = clamp((localTime - (duration - 0.45)) / 0.45, 0, 1);
  const exitOp = 1 - eInOut(exitT);
  const exitDx = -exitT * 30;

  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      gap: 80,
      fontFamily: HA.font,
      opacity: exitOp,
      transform: `translateX(${exitDx}px)`,
    }}>
      {/* Icon panel */}
      <div style={{
        width: 280, height: 280, borderRadius: 36,
        background: HA.accentSoft,
        border: `1.5px solid ${HA.accent}33`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        opacity: eIcon,
        transform: `translateY(${(1 - eIcon) * 24}px) scale(${0.9 + eIcon * 0.1})`,
      }}>
        <div style={{ width: 130, height: 130 }}>{icon(HA.accent)}</div>
      </div>

      {/* Text */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 980 }}>
        <div style={{
          opacity: eLabel,
          transform: `translateY(${(1 - eLabel) * 14}px)`,
          fontFamily: HA.mono,
          fontSize: 22, color: HA.accent,
          letterSpacing: '0.18em', textTransform: 'uppercase',
        }}>{label}</div>

        <div style={{
          opacity: eHead,
          transform: `translateY(${(1 - eHead) * 18}px)`,
          fontSize: 116, fontWeight: 600, color: HA.ink,
          letterSpacing: '-0.035em', lineHeight: 1.0,
        }}>{headline}</div>

        <div style={{
          opacity: eDesc,
          transform: `translateY(${(1 - eDesc) * 14}px)`,
          fontSize: 36, color: HA.inkMute, lineHeight: 1.3,
          fontWeight: 400, maxWidth: 900,
        }}>{description}</div>

        {footnote && (
          <div style={{
            marginTop: 8,
            opacity: eFoot,
            transform: `translateY(${(1 - eFoot) * 10}px)`,
            display: 'flex', alignItems: 'center', gap: 14,
          }}>
            <div style={{
              width: 10, height: 10, borderRadius: 5, background: HA.accent,
            }}/>
            <div style={{ fontSize: 24, color: HA.inkDim, fontFamily: HA.mono }}>
              {footnote}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Scene 5 — summary + CTA (20..27.5s) ────────────────────────────────────
function SummaryScene() {
  const { localTime, duration } = useSprite();

  const eHead = eOut(clamp(localTime / 0.6, 0, 1));
  const benefits = [
    { icon: Icons.bolt,   label: 'Быстро',     desc: 'Подключение за 2 минуты' },
    { icon: Icons.lock,   label: 'Безопасно',  desc: 'Прозрачные условия' },
    { icon: Icons.wallet, label: 'Выгодно',    desc: 'Единая оплата, лучшие цены' },
    { icon: Icons.chat,   label: 'Поддержка',  desc: '24/7 в Telegram' },
  ];

  const eCta = eOut(clamp((localTime - 1.7) / 0.55, 0, 1));
  // CTA pulse — 1.5s loop, soft sine
  const pulseT = (localTime % 1.5) / 1.5;
  const pulse = 0.5 + 0.5 * Math.sin(pulseT * Math.PI * 2);

  const exitT = clamp((localTime - (duration - 0.6)) / 0.6, 0, 1);
  const exitOp = 1 - eInOut(exitT);

  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      justifyContent: 'center', gap: 60,
      fontFamily: HA.font, opacity: exitOp,
    }}>
      {/* Headline */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 22,
        opacity: eHead, transform: `translateY(${(1 - eHead) * 16}px)`,
      }}>
        <HeroLogo size={84} radius={18} />
        <div style={{
          fontSize: 124, fontWeight: 600, color: HA.ink,
          letterSpacing: '-0.04em', lineHeight: 1,
        }}>Payment <span style={{ color: HA.accent }}>ai</span></div>
      </div>

      {/* Benefit row */}
      <div style={{ display: 'flex', gap: 56 }}>
        {benefits.map((b, i) => {
          const e = eOut(clamp((localTime - 0.45 - i * 0.18) / 0.55, 0, 1));
          return (
            <div key={i} style={{
              width: 320,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18,
              opacity: e, transform: `translateY(${(1 - e) * 18}px)`,
            }}>
              <div style={{
                width: 96, height: 96, borderRadius: 22,
                background: HA.accentSoft,
                border: `1.5px solid ${HA.accent}33`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <div style={{ width: 48, height: 48 }}>{b.icon(HA.accent)}</div>
              </div>
              <div style={{ fontSize: 32, fontWeight: 600, color: HA.ink, letterSpacing: '-0.01em' }}>
                {b.label}
              </div>
              <div style={{ fontSize: 22, color: HA.inkMute, textAlign: 'center', maxWidth: 280, lineHeight: 1.35 }}>
                {b.desc}
              </div>
            </div>
          );
        })}
      </div>

      {/* CTA */}
      <div style={{
        opacity: eCta,
        transform: `translateY(${(1 - eCta) * 14}px)`,
        position: 'relative',
      }}>
        {/* Glow halo */}
        <div style={{
          position: 'absolute', inset: -22,
          borderRadius: 22,
          boxShadow: `0 0 ${30 + pulse * 40}px ${4 + pulse * 12}px ${HA.accent}55`,
          opacity: 0.6 + pulse * 0.4,
          pointerEvents: 'none',
        }}/>
        <div style={{
          position: 'relative',
          padding: '26px 56px',
          background: HA.accent,
          color: '#04140d',
          borderRadius: 18,
          fontSize: 36, fontWeight: 600,
          letterSpacing: '-0.01em',
          display: 'flex', alignItems: 'center', gap: 16,
          transform: `scale(${1 + pulse * 0.012})`,
        }}>
          Открыть каталог <span style={{ fontSize: 36 }}>→</span>
        </div>
      </div>
    </div>
  );
}

// ── Loop bridge — 27.5..28s — fades to brand color before restart ──────────
function LoopBridge() {
  const { localTime, duration } = useSprite();
  const e = eInOut(clamp(localTime / duration, 0, 1));
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: HA.bg,
      opacity: e,
      pointerEvents: 'none',
    }}/>
  );
}

// ── Section indicator (top hairline progress) ──────────────────────────────
function SectionRail() {
  const t = useTime();
  // Show during benefits + summary (2.8..27)
  const visible = t > 2.8 && t < 26.8;
  const e = eOut(clamp((t - 2.8) / 0.5, 0, 1)) * (1 - eOut(clamp((t - 26.3) / 0.5, 0, 1)));

  // 4 segments mapped to scene timing
  const segments = [
    { label: 'Быстро',    s: 3.5,  e: 8.0 },
    { label: 'Безопасно', s: 8.0,  e: 13.0 },
    { label: 'Выгодно',   s: 13.0, e: 18.0 },
    { label: 'Итого',     s: 18.0, e: 27.0 },
  ];

  if (!visible) return null;
  return (
    <div style={{
      position: 'absolute', top: 64,
      left: '50%', transform: 'translateX(-50%)',
      display: 'flex', gap: 24, alignItems: 'center',
      opacity: e,
      fontFamily: HA.mono,
    }}>
      {segments.map((seg, i) => {
        const active = t >= seg.s && t <= seg.e;
        const done = t > seg.e;
        const w = 110;
        const fill = active ? clamp((t - seg.s) / (seg.e - seg.s), 0, 1) : (done ? 1 : 0);
        return (
          <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'center' }}>
            <div style={{
              fontSize: 14, letterSpacing: '0.18em', textTransform: 'uppercase',
              color: active ? HA.accent : (done ? HA.inkDim : HA.inkDim),
              transition: 'color 200ms',
            }}>{seg.label}</div>
            <div style={{ width: w, height: 2, background: HA.rule, borderRadius: 1, position: 'relative' }}>
              <div style={{
                position: 'absolute', left: 0, top: 0, bottom: 0,
                width: `${fill * 100}%`,
                background: HA.accent,
              }}/>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ── Bottom corner mark ─────────────────────────────────────────────────────
function CornerStamp() {
  const t = useTime();
  const e = eOut(clamp((t - 0.6) / 0.6, 0, 1));
  // hide during the very last fade
  const fadeOut = 1 - eInOut(clamp((t - 27.4) / 0.5, 0, 1));
  return (
    <div style={{
      position: 'absolute', right: 64, bottom: 64,
      display: 'flex', alignItems: 'center', gap: 12,
      opacity: e * fadeOut,
      fontFamily: HA.mono, fontSize: 18,
      color: HA.inkDim, letterSpacing: '0.14em', textTransform: 'uppercase',
    }}>
      <div style={{ width: 8, height: 8, borderRadius: 4, background: HA.accent }}/>
      payment.ai
    </div>
  );
}

// ── Root ───────────────────────────────────────────────────────────────────
function HeroVideo() {
  const t = useTime();

  React.useEffect(() => {
    const root = document.querySelector('[data-screen-label]');
    if (root) {
      const sec = Math.floor(t);
      const nxt = `t=${sec}s`;
      if (root.getAttribute('data-screen-label') !== nxt) {
        root.setAttribute('data-screen-label', nxt);
      }
    }
  }, [Math.floor(t)]);

  return (
    <div data-screen-label="t=0s" style={{
      position: 'absolute', inset: 0,
      background: HA.bg, overflow: 'hidden',
    }}>
      <HeroBackdrop />

      {/* Scene 1 — 0..3.5s — logo + hook */}
      <Sprite start={0} end={3.5}>
        <HeroIntro />
      </Sprite>

      {/* Benefits */}
      <Sprite start={3.5} end={8.05}>
        <Benefit
          icon={Icons.bolt}
          label="01 — Быстро"
          headline="2 минуты до доступа"
          description="Оформление в один клик. Ключ и инструкции приходят сразу в Telegram."
          footnote="без регистрации, без ожидания"
        />
      </Sprite>

      <Sprite start={8.0} end={13.05}>
        <Benefit
          icon={Icons.lock}
          label="02 — Безопасно"
          headline="Прозрачные условия"
          description="Только официальные сервисы. Чек, гарантия возврата и поддержка по каждому заказу."
          footnote="8 742+ успешных оформлений"
        />
      </Sprite>

      <Sprite start={13.0} end={18.05}>
        <Benefit
          icon={Icons.wallet}
          label="03 — Выгодно"
          headline="Единая оплата"
          description="ChatGPT, Claude, Grok, Suno, Cursor, Gemini и другие — по лучшим ценам в одном кабинете."
          footnote="от 1 390 ₽ за подписку"
        />
      </Sprite>

      {/* Summary + CTA */}
      <Sprite start={18.0} end={27.5}>
        <SummaryScene />
      </Sprite>

      {/* Final fade for clean loop */}
      <Sprite start={27.4} end={28.0}>
        <LoopBridge />
      </Sprite>

      {/* Persistent UI */}
      <SectionRail />
      <CornerStamp />
    </div>
  );
}

Object.assign(window, {
  HA, HeroLogo, Icons, HeroBackdrop,
  HeroIntro, Benefit, SummaryScene, LoopBridge,
  SectionRail, CornerStamp, HeroVideo,
  HERO_W, HERO_H,
});
