"use client";

import React, { useEffect, useState } from "react";
import { motion, useScroll, useSpring } from "framer-motion";

export function ScrollProgressBar() {
  const { scrollYProgress } = useScroll();

  // Fine-tuned physics spring for reactive, buttery-smooth lerping
  const scaleX = useSpring(scrollYProgress, {
    stiffness: 180,
    damping: 28,
    restDelta: 0.001,
  });

  const scaleY = useSpring(scrollYProgress, {
    stiffness: 180,
    damping: 28,
    restDelta: 0.001,
  });

  const [percent, setPercent] = useState(0);

  useEffect(() => {
    return scaleX.on("change", (latest) => {
      setPercent(Math.min(100, Math.max(0, Math.round(latest * 100))));
    });
  }, [scaleX]);

  return (
    <>
      {/* 1. Global Architectural Top Progress Bar with Spring Smoothing */}
      <div className="fixed top-0 left-0 right-0 z-50 h-[3px] bg-[#E2E8F0] pointer-events-none">
        <motion.div
          className="h-full bg-black origin-left shadow-[0_0_8px_rgba(0,0,0,0.2)]"
          style={{ scaleX }}
        />
      </div>

      {/* 2. Side Reactive Telemetry Indicator (Desktop) */}
      <motion.div
        initial={{ opacity: 0, x: 20 }}
        animate={{ opacity: percent > 1 ? 1 : 0, x: percent > 1 ? 0 : 20 }}
        transition={{ duration: 0.2 }}
        className="fixed right-4 bottom-8 z-40 hidden xl:flex flex-col items-center gap-2 pointer-events-none select-none"
      >
        <div className="bg-white/95 backdrop-blur-md border border-[#CBD5E1] px-2.5 py-1 shadow-sm font-mono text-[10px] uppercase tracking-caps text-black font-bold flex items-center gap-1.5">
          <span className="w-1.5 h-1.5 rounded-full bg-black animate-pulse" />
          <span>{percent}%</span>
        </div>
        <div className="w-1 h-20 bg-[#E2E8F0] relative overflow-hidden">
          <motion.div
            className="w-full bg-black origin-top"
            style={{ scaleY }}
          />
        </div>
      </motion.div>
    </>
  );
}
