// Primitives: Logo, Button, Chip, Badge, Reveal-on-scroll, ImagePlaceholder.

const { motion, AnimatePresence } = window;
const _swAssetPath = (window.SW_I18N && window.SW_I18N.assetPath) || ((p) => p);
// Resource-aware asset resolver. When the page is exported as a standalone
// (offline) bundle, the bundler populates window.__resources[id] with blob
// URLs. In normal dev/prod, that map is empty and we fall through.
const assetPath = (path) => {
  if (window.__resources && window.__resources[path]) return window.__resources[path];
  return _swAssetPath(path);
};

const Logo = ({ tone = "forest", height = 32 }) => {
  // Dark navy + sage logo art, exactly as provided by the brand.
  // For dark backgrounds we invert luminance (cream-on-dark) using a CSS filter.
  const filter =
    tone === "cream" ? "brightness(0) invert(1) opacity(.95)" : "none";
  return (
    <a href="#top" className="inline-flex items-center group" aria-label="staywise.pet">
      <img
        src={assetPath("assets/logo-trans.png")}
        alt="staywise.pet"
        style={{ height, width: "auto", filter, objectFit: "cover" }}
        draggable="false"
      />
    </a>
  );
};

const Button = ({
  as: As = "button",
  variant = "primary",
  size = "md",
  className = "",
  children,
  ...rest
}) => {
  const sizes = {
    sm: "px-3.5 py-2 text-[13px]",
    md: "px-4 py-2.5 text-[14px]",
    lg: "px-5 py-3 text-[15px]",
    xl: "px-6 py-3.5 text-[16px]",
  };
  const variants = {
    primary:
      "bg-forest text-cream hover:bg-forestDeep shadow-soft",
    coral:
      "bg-coral text-white hover:brightness-95 shadow-soft",
    ghost:
      "bg-transparent text-forest hover:bg-mint/60",
    outline:
      "bg-transparent text-forest border border-forest/20 hover:border-forest/40 hover:bg-cream",
    soft:
      "bg-mint text-forest hover:bg-mintDeep",
    chip:
      "bg-cream border border-line text-ink hover:border-forest/30",
  };
  return (
    <As
      className={`inline-flex items-center justify-center gap-2 rounded-full font-medium transition-all active:scale-[.98] ${sizes[size]} ${variants[variant]} ${className}`}
      {...rest}
    >
      {children}
    </As>
  );
};

const Chip = ({ active, onClick, icon, children, tone = "default" }) => {
  const base =
    "inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-[13px] transition-all border select-none";
  const styles = active
    ? "bg-forest text-cream border-forest"
    : tone === "mint"
    ? "bg-mint/70 text-forest border-mintDeep/70 hover:bg-mint"
    : "bg-cream text-ink border-line hover:border-forest/30";
  return (
    <motion.button
      whileTap={{ scale: 0.96 }}
      onClick={onClick}
      className={`${base} ${styles}`}
      aria-pressed={!!active}
    >
      <span className="inline-flex items-center gap-1.5 whitespace-nowrap">
        {icon}
        {children}
      </span>
    </motion.button>
  );
};

const Badge = ({ icon, children, tone = "mint" }) => {
  const tones = {
    mint: "bg-mint text-forest",
    cream: "bg-creamSoft text-forest",
    coral: "bg-coralSoft text-[#8a2f17]",
    butter: "bg-butter text-[#6a4f00]",
    forest: "bg-forest text-cream",
    white: "bg-white text-forest border border-line",
  };
  return (
    <span
      className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[12px] font-medium ${tones[tone]}`}
    >
      {icon}
      {children}
    </span>
  );
};

// Reveal on scroll using IntersectionObserver
const Reveal = ({ children, delay = 0, y = 18, className = "", as: As = "div" }) => {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setShown(true);
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -40px 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <As
      ref={ref}
      style={{
        opacity: shown ? 1 : 0,
        transform: shown ? "translateY(0)" : `translateY(${y}px)`,
        transition: `opacity .7s ${delay}ms ease, transform .7s ${delay}ms cubic-bezier(.2,.7,.2,1)`,
        willChange: "opacity, transform",
      }}
      className={className}
    >
      {children}
    </As>
  );
};

// Curated, stable Unsplash photo IDs grouped by category.
// We append crop/quality params to keep them small and consistent.
const UNSPLASH_BY_CATEGORY = {
  // cozy pet-friendly home / hosting interiors
  host: [
    "photo-1560448204-e02f11c3d0e2", // bright living room
    "photo-1502672260266-1c1ef2d93688", // cozy modern interior
    "photo-1505691938895-1758d7feb511", // wood + plants living
    "photo-1493809842364-78817add7ffb", // light scandi room
    "photo-1416331108676-a22ccb276e35", // garden / yard
    "photo-1556909114-f6e7ad7d3136", // farmhouse kitchen
    "photo-1556228720-195a672e8a03", // master bedroom
  ],
  dog: [
    "photo-1543466835-00a7907e9de1", // golden retriever portrait
    "photo-1583337130417-3346a1be7dee", // dog on bed
    "photo-1601758228041-f3b2795255f1", // happy dog outdoors
    "photo-1587300003388-59208cc962cb", // dog with toy
    "photo-1561037404-61cd46aa615b", // brown small dog
    "photo-1517423440428-a5a00ad493e8", // dog being walked
  ],
  cat: [
    "photo-1514888286974-6c03e2ca1dba", // orange cat sleeping
    "photo-1573865526739-10659fec78a5", // grey cat looking
    "photo-1574144611937-0df059b5ef3e", // tabby cat
  ],
  person: [
    "photo-1544005313-94ddf0286df2", // smiling woman
    "photo-1502685104226-ee32379fefbe", // friendly man
    "photo-1539571696357-5a69c17a67c6", // woman portrait
    "photo-1500648767791-00dcc994a43e", // bearded man portrait
    "photo-1546961342-1e7e11d09c1a", // young woman
    "photo-1531123897727-8f129e1688ce", // older man portrait
  ],
  walk: [
    "photo-1450778869180-41d0601e046e", // person walking dogs in park
    "photo-1507146426996-ef05306b995a", // dog on leash autumn
  ],
  yard: [
    "photo-1416331108676-a22ccb276e35", // fenced garden / backyard (confirmed)
    "photo-1599686301992-7a5e67b5e3e0", // simple green lawn backyard
  ],
  dogpark: [
    "photo-1548199973-03cce0bbc87b", // two retrievers running freely in park
    "photo-1507146426996-ef05306b995a", // dog on leash in park
    "photo-1601758228041-f3b2795255f1", // happy dog playing outdoors
  ],
};

const photoSrc = (category, idx = 0, w = 800) => {
  const list = UNSPLASH_BY_CATEGORY[category] || UNSPLASH_BY_CATEGORY.host;
  const id = list[idx % list.length];
  const resKey = `unsplash-${id}`;
  if (window.__resources && window.__resources[resKey]) return window.__resources[resKey];
  return `https://images.unsplash.com/${id}?auto=format&fit=crop&w=${w}&q=70`;
};

// Photo — renders a real image when `src` (URL) or `cat` (category) is provided.
// Falls back to a striped placeholder so layouts always have something to render.
const Photo = ({
  ratio = "4 / 3",
  label,
  tone = "forest",
  className = "",
  children,
  rounded = "rounded-2xl",
  src,
  cat,
  idx = 0,
  w = 800,
  alt = "",
  objectPosition = "center",
}) => {
  const finalSrc = src ? assetPath(src) : (cat ? photoSrc(cat, idx, w) : null);
  return (
    <div
      className={`relative overflow-hidden ${rounded} ${className}`}
      style={{ aspectRatio: ratio, background: tone === "mint" ? "#CCFBF1" : "#E2E8F0" }}
    >
      {finalSrc ? (
        <img
          src={finalSrc}
          alt={alt}
          loading="lazy"
          draggable="false"
          className="absolute inset-0 w-full h-full object-cover"
          style={{ objectPosition }}
          onError={(e) => { e.currentTarget.style.display = "none"; }}
        />
      ) : (
        <div className="absolute inset-0 ph-stripes" />
      )}
      {label && (
        <div className="absolute left-3 bottom-3 px-2 py-1 rounded-md bg-white/85 backdrop-blur-sm text-forest text-[10.5px] font-mono tracking-tight">
          {label}
        </div>
      )}
      {children}
    </div>
  );
};

// Section wrapper with consistent padding
const Section = ({ id, eyebrow, title, kicker, children, className = "", maxW = "max-w-7xl mx-auto" }) => (
  <section id={id} className={`relative px-5 sm:px-8 lg:px-12 ${className}`}>
    <div className={maxW}>
      {(eyebrow || title || kicker) && (
        <div className="mb-10 sm:mb-14 max-w-3xl mx-auto text-center">
          {eyebrow && (
            <Reveal>
              <div className="inline-flex items-center gap-2 mb-4 px-3 py-1 rounded-full bg-mint text-forest text-[12px] font-medium">
                <span className="w-1.5 h-1.5 rounded-full bg-coral" />
                {eyebrow}
              </div>
            </Reveal>
          )}
          {title && (
            <Reveal delay={60}>
              <h2 className="font-display text-[34px] sm:text-[44px] lg:text-[52px] leading-[1.02] text-forestDeep">
                {title}
              </h2>
            </Reveal>
          )}
          {kicker && (
            <Reveal delay={120}>
              <p className="mt-4 text-[16px] sm:text-[17px] text-inkSoft max-w-2xl mx-auto text-pretty">
                {kicker}
              </p>
            </Reveal>
          )}
        </div>
      )}
      {children}
    </div>
  </section>
);

Object.assign(window, { Logo, Button, Chip, Badge, Reveal, Photo, Section, photoSrc, UNSPLASH_BY_CATEGORY });
