'use client';

import React, { useState, useEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';
import { ChevronUp } from 'lucide-react';

export const ScrollToTop: React.FC = () => {
  const pathname = usePathname();
  const [progress, setProgress] = useState(0);
  const [isVisible, setIsVisible] = useState(false);
  const isFirstRender = useRef(true);

  // Reset scroll to top on page navigation, but NOT on browser reload (first mount)
  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return;
    }
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, [pathname]);

  useEffect(() => {
    const handleScroll = () => {
      const scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
      if (scrollHeight > 0) {
        setProgress(window.scrollY / scrollHeight);
      }
      
      if (window.scrollY > 300) {
        setIsVisible(true);
      } else {
        setIsVisible(false);
      }
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    // Run once on mount
    handleScroll();

    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  if (pathname?.startsWith('/reseller')) {
    return null;
  }

  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  };

  const radius = 20;
  const circumference = 2 * Math.PI * radius; // ~125.66
  const strokeDashoffset = circumference - progress * circumference;

  return (
    <div 
      className={`fixed bottom-24 lg:bottom-8 right-6 z-40 flex h-12 w-12 items-center justify-center transition-all duration-300 ${
        isVisible ? 'opacity-100 scale-100' : 'opacity-0 scale-75 pointer-events-none'
      }`}
    >
      {/* SVG Progress Ring */}
      <svg className="absolute inset-0 h-full w-full select-none pointer-events-none" viewBox="0 0 48 48">
        {/* Faint background circle */}
        <circle
          cx="24"
          cy="24"
          r={radius}
          fill="none"
          stroke="rgba(243, 112, 33, 0.15)"
          strokeWidth="2"
        />
        {/* Active progress circle */}
        <circle
          cx="24"
          cy="24"
          r={radius}
          fill="none"
          stroke="var(--color-secondary)"
          strokeWidth="2"
          strokeDasharray={circumference}
          strokeDashoffset={strokeDashoffset}
          strokeLinecap="round"
          className="transition-all duration-75 ease-out"
        />
      </svg>

      {/* Chevron Button */}
      <button
        onClick={scrollToTop}
        type="button"
        className="flex h-9 w-9 items-center justify-center rounded-full bg-secondary text-white shadow-md cursor-pointer transition-all duration-300 hover:scale-110 active:scale-95 focus:outline-none"
        aria-label="Scroll to top"
      >
        <ChevronUp className="h-5 w-5 stroke-[3]" />
      </button>
    </div>
  );
};
