"use client";

import { useRef } from "react";
import { motion, useReducedMotion, useScroll, useTransform, type MotionValue } from "motion/react";

const STATEMENT = "Syria holds some of the oldest cities on earth, still alive with markets, music and meals.";
const HIGHLIGHT = new Set(["oldest", "cities", "alive"]);

function Word({ word, range, progress, hl }: { word: string; range: [number, number]; progress: MotionValue<number>; hl: boolean }) {
  const opacity = useTransform(progress, range, [0.16, 1]);
  return (
    <motion.span className={`w${hl ? " hl" : ""}`} style={{ opacity }}>
      {word}
    </motion.span>
  );
}

export default function Intro() {
  const reduce = useReducedMotion();
  const ref = useRef<HTMLHeadingElement>(null);
  const { scrollYProgress } = useScroll({ target: ref, offset: ["start 0.85", "end 0.5"] });
  const words = STATEMENT.split(" ");

  return (
    <section className="intro" id="intro">
      <div className="wrap">
        <h2 className="statement" ref={ref} aria-label={STATEMENT}>
          {words.map((w, i) => {
            const start = i / words.length;
            const end = Math.min(start + 1.6 / words.length, 1);
            const clean = w.replace(/[^a-z]/gi, "").toLowerCase();
            return reduce ? (
              <span key={i} className={`w${HIGHLIGHT.has(clean) ? " hl" : ""}`} aria-hidden="true">{w}</span>
            ) : (
              <Word key={i} word={w} range={[start, end]} progress={scrollYProgress} hl={HIGHLIGHT.has(clean)} />
            );
          })}
        </h2>
      </div>
    </section>
  );
}
