<section id="product-grid" class="bg-surface">
  <div id="react-product-grid"></div>

  <script type="text/babel">

    const productGridTitle = "{{ sections.product_grid.title }}";
    const productGridItems = {{ sections.product_grid.items | tojson | safe }};
    const themeColors = {
      primary: "{{ settings.theme.colors.primary | default('#4F46E5') }}",
      accent: "{{ settings.theme.colors.accent | default('#818CF8') }}",
      success: "{{ settings.theme.colors.success | default('#10B981') }}"
    };

    const products = productGridItems.map((item, index) => ({
      id: index + 1,
      name: item.name,
      description: item.description,
      image: item.image.src,
      imageAlt: item.image.alt,
      price: {
        amount: item.price.amount,
        currency: item.price.currency
      },
      category: item.category || "Uncategorized",
      offer: item.offer || null
    }));

    const filters = {
      category: ["All", "Electronics", "Clothing", "Books"],
      price: ["All", "0-20", "20-50", "50+"],
    };

    function App() {
      const [cart, setCart] = React.useState([]);
      const [view, setView] = React.useState("shop");
      const addToCart = (p) => setCart((c) => [...c, p]);
      const removeFromCart = (i) =>
        setCart((c) => c.filter((_, j) => j !== i));
      const total = cart
        .reduce((sum, it) => sum + it.price.amount, 0)
        .toFixed(2);

      return view === "shop" ? (
        <ShopPage
          products={products}
          filters={filters}
          cart={cart}
          addToCart={addToCart}
          removeFromCart={removeFromCart}
          goToCheckout={() => setView("checkout")}
        />
      ) : (
        <PaymentPage total={total} goBack={() => setView("shop")} />
      );
    }

    function Navbar({ cartCount, onCart, onFilter }) {
      return (
        <nav className="bg-white shadow-lg sticky top-0 z-50">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex items-center justify-between">
            <span className="text-2xl font-bold text-gray-900">
              {productGridTitle}
            </span>
            <div className="flex-1 mx-6 hidden md:block">
              <input
                type="text"
                placeholder="Search products..."
                className="w-full py-2.5 px-4 rounded-full bg-gray-50 border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary text-gray-700 transition"
              />
            </div>
            <div className="flex items-center space-x-4">
              <button
                className="md:hidden text-gray-600 hover:text-primary transition"
                onClick={onFilter}
                aria-label="Filters"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  className="h-6 w-6"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2a1 1 0 01-.293.707L15 13.414V19a1 1 0 01-.553.894l-4 2A1 1 0 019 21v-7.586L3.293 6.707A1 1 0 013 6V4z"
                  />
                </svg>
              </button>
              <button
                onClick={onCart}
                className="relative text-gray-600 hover:text-primary transition"
                aria-label="Cart"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  className="h-6 w-6"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2 9M17 13l2 9M9 21h6"
                  />
                </svg>
                {cartCount > 0 && (
                  <span className="absolute -top-2 -right-2 bg-primary text-white text-xs rounded-full px-2 py-0.5">
                    {cartCount}
                  </span>
                )}
              </button>
            </div>
          </div>
        </nav>
      );
    }

    function ShopPage({
      products,
      filters,
      cart,
      addToCart,
      removeFromCart,
      goToCheckout,
    }) {
      const [cat, setCat] = React.useState("All");
      const [price, setPrice] = React.useState("All");
      const [showCart, setShowCart] = React.useState(false);
      const [showFilter, setShowFilter] = React.useState(false);
      const [toast, setToast] = React.useState("");

      React.useEffect(() => {
        if (!toast) return;
        const id = setTimeout(() => setToast(""), 2000);
        return () => clearTimeout(id);
      }, [toast]);



      const handleAdd = (p) => {
        addToCart(p);
        setToast(`"${p.name}" added to cart`);
      };

      const filtered = products.filter((p) => {
        if (cat !== "All" && p.category !== cat) return false;
        const amt = p.price.amount;
        if (price !== "All") {
          if (price === "0-20" && !(amt <= 20)) return false;
          if (price === "20-50" && !(amt > 20 && amt <= 50)) return false;
          if (price === "50+" && !(amt > 50)) return false;
        }
        return true;
      });

      return (
        <>
          <Navbar
            cartCount={cart.length}
            onCart={() => setShowCart(true)}
            onFilter={() => setShowFilter(true)}
          />

          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 grid grid-cols-1 lg:grid-cols-4 gap-8">
            {/* Desktop Sidebar */}
            <aside className="hidden lg:block bg-white p-6 rounded-xl shadow-sm space-y-8 sticky top-24">
              <FilterContent
                filters={filters}
                cat={cat}
                setCat={setCat}
                price={price}
                setPrice={setPrice}
              />
            </aside>

            {/* Products + Mobile Filter */}
            <div className="lg:col-span-3">
              <div className="flex items-center justify-between mb-6 lg:hidden">
                <button
                  onClick={() => setShowFilter(true)}
                  className="flex items-center px-4 py-2 bg-white rounded-lg shadow-sm border border-gray-200 hover:bg-gray-50 transition"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    className="h-5 w-5 mr-2 text-gray-600"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2a1 1 0 01-.293.707L15 13.414V19a1 1 0 01-.553.894l-4 2A1 1 0 019 21v-7.586L3.293 6.707A1 1 0 013 6V4z"
                    />
                  </svg>
                  Filters
                </button>
              </div>

              <div className="grid gap-6 grid-cols-1 sm:grid-cols-2 lg:grid-cols-3">
                {filtered.length > 0 ? (
                  filtered.map((p, index) => (
                    <div
                      key={p.id}
                      className="bg-white rounded-xl shadow-sm hover:shadow-lg hover-scale transition overflow-hidden flex flex-col animate-slide-in"
                    >
                      <div className="relative">
                        <img
                          src={p.image}
                          alt={p.imageAlt}
                          className="h-56 w-full object-cover"
                        />
                        {p.offer && (
                          <span className="absolute top-3 right-3 bg-accent/10 text-accent px-3 py-1 rounded-full text-xs font-medium">
                            {p.offer.discount}
                          </span>
                        )}
                      </div>
                      <div className="p-5 flex-1 flex flex-col">
                        <h3 className="text-lg font-semibold text-gray-900">
                          {p.name}
                        </h3>
                        <p className="text-gray-600 text-sm mt-1 flex-1">
                          {p.description}
                        </p>
                        <div className="mt-4 flex items-center justify-between">
                          <span className="text-xl font-bold text-primary">
                            ${p.price.amount.toFixed(2)}
                          </span>
                        </div>
                        {p.offer && (
                          <div className="text-sm text-success mt-1">
                            {p.offer.description}
                          </div>
                        )}
                        <button
                          onClick={() => handleAdd(p)}
                          className="mt-4 bg-primary text-white py-2.5 rounded-lg hover:bg-primary/90 transition font-medium"
                        >
                          Add to Cart
                        </button>
                      </div>
                    </div>
                  ))
                ) : (
                  <p className="text-center text-gray-500 col-span-full">
                    No products found.
                  </p>
                )}
              </div>
            </div>
          </div>

          {/* Mobile Filter Drawer */}
          {showFilter && (
            <div className="fixed inset-0 z-50 flex">
              <div className="w-80 bg-white p-6 shadow-xl animate-slide-in">
                <div className="flex justify-between items-center mb-6">
                  <h2 className="text-xl font-semibold">Filters</h2>
                  <button
                    onClick={() => setShowFilter(false)}
                    className="text-gray-600 hover:text-gray-900"
                  >
                    ✕
                  </button>
                </div>
                <FilterContent
                  filters={filters}
                  cat={cat}
                  setCat={setCat}
                  price={price}
                  setPrice={setPrice}
                />
              </div>
              <div
                className="flex-1 bg-black bg-opacity-30"
                onClick={() => setShowFilter(false)}
              ></div>
            </div>
          )}

          {/* Cart Modal */}
          {showCart && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
              <div className="bg-white w-full max-w-md mx-4 p-6 rounded-xl shadow-xl animate-slide-in">
                <div className="flex justify-between items-center mb-6">
                  <h3 className="text-xl font-semibold">My Cart</h3>
                  <button
                    onClick={() => setShowCart(false)}
                    className="text-gray-600 hover:text-gray-900"
                  >
                    ✕
                  </button>
                </div>
                {cart.length === 0 ? (
                  <p className="text-gray-600 text-center">Cart is empty.</p>
                ) : (
                  <ul className="space-y-4 mb-6 max-h-60 overflow-y-auto">
                    {cart.map((it, i) => (
                      <li
                        key={i}
                        className="flex justify-between items-center"
                      >
                        <span className="text-gray-900 font-medium">
                          {it.name}
                        </span>
                        <div className="flex items-center space-x-4">
                          <span className="text-gray-900 font-semibold">
                            ${it.price.amount.toFixed(2)}
                          </span>
                          <button
                            onClick={() => removeFromCart(i)}
                            className="text-red-500 hover:text-red-700 transition"
                          >
                            Remove
                          </button>
                        </div>
                      </li>
                    ))}
                  </ul>
                )}
                <div className="font-semibold text-lg mb-6">
                  Total: $
                  {cart.reduce((s, it) => s + it.price.amount, 0).toFixed(2)}
                </div>
                <div className="flex justify-end space-x-4">
                  <button
                    onClick={() => setShowCart(false)}
                    className="px-4 py-2 rounded-lg border border-gray-200 hover:bg-gray-100 transition"
                  >
                    Continue Shopping
                  </button>
                  <button
                    onClick={() => {
                      setShowCart(false);
                      setTimeout(goToCheckout, 100);
                    }}
                    className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition"
                  >
                    Checkout
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Toast */}
          {toast && (
            <div className="fixed bottom-8 inset-x-0 flex justify-center z-50 pointer-events-none">
              <div className="bg-gray-900 text-white px-4 py-2 rounded-lg shadow-lg animate-slide-in">
                {toast}
              </div>
            </div>
          )}
        </>
      );
    }

    function FilterContent({ filters, cat, setCat, price, setPrice }) {
      return (
        <>
          <div>
            <h4 className="font-semibold text-lg mb-3">Category</h4>
            {filters.category.map((c) => (
              <label
                key={c}
                className="flex items-center mb-3 cursor-pointer"
              >
                <input
                  type="radio"
                  name="cat"
                  className="h-4 w-4 text-primary focus:ring-primary border-gray-300"
                  checked={cat === c}
                  onChange={() => setCat(c)}
                />
                <span className="ml-3 text-gray-700">{c}</span>
              </label>
            ))}
          </div>
          <div className="mt-6">
            <h4 className="font-semibold text-lg mb-3">Price</h4>
            {filters.price.map((r) => (
              <label
                key={r}
                className="flex items-center mb-3 cursor-pointer"
              >
                <input
                  type="radio"
                  name="price"
                  className="h-4 w-4 text-primary focus:ring-primary border-gray-300"
                  checked={price === r}
                  onChange={() => setPrice(r)}
                />
                <span className="ml-3 text-gray-700">{r}</span>
              </label>
            ))}
          </div>
        </>
      );
    }

    function PaymentPage({ total, goBack }) {
      const openRazorpay = () => {
        const options = {
          key: "rzp_test_yourKeyHere",
          amount: Math.round(total * 100),
          currency: "INR",
          name: productGridTitle,
          description: "Test Transaction",
          handler: (resp) =>
            alert("Payment successful! ID: " + resp.razorpay_payment_id),
          theme: { color: themeColors.primary },
        };
        new window.Razorpay(options).open();
      };

      return (
        <div>
          <Navbar cartCount={0} onCart={goBack} onFilter={() => {}} />
          <div className="max-w-lg mx-auto mt-12 bg-white p-8 rounded-xl shadow-sm">
            <h2 className="text-2xl font-bold mb-6">Checkout</h2>
            <div className="mb-6">
              <p className="text-gray-700 mb-2">Amount to pay:</p>
              <p className="text-2xl font-semibold text-primary">₹{total}</p>
            </div>
            <button
              onClick={openRazorpay}
              className="w-full bg-primary text-white py-3 rounded-lg hover:bg-primary/90 transition font-medium"
            >
              Pay Now
            </button>
            <button
              onClick={goBack}
              className="w-full mt-3 bg-gray-100 text-gray-700 py-3 rounded-lg hover:bg-gray-200 transition"
            >
              Back to Shop
            </button>
          </div>
        </div>
      );
    }

      if (typeof React !== "undefined" && typeof ReactDOM !== "undefined") {
        const rootElement = document.getElementById("react-product-grid");
        if (rootElement) {
          ReactDOM.createRoot(rootElement).render(<App/>);
        }
      }
  </script>

  <style>
    @keyframes slideIn {
      from {
        transform: translateY(20px);
        opacity: 0;
      }
      to {
        transform: translateY(0);
        opacity: 1;
      }
    }
  </style>
</section>
