// Shared UI primitives
const { useState, useEffect, useRef, useMemo, useCallback } = React;

function useMobile(bp = 768) {
  const [m, setM] = useState(() => window.innerWidth < bp);
  useEffect(() => {
    const fn = () => setM(window.innerWidth < bp);
    window.addEventListener("resize", fn, { passive: true });
    return () => window.removeEventListener("resize", fn);
  }, [bp]);
  return m;
}
window.useMobile = useMobile;

function Placeholder({ label, src, className = "", style = {}, children }) {
  if (src) {
    return (
      <div className={className} style={{
        position: "relative", overflow: "hidden",
        background: "var(--paper-2)", ...style,
      }}>
        <img src={src} alt={label || ""} loading="lazy"
          onError={e => { e.currentTarget.parentElement.className += " ph"; e.currentTarget.remove(); }}
          style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
        {label && (
          <div style={{
            position: "absolute", right: 10, bottom: 10,
            fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.1em",
            textTransform: "uppercase", color: "#fff",
            background: "rgba(0,0,0,.45)", padding: "3px 8px", borderRadius: 2,
            backdropFilter: "blur(3px)",
          }}>{label}</div>
        )}
        {children}
      </div>
    );
  }
  return (
    <div className={"ph " + className} data-label={label} style={style}>
      {children}
    </div>
  );
}

function Eyebrow({ children, style = {} }) {
  return <div className="eyebrow" style={style}>{children}</div>;
}

function IconStar({ filled }) {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill={filled ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.6">
      <path d="M12 3l2.7 5.8 6.3.8-4.6 4.3 1.2 6.3L12 17l-5.6 3.1 1.2-6.3L3 9.6l6.3-.8L12 3z"/>
    </svg>
  );
}

function IconSearch() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
      <circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/>
    </svg>
  );
}

function IconSun() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
      <circle cx="12" cy="12" r="4"/>
      <path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>
    </svg>
  );
}
function IconMoon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
      <path d="M21 12.5A9 9 0 1 1 11.5 3a7 7 0 0 0 9.5 9.5z"/>
    </svg>
  );
}
function IconArrow({ rotate = 0 }) {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" style={{ transform: `rotate(${rotate}deg)` }}>
      <path d="M5 12h14M13 5l7 7-7 7"/>
    </svg>
  );
}
function IconChevron({ rotate = 0 }) {
  return (
    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" style={{ transform: `rotate(${rotate}deg)` }}>
      <path d="M6 9l6 6 6-6"/>
    </svg>
  );
}
function IconClose() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
      <path d="M6 6l12 12M18 6L6 18"/>
    </svg>
  );
}
function IconHeart({ filled }) {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill={filled ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.6">
      <path d="M12 20s-7-4.35-7-10a4 4 0 0 1 7-2.65A4 4 0 0 1 19 10c0 5.65-7 10-7 10z"/>
    </svg>
  );
}

function FavoriteButton({ id }) {
  const [fav, setFav] = useState(() => {
    try {
      const list = JSON.parse(localStorage.getItem("cal:favs") || "[]");
      return list.includes(id);
    } catch { return false; }
  });
  const toggle = (e) => {
    e.preventDefault(); e.stopPropagation();
    setFav(v => {
      const next = !v;
      try {
        const list = JSON.parse(localStorage.getItem("cal:favs") || "[]");
        const upd = next ? [...new Set([...list, id])] : list.filter(x => x !== id);
        localStorage.setItem("cal:favs", JSON.stringify(upd));
        window.dispatchEvent(new CustomEvent("favsChanged", { detail: upd }));
      } catch {}
      window.showToast && window.showToast(next ? "Aggiunto ai preferiti" : "Rimosso dai preferiti");
      return next;
    });
  };
  return (
    <button
      onClick={toggle}
      aria-label={fav ? "Rimuovi dai preferiti" : "Aggiungi ai preferiti"}
      style={{
        width: 32, height: 32, borderRadius: 999,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        background: "rgba(242,237,227,.88)", color: fav ? "var(--ocra)" : "var(--ink)",
        border: "1px solid var(--line)", backdropFilter: "blur(6px)",
      }}
    >
      <IconHeart filled={fav} />
    </button>
  );
}

function SectionHeader({ kicker, title, link, linkLabel = "Vedi tutti" }) {
  return (
    <div style={{ display: "flex", alignItems: "end", justifyContent: "space-between", gap: 24, marginBottom: 64, flexWrap: "wrap" }}>
      <div>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
          <div style={{ width: 28, height: 1, background: "var(--ocra)" }} />
          <Eyebrow>{kicker}</Eyebrow>
        </div>
        <h2 style={{
          fontFamily: "var(--font-display)",
          fontSize: "clamp(32px, 4vw, 56px)",
          fontWeight: 500,
          lineHeight: 1.1,
          margin: 0,
          paddingBottom: "0.15em",
          letterSpacing: "-0.01em",
          maxWidth: 780,
        }}>{title}</h2>
      </div>
      {link && (
        <a href="#" style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          fontSize: 13, fontWeight: 500, letterSpacing: "0.06em",
          textTransform: "uppercase", paddingBottom: 6,
          borderBottom: "1px solid currentColor",
        }}>{linkLabel} <IconArrow /></a>
      )}
    </div>
  );
}

function showToast(msg) {
  const t = document.getElementById("toast");
  if (!t) return;
  t.textContent = msg;
  t.classList.add("on");
  clearTimeout(window.__toastTO);
  window.__toastTO = setTimeout(() => t.classList.remove("on"), 1800);
}
window.showToast = showToast;

Object.assign(window, {
  Placeholder, Eyebrow, SectionHeader, FavoriteButton,
  IconStar, IconSearch, IconSun, IconMoon, IconArrow, IconChevron, IconClose, IconHeart
});
