import { e as createComponent, m as maybeRenderHead, g as addAttribute, k as renderComponent, r as renderTemplate, h as createAstro } from './astro/server_DePCulMI.mjs';
import 'piccolore';
import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';

function WatchlistButton({ productId, size = "sm" }) {
  const [isOnList, setIsOnList] = useState(false);
  const [loading, setLoading] = useState(false);
  const [user, setUser] = useState(null);
  const [showModal, setShowModal] = useState(false);
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [targetPrice, setTargetPrice] = useState("");
  useEffect(() => {
    fetch("/api/auth/session").then((r) => r.json()).then((data) => {
      if (data.user) {
        setUser(data.user);
        fetch("/api/watchlist").then((r) => r.json()).then((wl) => {
          if (wl.items?.some((i) => i.product_id === productId)) {
            setIsOnList(true);
          }
        }).catch(() => {
        });
      }
    }).catch(() => {
    });
  }, [productId]);
  const handleClick = async (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (!user) {
      setShowModal(true);
      return;
    }
    setLoading(true);
    try {
      if (isOnList) {
        await fetch("/api/watchlist", {
          method: "DELETE",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ product_id: productId })
        });
        setIsOnList(false);
      } else {
        await fetch("/api/watchlist", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            product_id: productId,
            target_price: targetPrice ? parseFloat(targetPrice) : null
          })
        });
        setIsOnList(true);
      }
    } catch {
    }
    setLoading(false);
  };
  const handleRegister = async (e) => {
    e.preventDefault();
    setLoading(true);
    setMessage("");
    try {
      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email })
      });
      const data = await res.json();
      if (data.ok) {
        setMessage("Check je email! 📧");
      } else if (data.error?.includes("al geregistreerd")) {
        const loginRes = await fetch("/api/auth/login", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email })
        });
        const loginData = await loginRes.json();
        setMessage(loginData.message || "Check je email voor de inloglink!");
      } else {
        setMessage(data.error || "Er ging iets mis");
      }
    } catch {
      setMessage("Er ging iets mis");
    }
    setLoading(false);
  };
  const iconSize = size === "sm" ? "w-5 h-5" : "w-6 h-6";
  const btnSize = size === "sm" ? "p-1.5" : "p-2";
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      "button",
      {
        onClick: handleClick,
        disabled: loading,
        className: `${btnSize} rounded-full transition-all duration-200 ${isOnList ? "bg-[#00FF6A]/20 text-[#00FF6A]" : "bg-white/10 text-white/60 hover:bg-white/20 hover:text-white"} ${loading ? "opacity-50" : ""}`,
        title: isOnList ? "Verwijder van watchlist" : "Voeg toe aan watchlist",
        children: /* @__PURE__ */ jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: isOnList ? "currentColor" : "none", stroke: "currentColor", strokeWidth: 2, className: iconSize, children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z" }) })
      }
    ),
    showModal && typeof document !== "undefined" && createPortal(
      /* @__PURE__ */ jsx(
        "div",
        {
          className: "fixed inset-0 z-[9999] flex items-center justify-center bg-black/70 p-4",
          onClick: (e) => {
            if (e.target === e.currentTarget) setShowModal(false);
          },
          children: /* @__PURE__ */ jsxs("div", { className: "w-full max-w-sm rounded-2xl border border-white/10 bg-[#141414] p-6 shadow-2xl", onClick: (e) => e.stopPropagation(), children: [
            /* @__PURE__ */ jsx("h3", { className: "mb-2 text-lg font-bold text-white", children: "Sneaker volgen" }),
            /* @__PURE__ */ jsx("p", { className: "mb-4 text-sm text-white/60", children: "Voer je email in om deze sneaker op je watchlist te zetten en prijsalerts te ontvangen." }),
            /* @__PURE__ */ jsxs("form", { onSubmit: handleRegister, children: [
              /* @__PURE__ */ jsx(
                "input",
                {
                  type: "email",
                  value: email,
                  onChange: (e) => setEmail(e.target.value),
                  placeholder: "je@email.nl",
                  required: true,
                  className: "mb-3 w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2.5 text-white placeholder-white/30 focus:border-[#00FF6A]/50 focus:outline-none"
                }
              ),
              /* @__PURE__ */ jsxs("div", { className: "mb-3 rounded-lg border border-white/10 bg-white/5 p-3", children: [
                /* @__PURE__ */ jsx("p", { className: "text-xs font-medium text-white/50 mb-1.5", children: "Prijsalert (optioneel)" }),
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx("span", { className: "text-sm text-white/60", children: "Mail mij onder €" }),
                  /* @__PURE__ */ jsx(
                    "input",
                    {
                      type: "number",
                      value: targetPrice,
                      onChange: (e) => setTargetPrice(e.target.value),
                      placeholder: "0,00",
                      step: "0.01",
                      min: "0",
                      className: "w-24 rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-white placeholder-white/30 focus:border-[#00FF6A]/50 focus:outline-none"
                    }
                  )
                ] })
              ] }),
              message && /* @__PURE__ */ jsx("p", { className: `mb-3 text-sm ${message.includes("Check") ? "text-[#00FF6A]" : "text-red-400"}`, children: message }),
              /* @__PURE__ */ jsx(
                "button",
                {
                  type: "submit",
                  disabled: loading,
                  className: "w-full rounded-lg bg-[#00FF6A] px-4 py-2.5 font-bold text-black transition-colors hover:bg-[#00FF6A]/90 disabled:opacity-50",
                  children: loading ? "Even geduld..." : "Watchlist & Alerts activeren"
                }
              )
            ] }),
            /* @__PURE__ */ jsx(
              "button",
              {
                onClick: () => setShowModal(false),
                className: "mt-3 w-full text-center text-sm text-white/40 hover:text-white/60",
                children: "Annuleren"
              }
            )
          ] })
        }
      ),
      document.body
    )
  ] });
}

const $$Astro = createAstro();
const $$ProductCard = createComponent(($$result, $$props, $$slots) => {
  const Astro2 = $$result.createAstro($$Astro, $$props, $$slots);
  Astro2.self = $$ProductCard;
  function getDiscountPercent(sneaker2) {
    return Math.round((sneaker2.originalPrice - sneaker2.lowestPrice) / sneaker2.originalPrice * 100);
  }
  const { sneaker, index = 0 } = Astro2.props;
  const discount = getDiscountPercent(sneaker);
  return renderTemplate`${maybeRenderHead()}<a${addAttribute(`/sneakers/${sneaker.slug}`, "href")}${addAttribute([
    "group relative flex flex-col overflow-hidden rounded-2xl border border-border/50 bg-bg-card transition-all duration-300 hover:-translate-y-1 hover:border-accent/30 hover:shadow-lg hover:shadow-accent/5",
    "animate-fade-up",
    `stagger-${Math.min(index + 1, 8)}`
  ], "class:list")}${addAttribute(sneaker.id, "data-analytics-item-id")}${addAttribute(`${sneaker.brand} ${sneaker.name}`, "data-analytics-item-name")}${addAttribute(sneaker.brand, "data-analytics-item-brand")}${addAttribute(sneaker.lowestPrice, "data-analytics-price")} onclick="(function(el){window.dataLayer=window.dataLayer||[];window.dataLayer.push({ecommerce:null});window.dataLayer.push({event:'select_item',ecommerce:{items:[{item_id:el.dataset.analyticsItemId,item_name:el.dataset.analyticsItemName,item_brand:el.dataset.analyticsItemBrand,price:parseFloat(el.dataset.analyticsPrice)}]}})})(this)"> <!-- Watchlist button --> <div class="absolute right-3 top-3 z-10 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity duration-200"> ${renderComponent($$result, "WatchlistButton", WatchlistButton, { "client:visible": true, "productId": sneaker.id, "size": "sm", "client:component-hydration": "visible", "client:component-path": "C:/Users/Roel/clawd/sneakerpicks/src/components/WatchlistButton.tsx", "client:component-export": "default" })} </div> <!-- Discount badge --> ${discount > 0 && renderTemplate`<div class="absolute left-3 top-3 z-10 rounded-full bg-deal px-2.5 py-1 text-xs font-bold text-white">
-${discount}%
</div>`} <!-- Image --> <div class="relative aspect-square w-full shrink-0 overflow-hidden bg-bg-elevated"> <img${addAttribute(`/api/img/${sneaker.id}`, "src")}${addAttribute(`${sneaker.brand} ${sneaker.name}`, "alt")} width="600" height="600" class="h-full w-full object-contain transition-transform duration-500 group-hover:scale-110 text-transparent" loading="lazy" onerror="this.style.display='none'"> <!-- Hover glow --> <div class="absolute inset-0 bg-gradient-to-t from-accent/5 to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100"></div> </div> <!-- Info --> <div class="flex flex-1 flex-col gap-2 p-4"> <span class="text-[11px] font-bold uppercase tracking-widest text-text-muted">${sneaker.brand}</span> <h3 class="font-semibold leading-tight text-text transition-colors group-hover:text-accent">${sneaker.name}</h3> <p class="text-xs text-text-muted">${sneaker.colorway}</p> <div class="mt-auto flex items-baseline gap-2 pt-2"> <span class="text-lg font-black text-accent">vanaf €${sneaker.lowestPrice.toFixed(2).replace(".", ",")}</span> ${sneaker.originalPrice > sneaker.lowestPrice && renderTemplate`<span class="text-sm text-text-muted line-through">€${sneaker.originalPrice.toFixed(2).replace(".", ",")}</span>`} </div> <div class="text-[11px] text-text-muted">${sneaker.offers.filter((o) => o.inStock).length} shops</div> </div> </a>`;
}, "C:/Users/Roel/clawd/sneakerpicks/src/components/ProductCard.astro", void 0);

export { $$ProductCard as $, WatchlistButton as W };
