"use client";
import { createContext, useContext, useEffect, useState, useCallback } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";

type Item = { id: number; qty: number };
type Ctx = { cart: Item[]; saved: Item[]; wish: number[]; add: (id: number, qty?: number) => void; setQty: (id: number, qty: number) => void; remove: (id: number) => void; clear: () => void; toggleWish: (id: number) => void; saveForLater: (id: number) => void; moveToCart: (id: number) => void; toast: (m: string) => void };
const C = createContext<Ctx | null>(null);
export const useCart = () => useContext(C)!;

function load<T>(k: string, d: T): T { try { return JSON.parse(localStorage.getItem(k) || "") as T; } catch { return d; } }

export function CartProvider({ children }: { children: React.ReactNode }) {
  const [cart, setCart] = useState<Item[]>([]);
  const [saved, setSaved] = useState<Item[]>([]);
  const [wish, setWish] = useState<number[]>([]);
  const [msg, setMsg] = useState<string | null>(null);
  useEffect(() => { setCart(load("mfp_cart", [])); setSaved(load("mfp_saved", [])); setWish(load("mfp_wish", [])); }, []);
  const persist = (k: string, v: unknown) => localStorage.setItem(k, JSON.stringify(v));
  const toast = useCallback((m: string) => { setMsg(m); setTimeout(() => setMsg(null), 2600); }, []);
  const upd = (n: Item[]) => { setCart(n); persist("mfp_cart", n); };
  const ctx: Ctx = {
    cart, saved, wish, toast,
    add: (id, qty = 1) => { const ex = cart.find((i) => i.id === id); upd(ex ? cart.map((i) => (i.id === id ? { ...i, qty: i.qty + qty } : i)) : [...cart, { id, qty }]); toast("Added to cart ✓"); },
    setQty: (id, qty) => upd(cart.map((i) => (i.id === id ? { ...i, qty: Math.max(1, qty) } : i))),
    remove: (id) => upd(cart.filter((i) => i.id !== id)),
    clear: () => upd([]),
    toggleWish: (id) => { const n = wish.includes(id) ? wish.filter((x) => x !== id) : [...wish, id]; setWish(n); persist("mfp_wish", n); toast(wish.includes(id) ? "Removed from wishlist" : "Saved to wishlist ♥"); },
    saveForLater: (id) => { const it = cart.find((i) => i.id === id); if (!it) return; upd(cart.filter((i) => i.id !== id)); const n = [...saved.filter((s) => s.id !== id), it]; setSaved(n); persist("mfp_saved", n); },
    moveToCart: (id) => { const it = saved.find((i) => i.id === id); const n = saved.filter((s) => s.id !== id); setSaved(n); persist("mfp_saved", n); if (it) upd([...cart.filter((c) => c.id !== id), it]); },
  };
  return (
    <C.Provider value={ctx}>
      {children}
      {msg && <div className="fixed bottom-24 left-1/2 -translate-x-1/2 z-[60] bg-ink text-white px-5 py-3 rounded-full shadow-xl text-sm font-medium anim-fade-up">{msg}</div>}
    </C.Provider>
  );
}

export function CartCount() {
  const { cart } = useCart();
  const n = cart.reduce((a, i) => a + i.qty, 0);
  return n ? <span key={n} className="absolute -top-1.5 -right-1.5 bg-brand text-white text-[10px] font-bold rounded-full min-w-[18px] h-[18px] grid place-items-center px-1 anim-pop">{n}</span> : null;
}
export function WishCount() {
  const { wish } = useCart();
  return wish.length ? <span className="absolute -top-1.5 -right-1.5 bg-royal text-white text-[10px] font-bold rounded-full min-w-[18px] h-[18px] grid place-items-center">{wish.length}</span> : null;
}

export function AddToCart({ id, disabled, label = "Add to Cart", qtyPicker = false, className = "" }: { id: number; disabled?: boolean; label?: string; qtyPicker?: boolean; className?: string }) {
  const { add } = useCart();
  const [q, setQ] = useState(1);
  return (
    <div className={`flex gap-2 ${className}`}>
      {qtyPicker && (
        <div className="flex items-center border rounded-full overflow-hidden">
          <button type="button" className="px-3 py-2" onClick={() => setQ(Math.max(1, q - 1))}>−</button>
          <span className="w-8 text-center font-semibold">{q}</span>
          <button type="button" className="px-3 py-2" onClick={() => setQ(q + 1)}>+</button>
        </div>
      )}
      <button type="button" disabled={disabled} onClick={() => add(id, q)} className="btn btn-green flex-1 !py-2.5">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6h15l-1.5 9h-12z M6 6 5 3H2 M9 20a1 1 0 1 0 0 .01 M18 20a1 1 0 1 0 0 .01" /></svg>
        {label}
      </button>
    </div>
  );
}

export function WishButton({ id, className = "" }: { id: number; className?: string }) {
  const { wish, toggleWish } = useCart();
  const on = wish.includes(id);
  return (
    <button type="button" aria-label="Wishlist" onClick={() => toggleWish(id)} className={`w-9 h-9 grid place-items-center rounded-full bg-white shadow-sm border hover:scale-110 transition ${className}`}>
      <svg key={String(on)} className={on ? "anim-pop" : ""} width="17" height="17" viewBox="0 0 24 24" fill={on ? "#e11d48" : "none"} stroke={on ? "#e11d48" : "#64748b"} strokeWidth="2"><path d="M12 21s-7-4.5-9.5-9A5.5 5.5 0 0 1 12 6a5.5 5.5 0 0 1 9.5 6C19 16.5 12 21 12 21z" /></svg>
    </button>
  );
}

export function SearchBar({ categories }: { categories: { name: string; slug: string }[] }) {
  const r = useRouter();
  const [q, setQ] = useState(""); const [cat, setCat] = useState("");
  return (
    <form onSubmit={(e) => { e.preventDefault(); r.push(`/shop?q=${encodeURIComponent(q)}${cat ? `&category=${cat}` : ""}`); }} className="flex w-full items-center bg-cloud rounded-full border border-transparent focus-within:border-brand focus-within:bg-white transition overflow-hidden">
      <select value={cat} onChange={(e) => setCat(e.target.value)} className="hidden md:block bg-transparent text-sm font-medium pl-5 pr-2 py-3 outline-none border-r border-slate-200 max-w-[170px]">
        <option value="">All Categories</option>
        {categories.map((c) => <option key={c.slug} value={c.slug}>{c.name}</option>)}
      </select>
      <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search medicines, vitamins, baby care…" className="flex-1 bg-transparent px-4 py-3 text-sm outline-none min-w-0" />
      <button className="m-1 bg-brand text-white rounded-full w-10 h-10 grid place-items-center shrink-0" aria-label="Search">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></svg>
      </button>
    </form>
  );
}

export function MobileMenu({ links }: { links: { href: string; label: string }[] }) {
  const [open, setOpen] = useState(false);
  return (
    <>
      <button className="lg:hidden w-10 h-10 grid place-items-center rounded-full hover:bg-cloud" onClick={() => setOpen(true)} aria-label="Menu">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 6h16M4 12h16M4 18h16" /></svg>
      </button>
      {open && (
        <div className="fixed inset-0 z-[70] lg:hidden">
          <div className="absolute inset-0 bg-black/40 anim-fade" onClick={() => setOpen(false)} />
          <nav className="absolute right-0 top-0 h-full w-[82%] max-w-sm bg-white p-6 overflow-y-auto anim-slide-in">
            <button className="mb-6 text-sm font-semibold text-slate-500" onClick={() => setOpen(false)}>✕ Close</button>
            {links.map((l) => <Link key={l.href} href={l.href} onClick={() => setOpen(false)} className="block py-3 border-b font-semibold hover:text-brand">{l.label}</Link>)}
          </nav>
        </div>
      )}
    </>
  );
}

export function Announcements({ items }: { items: string[] }) {
  const [i, setI] = useState(0);
  useEffect(() => { if (items.length < 2) return; const t = setInterval(() => setI((x) => (x + 1) % items.length), 4000); return () => clearInterval(t); }, [items.length]);
  if (!items.length) return null;
  return <div className="bg-royal text-white text-center text-xs sm:text-sm font-medium py-2 px-4"><span key={i} className="inline-block anim-fade-up">{items[i]}</span></div>;
}

type Slide = { id: number; heading: string; description: string; buttonText: string; buttonLink: string; image: string };
export function HeroSlider({ slides }: { slides: Slide[] }) {
  const [i, setI] = useState(0);
  useEffect(() => { if (slides.length < 2) return; const t = setInterval(() => setI((x) => (x + 1) % slides.length), 6500); return () => clearInterval(t); }, [slides.length]);
  if (!slides.length) return null;
  const s = slides[i];
  return (
    <section className="container-x pt-5">
      <div className="relative overflow-hidden rounded-[1.75rem] bg-mint min-h-[380px] md:min-h-[460px] grid md:grid-cols-2">
        <div key={"t" + i} className="relative z-10 p-8 md:p-14 flex flex-col justify-center anim-fade-up">
          <span className="inline-flex w-fit items-center gap-2 bg-white text-brand text-xs font-bold px-3 py-1.5 rounded-full mb-5 shadow-sm">● Trusted Family Pharmacy · Kalisizo</span>
          <h1 className="text-3xl md:text-5xl font-extrabold leading-[1.1] tracking-tight text-ink">{s.heading}</h1>
          <p className="mt-4 text-slate-600 md:text-lg max-w-md">{s.description}</p>
          <div className="mt-7 flex gap-3 flex-wrap">
            <Link href={s.buttonLink} className="btn btn-green !px-7 !py-3">{s.buttonText} →</Link>
            <Link href="/prescription" className="btn btn-outline !px-6 !py-3">Upload Prescription</Link>
          </div>
        </div>
        <div className="relative min-h-[220px]">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img key={"i" + i} src={s.image} alt={s.heading} className="absolute inset-0 w-full h-full object-cover anim-kenburns md:rounded-l-[2rem]" fetchPriority="high" />
          <div className="absolute inset-0 bg-gradient-to-r from-mint/60 to-transparent md:from-mint md:via-transparent" />
        </div>
        <div className="absolute bottom-5 left-8 md:left-14 z-20 flex gap-2">
          {slides.map((_, k) => <button key={k} aria-label={`Slide ${k + 1}`} onClick={() => setI(k)} className={`h-2 rounded-full transition-all ${k === i ? "w-8 bg-brand" : "w-2 bg-brand/30"}`} />)}
        </div>
      </div>
    </section>
  );
}

export function Reveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((es) => es.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } }), { threshold: 0.1 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
  return null;
}

export function Counter({ to, suffix = "" }: { to: number; suffix?: string }) {
  const [n, setN] = useState(0);
  useEffect(() => { let v = 0; const step = Math.max(1, Math.ceil(to / 40)); const t = setInterval(() => { v = Math.min(to, v + step); setN(v); if (v >= to) clearInterval(t); }, 30); return () => clearInterval(t); }, [to]);
  return <>{n.toLocaleString()}{suffix}</>;
}
