// Hero — functional wow-effect: "Ascension Index"
// A live ticker/arrow that both animates (brush arrow ascending) AND surfaces useful info:
// - 5 city live clocks rotating
// - scroll-driven arrow growth
// - marquee of service keywords in 4 scripts (Latin/Cyrillic/Armenian/Arabic) as a multilingual signal

function useRotatingIndex(list, interval = 2400) {
  const [i, setI] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setI(v => (v + 1) % list.length), interval);
    return () => clearInterval(id);
  }, [list.length, interval]);
  return i;
}

function useClock(tz) {
  const [now, setNow] = React.useState(() => new Date());
  React.useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  try {
    const t = new Intl.DateTimeFormat('en-GB', {
      hour: '2-digit', minute: '2-digit', second: '2-digit',
      hour12: false, timeZone: tz
    }).format(now);
    return t;
  } catch (e) { return '--:--:--'; }
}

function CityTick({ cities }) {
  const idx = useRotatingIndex(cities, 2600);
  const city = cities[idx];
  const t = useClock(city.tz);
  return (
    <div className="city-tick" aria-live="polite">
      <span className="city-dot" />
      <span className="city-name">{city.c}</span>
      <span className="city-time">{t}</span>
      <span className="city-role">{city.r}</span>
    </div>
  );
}

function AscensionArrow({ progress }) {
  // progress 0..1 drives how high the red brush arrow has ascended
  // The arrow is drawn as a vertical brush stroke ending in an upward arrowhead.
  const lift = 180 * progress; // px
  return (
    <div className="ascension" aria-hidden="true">
      <svg viewBox="0 0 200 420" width="100%" height="100%" preserveAspectRatio="none">
        <defs>
          <filter id="asc-rough">
            <feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="3" />
            <feDisplacementMap in="SourceGraphic" scale="1.8" />
          </filter>
          <linearGradient id="asc-grad" x1="0" x2="0" y1="1" y2="0">
            <stop offset="0%" stopColor="#B30E1F" />
            <stop offset="60%" stopColor="#E8192C" />
            <stop offset="100%" stopColor="#FF3344" />
          </linearGradient>
        </defs>
        {/* Baseline guides */}
        <g stroke="rgba(10,10,11,0.08)" strokeDasharray="2 6">
          <line x1="0" y1="80" x2="200" y2="80" />
          <line x1="0" y1="160" x2="200" y2="160" />
          <line x1="0" y1="240" x2="200" y2="240" />
          <line x1="0" y1="320" x2="200" y2="320" />
        </g>
        <g filter="url(#asc-rough)" style={{ transform: `translateY(${-lift}px)`, transition: 'transform 0.25s cubic-bezier(.2,.8,.2,1)' }}>
          {/* Unified brush arrow — shaft + head in one path, no gaps */}
          <path
            d="M80 410 C 70 360, 90 300, 78 240 C 66 180, 100 130, 92 90 L 60 90 L 105 30 L 150 90 L 128 90 C 120 130, 142 180, 132 240 C 122 300, 138 360, 128 410 Z"
            fill="url(#asc-grad)"
          />
          {/* splatter */}
          <circle cx="160" cy="40" r="3" fill="#E8192C" />
          <circle cx="52" cy="55" r="2" fill="#E8192C" />
          <circle cx="170" cy="70" r="1.6" fill="#E8192C" />
        </g>
      </svg>
    </div>
  );
}

function Hero({ t, lang }) {
  const [progress, setProgress] = React.useState(0.2);
  const visualRef = React.useRef(null);

  React.useEffect(() => {
    function onScroll() {
      const h = window.innerHeight;
      const p = Math.min(1, Math.max(0, window.scrollY / (h * 0.9)));
      setProgress(0.15 + p * 0.85);
      if (visualRef.current) {
        visualRef.current.style.setProperty('--parallax', `${-window.scrollY * 0.12}px`);
      }
    }
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Multi-script marquee — signals multilingual capability as part of the wow
  const marquee = [
    'Brand', 'Бренд', 'ブランド', 'علامة', 'Ապրանքանիշ',
    'Product', 'Продукт', 'منتج', 'Ապրանք',
    'AI Agents', 'AI-агенты', 'وكلاء ذكيون',
    'Growth', 'Рост', 'نمو', 'Աճ',
    'Identity', 'Айдентика', 'هوية',
    'Performance', 'Перформанс', 'أداء'
  ];

  return (
    <section className="hero" data-screen-label="01 Hero">
      <div className="hero-grid">
        <div className="hero-copy">
          <div className="eyebrow">
            <LiveDot /> {t.hero.eyebrow}
          </div>

          <h1 className="hero-title">
            <span className="hero-title-line">
              <SplitReveal text={t.hero.title_a} />
            </span>
            <span className="hero-title-accent">
              <BrushUnderline>{t.hero.title_b}</BrushUnderline>
            </span>
            <span className="hero-title-sub">{t.hero.title_c}</span>
          </h1>

          <p className="hero-sub">{t.hero.sub}</p>

          <div className="hero-actions">
            <a className="btn btn-primary" href={WA_LINK(lang)} target="_blank" rel="noopener noreferrer">
              {t.cta.discuss}
              <ArrowUpRight />
            </a>
            <a className="btn btn-ghost" href="#services">
              {t.nav.services}
            </a>
          </div>
        </div>

        <div className="hero-visual" ref={visualRef}>
          <AscensionArrow progress={progress} />
          <div className="ascension-meta">
            <div className="ascension-label">
              <LiveDot /> {t.hero.index}
            </div>
            <div className="ascension-value">+{Math.round(progress * 100)}<span>%</span></div>
            <div className="ascension-bar">
              <div className="ascension-bar-fill" style={{ height: `${progress * 100}%` }} />
            </div>
          </div>
        </div>
      </div>

      <div className="hero-foot">
        <CityTick cities={t.presence.cities} />
        <div className="scroll-hint">
          <span>{t.hero.scroll}</span>
          <span className="scroll-hint-line" />
        </div>
      </div>

      <div className="hero-marquee" aria-hidden="true">
        <div className="hero-marquee-track">
          {[...marquee, ...marquee].map((w, i) => (
            <span key={i} className="hero-marquee-item">
              {w}<span className="hero-marquee-dot">✦</span>
            </span>
          ))}
        </div>
      </div>
    </section>
  );
}

function SplitReveal({ text, delay = 0 }) {
  const ref = React.useRef(null);
  // Start visible; only hide if element is below the fold at mount (so scroll-down triggers reveal).
  const [visible, setVisible] = React.useState(true);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    if (r.top >= window.innerHeight) {
      setVisible(false);
      const io = new IntersectionObserver(entries => {
        entries.forEach(e => { if (e.isIntersecting) { setVisible(true); io.disconnect(); } });
      }, { threshold: 0, rootMargin: '0px 0px -10% 0px' });
      io.observe(el);
      return () => io.disconnect();
    }
  }, []);
  const words = text.split(' ');
  return (
    <span ref={ref} className={`split-reveal ${visible ? 'is-in' : ''}`}>
      {words.map((w, i) => (
        <React.Fragment key={i}>
          <span className="sr-word">
            <span
              className="sr-inner"
              style={{
                transitionDelay: `${delay + i * 60}ms`,
                transform: visible ? 'translateY(0)' : 'translateY(110%)'
              }}
            >{w}</span>
          </span>
          {i < words.length - 1 ? ' ' : null}
        </React.Fragment>
      ))}
    </span>
  );
}

function BrushUnderline({ children }) {
  return (
    <span className="brush-underline">
      <span className="brush-underline-text">{children}</span>
      <svg className="brush-underline-svg" viewBox="0 0 400 60" preserveAspectRatio="none">
        <defs>
          <filter id="bu-rough">
            <feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2" seed="5" />
            <feDisplacementMap in="SourceGraphic" scale="1.6" />
          </filter>
        </defs>
        <path
          filter="url(#bu-rough)"
          d="M4 30 C 60 14, 200 12, 396 24 L 394 48 C 200 42, 60 46, 6 52 Z"
          fill="#E8192C"
        />
      </svg>
    </span>
  );
}

function ArrowUpRight() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path d="M4 12 L 12 4 M 6 4 L 12 4 L 12 10" stroke="currentColor" strokeWidth="1.8" strokeLinecap="square" />
    </svg>
  );
}

const WA_LINK = (lang) => {
  const msg = lang === 'ru'
    ? 'Здравствуйте, я хочу обсудить проект'
    : 'Hello, I would like to discuss a project';
  return `https://api.whatsapp.com/send?phone=+37444638868&text=${encodeURIComponent(msg)}`;
};

function LiveDot() {
  return <span className="live-dot" aria-hidden="true" />;
}

Object.assign(window, { Hero, SplitReveal, BrushUnderline, ArrowUpRight, WA_LINK, CityTick, useClock, LiveDot });
