import { useRef, useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { ChevronDown, ChevronUp } from "lucide-react";
import { useLocation } from "react-router-dom";
import UniversalNavbar from "./UniversalNavbar";
import SellerSlide from "./SellerSlide";

const sections = [
  {
    id: "tips",
    label: "Selling Tips",
    content: (
      <>
        <p>
          Learn how to list products effectively, optimize your listings, and attract more buyers.
        </p>
        <ul className="list-disc ml-6 mt-2">
          <li>Use high-quality images highlighting product details.</li>
          <li>Write clear, keyword-rich titles for better visibility.</li>
          <li>Adopt competitive pricing strategies based on market data.</li>
        </ul>
      </>
    ),
  },
  {
    id: "tools",
    label: "Tools & Insights",
    content: (
      <>
        <p>
          Explore Seller Dashboard tools for analytics, sales tracking, and performance insights.
        </p>
        <ul className="list-disc ml-6 mt-2">
          <li>Dashboard for daily and monthly sales performance.</li>
          <li>Inventory insights to track stock and avoid shortages.</li>
          <li>Customer behavior analytics for smarter decisions.</li>
        </ul>
      </>
    ),
  },
  {
    id: "faqs",
    label: "FAQs",
    content: <FAQSection />,
  },
];

function FAQSection() {
  const [openIndex, setOpenIndex] = useState(null);
  const questions = [
    {
      q: "How do I start selling?",
      a: "To start selling, first register as a seller on our platform by providing your basic details such as name, email, and phone number. Complete the verification process by uploading any required documents. Once verified, you can create your product listings and start selling to buyers immediately."
    },
    {
      q: "When do I receive payments?",
      a: "Payments for your sold products are typically processed within 7–10 business days after the delivery is confirmed. The funds will be transferred directly to your registered bank account. You can track your payment status in the Seller Dashboard under 'Transactions'."
    },
    {
      q: "Can I edit my listings?",
      a: "Yes, you can edit your listings at any time. This includes updating product titles, descriptions, images, pricing, and stock availability. Make sure to save changes after editing. Frequent updates can help improve your visibility and attract more buyers."
    },
    {
      q: "What support is available?",
      a: "Our Seller Support team is available to help you with any issues or questions. You can contact them via live chat on the dashboard, email support, or through our dedicated helpline. Support is available Monday to Friday, 9 AM to 6 PM."
    },
    {
      q: "Are there listing fees?",
      a: "Creating a listing is completely free. A small commission is applied only when a sale is successfully completed. The commission percentage depends on the product category and is displayed clearly during the listing creation process. No hidden fees are charged."
    },
  ];

  return (
    <div className="space-y-4">
      {questions.map((item, index) => (
        <div key={index} className="border border-gray-200 rounded-lg p-4 bg-white shadow-sm">
          <button
            className="w-full flex justify-between items-center text-left font-medium text-gray-800"
            onClick={() => setOpenIndex(openIndex === index ? null : index)}
          >
            {item.q}
            {openIndex === index ? (
              <ChevronUp className="w-5 h-5 text-orange-600" />
            ) : (
              <ChevronDown className="w-5 h-5 text-gray-500" />
            )}
          </button>
          <AnimatePresence>
            {openIndex === index && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: "auto" }}
                exit={{ opacity: 0, height: 0 }}
                transition={{ duration: 0.3 }}
                className="mt-2 text-gray-600 text-sm leading-relaxed"
              >
                {item.a}
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      ))}
    </div>
  );
}

const Learn = () => {
  const sectionRefs = useRef({});
  const [activeSection, setActiveSection] = useState("tips");
  const location = useLocation();

  const handleScroll = (id) => {
    const el = sectionRefs.current[id];
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
    setActiveSection(id);
  };

  useEffect(() => {
    if (location.state?.section) {
      const target = location.state.section;
      const el = sectionRefs.current[target];
      if (el) {
        setTimeout(() => {
          el.scrollIntoView({ behavior: "smooth", block: "start" });
          setActiveSection(target);
        }, 300);
      }
    }
  }, [location.state]);

  useEffect(() => {
    const onScroll = () => {
      const positions = Object.keys(sectionRefs.current).map((id) => ({
        id,
        top: Math.abs(sectionRefs.current[id].getBoundingClientRect().top),
      }));
      positions.sort((a, b) => a.top - b.top);
      if (positions[0] && positions[0].id !== activeSection)
        setActiveSection(positions[0].id);
    };

    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, [activeSection]);

  return (
    <div className="flex flex-col min-h-screen bg-gray-50 font-sans">
      <UniversalNavbar />

      <div className="w-full bg-white shadow p-5">
        <SellerSlide />
      </div>

      <main className="flex flex-col md:flex-row px-5 mt-6 gap-8">
        {/* Sidebar */}
       <aside className="hidden md:flex flex-col w-64 space-y-2 sticky top-20 h-[calc(100vh-5rem)]">
          {sections.map((section) => (
            <button
              key={section.id}
              onClick={() => scrollToSection(section.id)}
              className={`w-full text-left px-3 py-2 rounded-lg transition-all duration-300 ${
                activeSection === section.id
                  ? "bg-orange-100 text-orange-600 font-semibold shadow-md scale-105"
                  : "hover:bg-gray-100 text-gray-700"
              }`}
            >
              {section.label}
            </button>
          ))}
        </aside>


        {/* Page Sections */}
        <div className="flex-1 space-y-16">
          {sections.map((section) => (
            <motion.section
              key={section.id}
              ref={(el) => (sectionRefs.current[section.id] = el)}
              className="scroll-mt-28"
              initial={{ opacity: 0, y: 40 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: false, amount: 0.2 }}
              transition={{ duration: 0.6 }}
            >
              {/* Reduced label size */}
              <h1 className="text-2xl font-bold mb-4 text-gray-900">{section.label}</h1>
              <div className="text-gray-800 text-lg leading-relaxed">{section.content}</div>
            </motion.section>
          ))}
        </div>
      </main>
    </div>
  );
};

export default Learn;
