import { useEffect, useRef, useState } from "react";
import SellerSlide from "./SellerSlide";
import ProductImg from "../../assets/images/ProductImg.png";
import payment1 from "../../assets/images/payment1.png";
import UniversalNavbar from "./UniversalNavbar";

const sections = [
  {
    id: "payment",
    label: "Payment Cycle",
    bg: "bg-white",
    content: (
      <div className="flex flex-col md:flex-row items-center gap-8 p-6">
        <div className="flex-1 space-y-3">
          <p>Congratulations on receiving your first order! At E-Sahakara, we ensure smooth, fast, and secure payments for every seller.</p>
          <p><strong>Payment Cycle:</strong> Payments are processed automatically once the order is marked as delivered and the buyer confirms satisfaction.</p>
          <ul className="list-disc ml-6">
            <li>Transparent settlement timelines</li>
            <li>Instant payout notifications</li>
            <li>Track earnings in your dashboard</li>
          </ul>
        </div>
        <div className="flex-1 flex justify-center">
          <img src={payment1} alt="Payment illustration" className="w-2/3 max-w-xs rounded-lg shadow-md object-contain" />
        </div>
      </div>
    ),
  },
  {
    id: "fulfilment",
    label: "Fulfilment Type",
    bg: "bg-orange-50",
    content: (
      <div className="flex flex-col md:flex-row-reverse items-center gap-8 p-6">
        <div className="flex-1 space-y-3">
          <p>The type of fulfilment you choose determines the services and fees associated with your sales on E-Sahakara.</p>
          <p><strong>Fulfilment by E-Sahakara (FBE):</strong></p>
          <ul className="list-disc ml-6">
            <li>E-Sahakara manages packaging, shipping, and delivery, ensuring quick and reliable service to your buyers.</li>
          </ul>
          <p className="mt-3"><strong>Self-Fulfilment (SFS):</strong></p>
          <ul className="list-disc ml-6">
            <li>You handle packaging and shipping directly to customers. Gives you control and flexibility over logistics.</li>
          </ul>
          <p>Each option carries different fee structures and benefits. Review them in your Seller Dashboard to maximise your profits.</p>
        </div>
        <div className="flex-1 flex justify-center">
          <img src={ProductImg} alt="Fulfilment illustration" className="w-2/3 max-w-xs rounded-lg shadow-md object-contain" />
        </div>
      </div>
    ),
  },
  {
    id: "calculate",
    label: "Calculate Margin",
    bg: "bg-white",
    content: (
      <div className="p-6">
        <p>Use E-Sahakara’s margin calculator to estimate profits easily.</p>
        <p className="mt-2">Input product price, logistics cost, and commission rate to understand your final earnings before listing.</p>
        <div className="overflow-x-auto mt-6">
          <table className="min-w-full border border-gray-200 rounded-lg text-sm">
            <thead className="bg-blue-50">
              <tr>
                <th className="border px-4 py-2 text-left font-semibold">Details</th>
                <th className="border px-4 py-2 text-left font-semibold">Local</th>
                <th className="border px-4 py-2 text-left font-semibold">Zonal</th>
                <th className="border px-4 py-2 text-left font-semibold">National</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td className="border px-4 py-2">0–500 grams</td>
                <td className="border px-4 py-2">0</td>
                <td className="border px-4 py-2">0</td>
                <td className="border px-4 py-2">16</td>
              </tr>
              <tr className="bg-orange-50">
                <td className="border px-4 py-2">Incremental 500g, up to 1kg</td>
                <td className="border px-4 py-2">5</td>
                <td className="border px-4 py-2">20</td>
                <td className="border px-4 py-2">25</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    ),
  },
];

const FeeAndCom = () => {
  const sectionRefs = useRef({});
  const [activeSection, setActiveSection] = useState("payment");

  // Scroll to section if hash exists
  useEffect(() => {
    const hash = window.location.hash.replace("#", "");
    if (hash) {
      const el = document.getElementById(hash);
      if (el) {
        el.scrollIntoView({ behavior: "smooth" });
        setActiveSection(hash);
      }
    }
  }, []);

  // Track scrolling to highlight sidebar
  useEffect(() => {
    const handleScroll = () => {
      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", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, [activeSection]);

  const scrollToSection = (id) => {
    sectionRefs.current[id]?.scrollIntoView({ behavior: "smooth" });
    setActiveSection(id);
  };

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

      {/* Seller Slide */}
      <div className="w-full bg-white shadow p-5 mb-6">
        <SellerSlide />
      </div>

      {/* Main layout */}
      <div className="flex flex-col md:flex-row px-5">
        {/* 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>
        {/* Content */}
        <main className="flex-1 p-8 space-y-24">
          {sections.map((section) => (
            <section
              key={section.id}
              id={section.id}
              ref={(el) => (sectionRefs.current[section.id] = el)}
              className="mb-24 scroll-mt-24"
            >
              <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>
            </section>
          ))}
        </main>
      </div>
    </div>
  );
};

export default FeeAndCom;
