// @design-system: layout/HeroSection/ManifestoHero
// Registered at /design-system#manifestohero-layout

'use client';

import { useEffect, useRef } from 'react';
import { cn } from '@/lib/cn';
import { useT, useLocale } from '@/lib/i18n/react';
import { formatInteger } from '@/lib/format';

/** Props for ManifestoHero */
export interface ManifestoHeroProps {
  /** Hero h1 title — pre-translated string; rendered alongside animated word rotator */
  title: string;
  /** Optional subtitle paragraph */
  subtitle?: string;
  /** Additional class names */
  className?: string;
}

/**
 * ManifestoHero — About page hero with kinetic word-swap headline.
 *
 * Headline cycles through animated words (buy / save / order / celebrate) with a suffix word.
 * Background: deep-navy radial gradient with slow breathing animation.
 * Stats counter animates on mount; replays every 8 s.
 * All animations off under prefers-reduced-motion.
 *
 * @example
 * ```tsx
 * <ManifestoHero title={t('manifesto_title')} />
 * ```
 */
export function ManifestoHero({ title, subtitle, className }: ManifestoHeroProps) {
  const t = useT('manifesto_hero');
  const { locale } = useLocale();
  const statsRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const container = statsRef.current;
    if (!container) return;

    const els = container.querySelectorAll<HTMLElement>('strong[data-to]');
    if (!els.length) return;

    const mql = window.matchMedia('(prefers-reduced-motion: reduce)');
    let interval: ReturnType<typeof setInterval> | null = null;
    const rafIds = new Set<number>();

    function setFinalValues() {
      els.forEach((el) => {
        const to = parseInt(el.getAttribute('data-to') ?? '0', 10);
        el.textContent = formatInteger(to, locale);
      });
    }

    function animateStat(el: HTMLElement) {
      const to = parseInt(el.getAttribute('data-to') ?? '0', 10);
      const dur = 1800;
      const start = performance.now();
      function frame(t: number) {
        if (mql.matches) {
          el.textContent = formatInteger(to, locale);
          return;
        }
        const p = Math.min(1, (t - start) / dur);
        const eased = 1 - Math.pow(1 - p, 3);
        el.textContent = formatInteger(Math.round(to * eased), locale);
        if (p < 1) {
          const id = requestAnimationFrame(frame);
          rafIds.add(id);
        }
      }
      const id = requestAnimationFrame(frame);
      rafIds.add(id);
    }

    function start() {
      els.forEach(animateStat);
      interval = setInterval(() => {
        els.forEach((s) => {
          s.textContent = '0';
          animateStat(s);
        });
      }, 8000);
    }

    function stop() {
      if (interval) {
        clearInterval(interval);
        interval = null;
      }
      rafIds.forEach((id) => cancelAnimationFrame(id));
      rafIds.clear();
      setFinalValues();
    }

    if (mql.matches) {
      setFinalValues();
    } else {
      start();
    }

    function onChange() {
      if (mql.matches) {
        stop();
      } else if (!interval) {
        start();
      }
    }

    mql.addEventListener('change', onChange);

    return () => {
      mql.removeEventListener('change', onChange);
      stop();
    };
  }, [locale]);

  return (
    <section className={cn('mdh-about-2', className)} dir="rtl">
      {/* Animated background gradient — decorative */}
      <div className="mdh-about-2__bg" aria-hidden="true" />

      <div className="mdh-about-2__inner">
        {/* Eyebrow */}
        <div className="mdh-about-2__eyebrow" aria-hidden="true">
          {t('eyebrow')}
        </div>

        {/* h1: static fixed word + animated word rotator */}
        <h1 className="mdh-about-2__title font-[var(--font-weight-extrabold)] text-[var(--font-size-display)]">
          <span className="fixed">{t('fixed_word')}</span>
          {/* Rotator is decorative — screen readers read the static title prop */}
          <span className="rotator" aria-hidden="true">
            <span className="w">{t('word_1')}</span>
            <span className="w">{t('word_2')}</span>
            <span className="w">{t('word_3')}</span>
            <span className="w">{t('word_4')}</span>
          </span>
          <span className="end fixed" aria-hidden="true">
            .
          </span>
          {/* Visually hidden accessible title */}
          <span className="sr-only">{title}</span>
        </h1>

        {/* Subtitle */}
        {subtitle ? (
          <p className="mdh-about-2__sub">{subtitle}</p>
        ) : (
          <p className="mdh-about-2__sub">{t('default_subtitle')}</p>
        )}

        {/* Stats */}
        <div className="mdh-about-2__stats" ref={statsRef} aria-hidden="true">
          <div className="stat">
            <strong data-to="142">0</strong>
            <span>{t('stat_1_label')}</span>
          </div>
          <div className="stat">
            <strong data-to="4800">0</strong>
            <span>{t('stat_2_label')}</span>
          </div>
          <div className="stat">
            <strong data-to="28">0</strong>
            <span>{t('stat_3_label')}</span>
          </div>
        </div>
      </div>

      <style>{`
        .mdh-about-2 {
          position: relative;
          overflow: hidden;
          background: var(--color-brand-primary-950);
          color: var(--color-brand-on-primary);
          padding: 7rem var(--spacing-6);
          font-family: var(--font-heebo, "Heebo", system-ui, sans-serif);
        }

        .mdh-about-2__bg {
          position: absolute;
          inset: 0;
          pointer-events: none;
          background:
            radial-gradient(ellipse at 80% 20%, color-mix(in srgb, var(--color-brand-primary-500) 35%, transparent), transparent 55%),
            radial-gradient(ellipse at 10% 90%, color-mix(in srgb, var(--color-brand-primary-700) 45%, transparent), transparent 60%);
        }

        @media (prefers-reduced-motion: no-preference) {
          .mdh-about-2__bg {
            animation: mdhA2Bg 12s ease-in-out infinite alternate;
          }
        }

        @keyframes mdhA2Bg {
          0%   { transform: scale(1); }
          100% { transform: scale(1.15); }
        }

        .mdh-about-2__inner {
          position: relative;
          max-width: 56.25rem;
          margin: 0 auto;
          text-align: center;
        }

        .mdh-about-2__eyebrow {
          font-family: var(--font-inter, "Inter", sans-serif);
          font-size: var(--font-size-xs);
          font-weight: 700;
          letter-spacing: 0.18em;
          color: var(--color-brand-primary-300);
          text-transform: uppercase;
          margin-bottom: var(--spacing-6);
        }

        .mdh-about-2__title {
          font-size: clamp(3rem, 9vw, 5.375rem);
          font-weight: 700;
          letter-spacing: -0.035em;
          margin: 0 0 1.75rem;
          line-height: 1;
          direction: rtl;
          display: inline-flex;
          align-items: baseline;
          gap: 1.125rem;
          flex-wrap: wrap;
          justify-content: center;
        }

        .mdh-about-2__title .fixed {
          color: var(--color-brand-on-primary);
        }

        .mdh-about-2__title .end {
          margin-inline-start: calc(-1 * var(--spacing-3));
          color: var(--color-brand-primary-400);
        }

        .mdh-about-2__title .rotator {
          position: relative;
          display: inline-block;
          height: 1em;
          min-width: 4.5ch;
          overflow: hidden;
          vertical-align: baseline;
          color: var(--color-brand-primary-400);
        }

        .mdh-about-2__title .rotator .w {
          position: absolute;
          inset: 0;
          display: inline-block;
          opacity: 0;
          transform: translateY(100%);
          white-space: nowrap;
        }

        @media (prefers-reduced-motion: no-preference) {
          .mdh-about-2__title .rotator .w {
            animation: mdhA2Rot 8s cubic-bezier(.65,.01,.35,1) infinite;
          }
          .mdh-about-2__title .rotator .w:nth-child(1) { animation-delay: 0s; }
          .mdh-about-2__title .rotator .w:nth-child(2) { animation-delay: 2s; }
          .mdh-about-2__title .rotator .w:nth-child(3) { animation-delay: 4s; }
          .mdh-about-2__title .rotator .w:nth-child(4) { animation-delay: 6s; }
        }

        @media (prefers-reduced-motion: reduce) {
          .mdh-about-2__title .rotator .w:nth-child(1) {
            opacity: 1;
            transform: translateY(0);
          }
        }

        @keyframes mdhA2Rot {
          0%   { opacity: 0; transform: translateY(100%); }
          4%   { opacity: 1; transform: translateY(0); }
          22%  { opacity: 1; transform: translateY(0); }
          26%  { opacity: 0; transform: translateY(-100%); }
          100% { opacity: 0; transform: translateY(-100%); }
        }

        .mdh-about-2__sub {
          font-size: var(--font-size-lg);
          line-height: 1.65;
          color: color-mix(in srgb, var(--color-brand-primary-100) 75%, transparent);
          margin: 0 auto var(--spacing-10);
          max-width: 37.5rem;
        }

        .mdh-about-2__stats {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: var(--spacing-8);
          max-width: 40rem;
          margin: 0 auto;
          border-top: 1px solid color-mix(in srgb, var(--color-brand-primary-300) 18%, transparent);
          padding-top: var(--spacing-8);
        }

        .mdh-about-2__stats .stat {
          text-align: center;
        }

        .mdh-about-2__stats strong {
          display: block;
          font-family: var(--font-inter, "Inter", sans-serif);
          font-weight: 800;
          font-size: clamp(2.25rem, 5vw, 3rem);
          color: var(--color-brand-on-primary);
          letter-spacing: -0.02em;
          font-variant-numeric: tabular-nums;
        }

        .mdh-about-2__stats span {
          font-size: var(--font-size-sm);
          color: color-mix(in srgb, var(--color-brand-primary-200) 70%, transparent);
        }

        @media (max-width: 45rem) {
          .mdh-about-2__stats {
            grid-template-columns: 1fr;
            gap: 1.125rem;
          }
        }
      `}</style>
    </section>
  );
}
