// Reusable glitched headline. Pair with CSS in index.html.
// Usage: <GlitchTitle lines={[{text:'THE'},{text:'BLOG.', accent:true}]} />

const GlitchTitle = ({ lines, style, className = '', cursor = true }) => {
  const T = window.TOKENS;
  const [glitch, setGlitch] = React.useState(false);
  const [cursorOn, setCursorOn] = React.useState(true);

  React.useEffect(() => {
    let active = true;
    let timer;
    const fire = () => {
      if (!active) return;
      setGlitch(true);
      setTimeout(() => active && setGlitch(false), 420);
      if (Math.random() < 0.3) {
        setTimeout(() => {
          if (!active) return;
          setGlitch(true);
          setTimeout(() => active && setGlitch(false), 260);
        }, 540);
      }
      timer = setTimeout(fire, 2200 + Math.random() * 3800);
    };
    timer = setTimeout(fire, 1400);
    return () => { active = false; clearTimeout(timer); };
  }, []);

  React.useEffect(() => {
    if (!cursor) return;
    const t = setInterval(() => setCursorOn(c => !c), 530);
    return () => clearInterval(t);
  }, [cursor]);

  const cls = ['glitch-title', 'glitch-name', glitch ? 'glitching' : '', className]
    .filter(Boolean).join(' ');

  return (
    <h1 className={cls} style={{
      margin: 0, fontSize: 'clamp(48px, 7vw, 92px)', lineHeight: 0.95, fontWeight: 900,
      letterSpacing: '-0.04em',
      ...style,
    }}>
      {lines.map((line, i) => {
        const isLast = i === lines.length - 1;
        const showCursor = cursor && isLast;
        return (
          <React.Fragment key={i}>
            <span
              className="glitch-line"
              data-text={showCursor ? line.text + '_' : line.text}
              style={line.accent ? { color: T.accent } : undefined}
            >
              {line.text}
              {showCursor && (
                <span style={{
                  color: T.accent,
                  opacity: cursorOn ? 1 : 0,
                  transition: 'opacity 0.05s',
                }}>_</span>
              )}
            </span>
            {!isLast && <br />}
          </React.Fragment>
        );
      })}
    </h1>
  );
};

window.GlitchTitle = GlitchTitle;
