"use client";
import { useState, useRef, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { MessageCircle } from "lucide-react";
import { SellerProvider, useSeller } from "@/lib/SellerContext";
import { SellerHero } from "./SellerHero";
import { SellerStats } from "./SellerStats";
import { AboutSeller } from "./AboutSeller";
import { VerificationBadges } from "./VerificationBadges";
import { SellerListings } from "./SellerListings";
import { RatingsReviews } from "./RatingsReviews";
import { ReputationScore } from "./ReputationScore";
import { ReputationTimeline } from "./ReputationTimeline";
import { SellerAchievements } from "./SellerAchievements";
import { LeaveReviewModal } from "./LeaveReviewModal";
import { ReportModal } from "./ReportModal";

const SECTION_TABS = [
  { id: "stats", label: "Stats" },
  { id: "about", label: "About" },
  { id: "listings", label: "Listings" },
  { id: "reviews", label: "Reviews" },
  { id: "trust", label: "Trust" },
  { id: "achievements", label: "Achievements" },
  { id: "timeline", label: "Journey" },
];

function SectionNav() {
  const [activeSection, setActiveSection] = useState("stats");

  const scrollTo = (id: string) => {
    const el = document.getElementById(id);
    if (el) {
      const offset = 60;
      const top = el.getBoundingClientRect().top + window.scrollY - offset;
      window.scrollTo({ top, behavior: "smooth" });
    }
    setActiveSection(id);
  };

  return (
    <div
      className="sticky top-0 z-30 px-4 py-2 overflow-x-auto no-scrollbar"
      style={{
        background: "rgba(26,26,46,0.92)",
        backdropFilter: "blur(12px)",
        borderBottom: "1px solid var(--border)",
      }}
    >
      <div className="flex gap-1.5">
        {SECTION_TABS.map((tab) => (
          <button
            key={tab.id}
            onClick={() => scrollTo(tab.id)}
            className="shrink-0 px-3 py-1.5 rounded-full text-[11px] font-semibold transition-all"
            style={{
              background: activeSection === tab.id ? "var(--accent)" : "transparent",
              color: activeSection === tab.id ? "#fff" : "var(--text-muted)",
            }}
          >
            {tab.label}
          </button>
        ))}
      </div>
    </div>
  );
}

function SkeletonLoader() {
  return (
    <div className="animate-pulse">
      {/* Hero skeleton */}
      <div className="h-44 rounded-none" style={{ background: "var(--card)" }} />
      <div className="px-4 pt-4 pb-5" style={{ background: "var(--bg)" }}>
        <div className="flex justify-between -mt-12 mb-4">
          <div className="w-[88px] h-[88px] rounded-2xl" style={{ background: "var(--deep)" }} />
          <div className="flex gap-2 mt-16">
            <div className="w-28 h-10 rounded-xl" style={{ background: "var(--deep)" }} />
            <div className="w-28 h-10 rounded-xl" style={{ background: "var(--deep)" }} />
            <div className="w-10 h-10 rounded-xl" style={{ background: "var(--deep)" }} />
          </div>
        </div>
        <div className="h-6 w-48 rounded-lg mb-2" style={{ background: "var(--deep)" }} />
        <div className="h-3 w-32 rounded-lg mb-4" style={{ background: "var(--deep)" }} />
        <div className="grid grid-cols-4 gap-2">
          {[1,2,3,4].map((k) => (
            <div key={k} className="h-16 rounded-xl" style={{ background: "var(--deep)" }} />
          ))}
        </div>
      </div>
      {/* Stats skeleton */}
      <div className="px-4 pb-6">
        <div className="h-4 w-32 rounded mb-3" style={{ background: "var(--deep)" }} />
        <div className="flex gap-3 overflow-hidden">
          {[1,2,3,4].map((k) => (
            <div key={k} className="w-32 h-24 rounded-2xl shrink-0" style={{ background: "var(--deep)" }} />
          ))}
        </div>
      </div>
    </div>
  );
}

function InnerPage() {
  const { profile } = useSeller();
  const [loaded, setLoaded] = useState(false);
  const [reviewModalOpen, setReviewModalOpen] = useState(false);
  const [reportModalOpen, setReportModalOpen] = useState(false);
  const [stickyVisible, setStickyVisible] = useState(false);
  const heroRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Simulate data fetch
    const t = setTimeout(() => setLoaded(true), 400);
    return () => clearTimeout(t);
  }, []);

  // Show sticky CTA when hero passes out of view
  useEffect(() => {
    const handleScroll = () => {
      const heroBottom = heroRef.current?.getBoundingClientRect().bottom ?? 0;
      setStickyVisible(heroBottom < 0);
    };
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  if (!loaded) return <SkeletonLoader />;

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.4 }}
      className="min-h-full pb-28 sm:pb-8"
      style={{ background: "var(--bg)" }}
    >
      {/* Section nav */}
      <SectionNav />

      {/* Hero */}
      <div ref={heroRef}>
        <SellerHero
          onReport={() => setReportModalOpen(true)}
          onMessage={() => {}}
        />
      </div>

      {/* Stats */}
      <SellerStats />

      {/* About */}
      <AboutSeller />

      {/* Verification */}
      <VerificationBadges />

      {/* Listings */}
      <SellerListings onMessage={() => {}} />

      {/* Reviews */}
      <RatingsReviews onLeaveReview={() => setReviewModalOpen(true)} />

      {/* Reputation Score */}
      <ReputationScore />

      {/* Timeline */}
      <ReputationTimeline />

      {/* Achievements */}
      <SellerAchievements />

      {/* Bottom padding */}
      <div className="h-4" />

      {/* Sticky "Contact Seller" bar — mobile only */}
      <AnimatePresence>
        {stickyVisible && (
          <motion.div
            initial={{ y: 80, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={{ y: 80, opacity: 0 }}
            transition={{ type: "spring", stiffness: 300, damping: 28 }}
            className="fixed bottom-0 left-0 right-0 z-40 sm:hidden px-4 pb-6 pt-3"
            style={{
              background: "linear-gradient(to top, rgba(26,26,46,0.98) 60%, transparent)",
            }}
          >
            <button
              className="w-full flex items-center justify-center gap-2.5 py-4 rounded-2xl font-bold text-base text-white shadow-lg active:scale-[0.98] transition-transform"
              style={{
                background: "linear-gradient(135deg, var(--accent) 0%, #ff4040 100%)",
                boxShadow: "0 6px 24px rgba(252,0,0,0.4)",
              }}
            >
              <MessageCircle size={18} />
              Contact {profile.name.split("'")[0]}
            </button>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Modals */}
      <LeaveReviewModal
        open={reviewModalOpen}
        onClose={() => setReviewModalOpen(false)}
      />
      <ReportModal
        open={reportModalOpen}
        onClose={() => setReportModalOpen(false)}
        mode="seller"
      />
    </motion.div>
  );
}

export function SellerProfilePage() {
  return (
    <SellerProvider>
      <InnerPage />
    </SellerProvider>
  );
}
