'use client';

import { useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';

// Pages without one of these fall back to "most of a screen height".
const HERO_SELECTOR = '.hero, .result-hero, .report-cover';
const RING_RADIUS = 22;
const RING_LENGTH = 2 * Math.PI * RING_RADIUS;

/** Floating "back to top" button. Appears once the page's hero is scrolled past; its ring shows scroll progress. */
export function BackToTop() {
  const pathname = usePathname();
  const [visible, setVisible] = useState(false);
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    let frame = 0;
    const update = () => {
      frame = 0;
      const hero = document.querySelector<HTMLElement>(HERO_SELECTOR);
      const heroBottom = hero ? hero.getBoundingClientRect().bottom + window.scrollY : window.innerHeight * 0.8;
      const y = window.scrollY;
      const max = document.documentElement.scrollHeight - window.innerHeight;
      setVisible(y > Math.max(heroBottom - 80, 240));
      setProgress(max > 0 ? Math.min(y / max, 1) : 0);
    };
    const onScroll = () => {
      if (!frame) frame = window.requestAnimationFrame(update);
    };
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (frame) window.cancelAnimationFrame(frame);
    };
  }, [pathname]);

  function toTop() {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    window.scrollTo({ top: 0, behavior: reduce ? 'auto' : 'smooth' });
  }

  return (
    <button
      type="button"
      className={visible ? 'to-top no-print is-visible' : 'to-top no-print'}
      onClick={toTop}
      aria-label="Back to top"
      tabIndex={visible ? 0 : -1}
      aria-hidden={!visible}
    >
      <svg viewBox="0 0 52 52" className="to-top-ring" aria-hidden="true">
        <circle cx="26" cy="26" r={RING_RADIUS} className="to-top-track" />
        <circle
          cx="26"
          cy="26"
          r={RING_RADIUS}
          className="to-top-progress"
          strokeDasharray={RING_LENGTH}
          strokeDashoffset={RING_LENGTH * (1 - progress)}
        />
      </svg>
      <svg viewBox="0 0 24 24" className="to-top-arrow" aria-hidden="true">
        <path d="M12 19V6M6 11l6-6 6 6" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
      <span className="to-top-label">Back to top</span>
    </button>
  );
}
