"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import type { Product } from "@/lib/api";
import { addToCart as addItem } from "@/lib/cart";
import { inWishlist, toggleWishlist } from "@/lib/wishlist";

function slugify(s: string) {
  return s.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
}

/** Swatch colours for the card's "more colours" row (shades show as a count only). */
const DOT: Record<string, string> = {
  black: "#23201c", white: "#f4efe6", grey: "#9a958c", gray: "#9a958c", nude: "#e6c3aa", rose: "#d87aa0", pink: "#e3a0b8",
  yellow: "#e6b422", orange: "#e07a3a", green: "#5f7d4f", aqua: "#6fc7c7", blue: "#3a5a9a", magenta: "#c0398b", coral: "#f08a6a",
};
const dot = (name?: string | null) => {
  const n = (name || "").toLowerCase();
  const k = Object.keys(DOT).find((c) => n.includes(c));
  return k ? DOT[k] : null;
};

export default function ProductCard({ p, variants }: { p: Product; variants?: Product[] }) {
  const discount = p.mrp && p.mrp > p.price ? Math.round((1 - p.price / p.mrp) * 100) : 0;
  const [wished, setWished] = useState(false);

  useEffect(() => {
    setWished(inWishlist(p.slug));
    const sync = () => setWished(inWishlist(p.slug));
    window.addEventListener("awafi-wish-change", sync);
    return () => window.removeEventListener("awafi-wish-change", sync);
  }, [p.slug]);

  function addToCart() {
    addItem({ id: p.slug, name: p.name, brand: p.brand, price: p.price, image: p.image || "", qty: 1 });
  }

  function toggleWish() {
    setWished(toggleWishlist({ id: p.id, slug: p.slug, name: p.name, brand: p.brand, price: p.price, oldPrice: p.mrp ?? null, image: p.image || "" }));
  }

  return (
    <article className="pb-card">
      <Link href={`/portal/product/${p.slug}`} className="pb-card-media">
        {discount > 0 && <span className="pb-badge pb-badge--sale">-{discount}%</span>}
        {/* eslint-disable-next-line @next/next/no-img-element */}
        {p.image ? (
          <img className="pb-card-img" src={p.image} alt={`${p.brand} ${p.name}`} loading="lazy" />
        ) : (
          <span className="pb-card-ph-mono">{(p.brand || "Awafi").slice(0, 2).toUpperCase()}</span>
        )}
      </Link>
      <button
        type="button"
        className={`pb-wish${wished ? " is-wished" : ""}`}
        onClick={toggleWish}
        aria-label={wished ? "Remove from wishlist" : "Add to wishlist"}
        aria-pressed={wished}
        data-wish-id={p.id}
        data-wish-slug={p.slug}
        data-wish-name={p.name}
        data-wish-brand={p.brand}
        data-wish-price={p.price}
        data-wish-old={p.mrp ?? ""}
        data-wish-image={p.image || ""}
      >
        <svg viewBox="0 0 24 24" width="18" height="18" fill={wished ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.7"><path d="M12 20s-7-4.4-9.3-8.4C1 8.5 2.4 5 5.8 5 8 5 12 7.5 12 7.5S16 5 18.2 5C21.6 5 23 8.5 21.3 11.6 19 15.6 12 20 12 20Z" /></svg>
      </button>
      <div className="pb-card-body">
        {p.brand ? (
          <Link href={`/portal/brand/${slugify(p.brand)}`} className="pb-card-brand">{p.brand}</Link>
        ) : (
          <span className="pb-card-brand">Awafi</span>
        )}
        <Link href={`/portal/product/${p.slug}`} className="pb-card-name">
          {variants && p.variant && p.name.endsWith(`, ${p.variant}`) ? p.name.slice(0, -(p.variant.length + 2)) : p.name}
        </Link>
        {variants && (
          <div className="pb-swatch-mini" aria-label={`${variants.length} options`}>
            {variants.slice(0, 6).map((v) => {
              const c = dot(v.variant);
              return c ? <i key={v.slug} style={{ background: c }} title={v.variant || ""} /> : null;
            })}
            <span>
              {variants.length} {variants.some((v) => v.variant?.startsWith("Shade")) ? "shades" : "colours"}
            </span>
          </div>
        )}
        <div className="pb-card-foot">
          <div className="pb-price">
            <span className="pb-price-now">AED {p.price}</span>
            {p.mrp && p.mrp > p.price && <span className="pb-price-was">AED {p.mrp}</span>}
          </div>
          <button
            className="pb-card-add"
            onClick={addToCart}
            aria-label={`Add ${p.name} to cart`}
            data-add-id={p.slug}
            data-add-name={p.name}
            data-add-brand={p.brand}
            data-add-price={p.price}
            data-add-image={p.image || ""}
          >
            <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14" strokeLinecap="round" /></svg>
          </button>
        </div>
      </div>
    </article>
  );
}
