import { motion, useReducedMotion } from "framer-motion";

interface Line { text: string; cls?: string }

// Per-character kinetic headline. Words are atomic (chars never break inside a
// word) but lines wrap naturally between words; an optional ember period is
// fused to the final word so it can never orphan onto its own line.
export default function CharHeadline({ lines, className = "", delay = 0, emberPeriod = false }: { lines: Line[]; className?: string; delay?: number; emberPeriod?: boolean }) {
  const reduce = useReducedMotion();
  let idx = 0;

  return (
    <h1 className={className} data-testid="hero-headline">
      {lines.map((ln, li) => {
        const raw = ln.text;
        const hasPeriod = emberPeriod && li === lines.length - 1 && raw.trimEnd().endsWith(".");
        const body = hasPeriod ? raw.trimEnd().slice(0, -1) : raw;
        const words = body.split(" ");
        return (
          <span key={li} className="block overflow-hidden pb-[0.07em] -mb-[0.07em]">
            <span className="inline">
              {words.map((word, wi) => {
                const isLastWord = wi === words.length - 1;
                const chars = (isLastWord && hasPeriod ? `${word}.` : word).split("");
                return (
                  <span key={wi} className="inline-flex whitespace-nowrap" style={{ marginRight: isLastWord ? 0 : "0.24em" }}>
                    {chars.map((ch, ci) => {
                      const isEmberPeriod = hasPeriod && isLastWord && ci === chars.length - 1;
                      const d = delay + idx++ * 0.028;
                      const cls = `inline-block ${isEmberPeriod ? "text-ember" : ln.cls || ""}`;
                      return reduce ? (
                        <span key={ci} className={cls}>{ch}</span>
                      ) : (
                        <motion.span
                          key={ci}
                          className={cls}
                          initial={{ y: "115%", rotate: 5, opacity: 0 }}
                          animate={{ y: "0%", rotate: 0, opacity: 1 }}
                          transition={{ duration: 0.8, delay: d, ease: [0.22, 1, 0.36, 1] }}
                        >
                          {ch}
                        </motion.span>
                      );
                    })}
                  </span>
                );
              })}
            </span>
          </span>
        );
      })}
    </h1>
  );
}
