import React, { useEffect, useRef, useMemo, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { productList } from "./productsData";
import "../styles/Product.css";

export default function Products() {
  const navigate = useNavigate();
  const location = useLocation();
  const productCardsRef = useRef([]);
  const [selectedCategory, setSelectedCategory] = useState("Fresh Fruits");

  const categoryToTypeMap = useMemo(
    () => ({
      "Fresh Fruits": "Fruit",
      Vegetables: "Vegetable",
      "Frozen Foods": "Frozen",
      Grains: "Grain",
    }),
    []
  );

  const categories = useMemo(
    () => ["Fresh Fruits", "Vegetables", "Frozen Foods", "Grains"],
    []
  );

  // Initialize category from URL (?category=fresh-fruits | vegetables | frozen-foods | grains)
  useEffect(() => {
    const params = new URLSearchParams(location.search);
    const categoryParam = (params.get("category") || "").toLowerCase();
    const paramToLabel = {
      "fresh-fruits": "Fresh Fruits",
      vegetables: "Vegetables",
      "frozen-foods": "Frozen Foods",
      grains: "Grains",
    };
    if (paramToLabel[categoryParam]) {
      setSelectedCategory(paramToLabel[categoryParam]);
    }
  }, [location.search]);

  const handleViewDetails = (product) => {
    navigate(`/product/${encodeURIComponent(product.name)}`);
  };

  const filteredProducts = useMemo(() => {
    const type = categoryToTypeMap[selectedCategory];
    return productList.filter((p) => p.type === type);
  }, [selectedCategory, categoryToTypeMap]);

  useEffect(() => {
    // Ensure currently mounted cards are visible
    productCardsRef.current.forEach((card) => {
      if (card) card.classList.add("visible");
    });
  }, [filteredProducts]);

  const handleSelectCategory = (label) => {
    setSelectedCategory(label);
    const labelToParam = {
      "Fresh Fruits": "fresh-fruits",
      Vegetables: "vegetables",
      "Frozen Foods": "frozen-foods",
      Grains: "grains",
    };
    const param = labelToParam[label];
    navigate({ pathname: "/products", search: `?category=${param}` }, { replace: true });
  };

  // Function to strip HTML tags
  const stripHtml = (html) => html.replace(/<[^>]*>/g, "").trim();

  return (
    <section className="products-section">
      <div className="title-box">
        <h1 className="main-title">Our Products</h1>
      </div>

      <div className="category-filter">
        {categories.map((label) => (
          <button
            key={label}
            className={`category-btn${label === selectedCategory ? " active" : ""}`}
            onClick={() => handleSelectCategory(label)}
            aria-pressed={label === selectedCategory}
          >
            {label}
          </button>
        ))}
      </div>

      <div className="products-grid">
        {filteredProducts.map((product, i) => (
          <div
            key={product.name}
            className="product-card"
            ref={(el) => (productCardsRef.current[i] = el)}
          >
            <div className="image-box">
              <img src={product.image} alt={product.name} />
            </div>
            <div className="card-content">
              <h2>{product.name}</h2>
              {/* Strip HTML tags here */}
              <p>{stripHtml(product.description)}</p>
            </div>
            <div className="hover-overlay">
              <button onClick={() => handleViewDetails(product)}>View Details</button>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}
