// Reusable primitives: placeholder image, reveal-on-scroll, language pair, wordmark.

const { useEffect, useRef, useState, createContext, useContext } = React;

// --- i18n ---
const LangCtx = createContext({ lang: 'en', setLang: () => {} });
const useLang = () => useContext(LangCtx);

// --- Stock photo catalog (Unsplash) ---
// All editorial / tropical / coastal scenes. The Placeholder component falls back
// to the striped placeholder if an image fails to load, so the page degrades gracefully.
const U = (id, w = 1600) => `https://images.unsplash.com/photo-${id}?auto=format&fit=crop&w=${w}&q=80`;
const PHOTOS = {
  hero: U('1540541338287-41700207dee6', 2200), // palms at golden hour
  // Zones
  langosta:    U('1473625247510-8ceb1760943f', 1200), // quiet surfers' beach, golden sunset
  tamarindo:   U('1502933691298-84fc14542831', 1200), // surfer / surf town
  playagrande: U('1505228395891-9a51e7e86bf6', 1200), // long pristine beach, palms
  flamingo:    U('1507525428034-b723cf961d3e', 1200), // white-sand bay from above
  // Homes
  home1: U('1582719478250-c89cae4dc85b', 1400), // modern villa exterior
  home2: U('1564540583246-934409427776', 1400), // rooftop pool
  home3: U('1545324418-cc1a3fa10c00', 1400), // luxury villa pool
  // Sustainability
  garden: U('1416879595882-3373a0480b5b', 1200) // tropical garden
};

// Bilingual pair: English primary, Spanish secondary in italic underneath
const BiHeading = ({ en, es, className = "", esClassName = "" }) =>
<h2 className={"h-serif " + className} data-comment-anchor>
    <span dangerouslySetInnerHTML={{ __html: en }} />
    <span className={"block italic text-terracotta/90 mt-1 " + esClassName}
  dangerouslySetInnerHTML={{ __html: es }} />
  </h2>;


// Picks copy by lang
const T = ({ en, es }) => {
  const { lang } = useLang();
  return <>{lang === 'es' ? es : en}</>;
};

// --- Wordmark ---
const Wordmark = ({ tone = "dark" }) => {
  const ink = tone === "light" ? "#F2F3ED" : "#2C4A3E";
  // Pale aqua reads beautifully over the dark hero/footer; on light sand it loses contrast,
  // so we shift to the deeper Pacífico teal there.
  const accent = tone === "light" ? "rgb(178, 217, 227)" : "#1E5B6B";
  // Always points to the homepage. On the landing itself, scroll to top;
  // from any /pages/ sub-page, navigate back to the landing.
  const inPages = typeof location !== 'undefined' && location.pathname.includes('/pages/');
  const homeHref = inPages ? '/' : '#top';
  return (
    <a href={homeHref} className="select-none whitespace-nowrap leading-none" aria-label="Summer Home CR — home">
      <span className="h-serif text-[22px] md:text-[24px]" style={{ color: ink }}>Summer Home </span>
      <span className="h-serif italic text-[22px] md:text-[24px]" style={{ color: accent }}>CR</span>
    </a>);

};

// --- Reveal ---
const Reveal = ({ children, as: Tag = "div", delay = 0, className = "" }) => {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {if (e.isIntersecting) {setTimeout(() => el.classList.add('in'), delay);io.unobserve(el);}});
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return <Tag ref={ref} className={"reveal " + className}>{children}</Tag>;
};

// --- Placeholder image ---
// shape: ratio string "4/3" etc. Variant controls fill tone.
// If `src` is provided, renders the photo; falls back to striped placeholder on error.
const Placeholder = ({ label, ratio = "4/3", variant = "sand", className = "", caption = null, src = null, position = "center" }) => {
  const fill =
  variant === "green" ? "ph-stripes-green" :
  variant === "sage" ? "ph-stripes-sage" : "ph-stripes";
  const labelClass = variant === "green" || variant === "sage" ? "ph-label ph-label-light" : "ph-label";
  const [failed, setFailed] = React.useState(false);
  const showImage = src && !failed;

  return (
    <div className={"relative w-full overflow-hidden " + (showImage ? "bg-linen" : fill) + " " + className}
    style={{ aspectRatio: ratio }}
    role="img" aria-label={label}>
      {showImage &&
      <img
        src={src}
        alt={label}
        loading="lazy"
        onError={() => setFailed(true)}
        className="absolute inset-0 w-full h-full object-cover"
        style={{ objectPosition: position }} />

      }
      {!showImage && <>
        <span className={"absolute left-3 top-3 z-10 " + labelClass}>[ replace · photo ]</span>
        <span className={"absolute right-3 bottom-3 z-10 " + labelClass + " text-right max-w-[80%]"}>{label}</span>
        <svg className="absolute inset-0 w-full h-full opacity-20" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
          <line x1="0" y1="0" x2="100" y2="100" stroke={variant === "sand" ? "#3D2817" : "#F5EFE3"} strokeWidth="0.15" vectorEffect="non-scaling-stroke" />
          <line x1="100" y1="0" x2="0" y2="100" stroke={variant === "sand" ? "#3D2817" : "#F5EFE3"} strokeWidth="0.15" vectorEffect="non-scaling-stroke" />
        </svg>
        {caption && <div className={"absolute left-3 bottom-3 z-10 " + labelClass}>{caption}</div>}
      </>}
    </div>);

};

// --- Section wrapper ---
const Section = ({ id, bg = "sand", className = "", children, label }) => {
  const bgMap = {
    sand: "bg-sand", offwhite: "bg-offwhite", green: "bg-green text-offwhite",
    sage: "bg-sage text-offwhite", linen: "bg-linen"
  };
  return (
    <section id={id} data-screen-label={label} className={(bgMap[bg] || "") + " " + className}>
      {children}
    </section>);

};

// --- Container ---
const Container = ({ className = "", children }) =>
<div className={"mx-auto max-w-[1280px] px-6 md:px-10 " + className}>{children}</div>;


Object.assign(window, { LangCtx, useLang, BiHeading, T, Wordmark, Reveal, Placeholder, Section, Container, PHOTOS });