"use client";

import { useEffect, useLayoutEffect, useRef, useState } from "react";

/**
 * Text that types itself out like a typewriter, with a blinking carriage
 * cursor, once it scrolls into view. The full sentence is laid out
 * invisibly underneath, so the page never jumps while it types. Screen
 * readers get the whole sentence at once, and visitors who ask for reduced
 * motion see it already typed.
 */
export default function TypewriterText({
  text,
  speedMs = 85,
  startDelayMs = 500,
  lineFeed = false,
  onDone
}: {
  text: string;
  speedMs?: number;
  startDelayMs?: number;
  /** Like a real typewriter: the line being typed stays at the bottom (by the
   *  roller) and the paper rolls up a line, with a carriage-return jolt,
   *  each time the typing moves to the next line. */
  lineFeed?: boolean;
  /** Called once the last letter is typed. */
  onDone?: () => void;
}) {
  const [shown, setShown] = useState(0);
  const [done, setDone] = useState(false);
  const ref = useRef<HTMLSpanElement>(null);
  const typedRef = useRef<HTMLSpanElement>(null);
  const lastHeight = useRef(0);
  const doneRef = useRef(onDone);
  doneRef.current = onDone;
  useEffect(() => {
    if (done) doneRef.current?.();
  }, [done]);

  // Next line: roll the paper up one line and jolt the carriage back.
  useLayoutEffect(() => {
    const el = typedRef.current;
    if (!lineFeed || !el) return;
    const h = el.getBoundingClientRect().height;
    if (lastHeight.current && h > lastHeight.current + 2) {
      el.classList.remove("tw-feed");
      void el.offsetWidth; // restart the animation
      el.classList.add("tw-feed");
    }
    lastHeight.current = h;
  }, [shown, lineFeed]);

  useEffect(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      setShown(text.length);
      setDone(true);
      return;
    }
    let timer: ReturnType<typeof setTimeout> | undefined;
    let i = 0;
    const tick = () => {
      i += 1;
      setShown(i);
      if (i >= text.length) {
        setDone(true);
        return;
      }
      // A slightly longer beat after punctuation, like a typist.
      const ch = text[i - 1];
      // Small human variation between keystrokes; a beat after punctuation.
      const jitter = speedMs * (0.7 + Math.random() * 0.6);
      timer = setTimeout(tick, /[.,;:]/.test(ch || "") ? speedMs * 5 : jitter);
    };
    const el = ref.current;
    const start = () => {
      timer = setTimeout(tick, startDelayMs);
    };
    if (!el || !("IntersectionObserver" in window)) {
      start();
      return () => clearTimeout(timer);
    }
    const io = new IntersectionObserver(
      (entries) => {
        if (entries.some((e) => e.isIntersecting)) {
          io.disconnect();
          start();
        }
      },
      { threshold: 0.4 }
    );
    io.observe(el);
    return () => {
      io.disconnect();
      clearTimeout(timer);
    };
  }, [text, speedMs, startDelayMs]);

  return (
    <span className={`typewriter${lineFeed ? " tw-linefeed" : ""}`} ref={ref}>
      <span className="sr-only">{text}</span>
      <span className="tw-ghost" aria-hidden="true">
        {text}
      </span>
      <span className="tw-typed" aria-hidden="true" ref={typedRef}>
        {text.slice(0, Math.max(0, shown - 1))}
        {/* The newest letter is "struck" onto the page. */}
        {shown > 0 && (
          <span className="tw-strike" key={shown}>
            {text[shown - 1]}
          </span>
        )}
        <span className={`tw-caret${done ? " is-done" : ""}`} />
      </span>
    </span>
  );
}
