// Shared primitives for all 3 homepage concepts — photo placeholders, icons, form bits.
// Uses CSS vars from ../colors_and_type.css and Lucide global.

// Detect touch / mobile viewport ONCE — all interactive wrappers short-circuit
// to their "settled" end state when this is true. This keeps the mobile
// experience completely static (no reveals, no hover lifts, no word cycling).
const IS_MOBILE = (() => {
  if (typeof window === "undefined") return false;
  const narrow = window.matchMedia && window.matchMedia("(max-width: 720px)").matches;
  const touch  = window.matchMedia && window.matchMedia("(hover: none) and (pointer: coarse)").matches;
  return !!(narrow || touch);
})();

// Warm cinematic photo placeholder — layered radial gradients, subtle noise/grain via gradients.
const Photo = ({tone="dusk", h="100%", w="100%", caption, children, src, alt="", pos="center"}) => {
  if (src) {
    return (
      <div style={{width:w, height:h, position:"relative", overflow:"hidden", background:"var(--epa-charcoal)"}}>
        <img src={src} alt={alt} loading="lazy" style={{
          position:"absolute", inset:0, width:"100%", height:"100%",
          objectFit:"cover", objectPosition: pos,
          filter:"saturate(.92) contrast(1.02)"}}/>
        {/* warm gold tone wash to unify with palette */}
        <div aria-hidden style={{position:"absolute", inset:0,
          background:"linear-gradient(180deg, rgba(15,10,6,0) 70%, rgba(15,10,6,.15) 100%)",
          mixBlendMode:"multiply"}}/>
        {caption && (
          <div style={{position:"absolute", bottom:24, left:28,
            font:"italic 400 13px/1.3 var(--font-editorial)", color:"var(--epa-champagne)",
            textShadow:"0 2px 12px rgba(0,0,0,.7)", maxWidth:"70%"}}>
            {caption}
          </div>
        )}
        {children}
      </div>
    );
  }
  const tones = {
    dusk:   "radial-gradient(ellipse at 70% 30%, rgba(242,222,164,.22), transparent 50%), radial-gradient(circle at 30% 80%, rgba(134,103,65,.28), transparent 55%), linear-gradient(155deg,#3a2a1b 0%,#1a120b 55%,#0f0a06 100%)",
    mediterranean: "radial-gradient(ellipse at 50% 20%, rgba(217,192,137,.18), transparent 60%), linear-gradient(180deg,#2a2018 0%,#16100a 70%,#0a0705 100%)",
    alpine: "radial-gradient(ellipse at 40% 40%, rgba(245,239,224,.12), transparent 55%), linear-gradient(170deg,#1e1812 0%,#0f0a06 100%)",
    gold:   "radial-gradient(circle at 50% 50%, rgba(192,163,111,.35), transparent 55%), linear-gradient(135deg,#5a3f22,#1a120b 75%)",
    ember:  "radial-gradient(ellipse at 30% 70%, rgba(192,163,111,.20), transparent 50%), linear-gradient(170deg,#3a2a1b,#0f0a06 80%)",
    warm:   "radial-gradient(ellipse at 60% 40%, rgba(170,135,87,.30), transparent 55%), linear-gradient(180deg,#4a3520,#1a120b 80%)",
    night:  "radial-gradient(circle at 80% 20%, rgba(192,163,111,.10), transparent 50%), linear-gradient(180deg,#0f0a06 0%,#060403 100%)"
  };
  return (
    <div style={{width:w, height:h, background:tones[tone] || tones.dusk, position:"relative", overflow:"hidden"}}>
      {/* subtle film grain */}
      <div style={{position:"absolute", inset:0, opacity:.25,
        background:"radial-gradient(rgba(255,255,255,.015) 1px, transparent 1px)",
        backgroundSize:"3px 3px", mixBlendMode:"overlay"}}/>
      {children}
      {caption && (
        <div style={{position:"absolute", bottom:24, left:28,
          font:"italic 400 13px/1.3 var(--font-editorial)", color:"var(--epa-champagne)",
          textShadow:"0 2px 12px rgba(0,0,0,.5)", maxWidth:"70%"}}>
          {caption}
        </div>
      )}
    </div>
  );
};

// Gold arabesque divider (two lines + center diamond)
const Arabesque = ({w=200, color="var(--epa-gold)"}) => (
  <svg viewBox="0 0 200 12" style={{width:w, height:12}}>
    <line x1="0" y1="6" x2="86" y2="6" stroke={color} strokeWidth=".6"/>
    <line x1="114" y1="6" x2="200" y2="6" stroke={color} strokeWidth=".6"/>
    <path d="M100 2 L105 6 L100 10 L95 6 Z" fill={color}/>
  </svg>
);

// EPA heraldic emblem — real logo PNG (on dark backgrounds only; has built-in gold stroke)
const Emblem = ({size=48}) => (
  <img src="assets/epa-logo.png" alt="Elite Private Agency"
    width={size} height={size}
    style={{display:"block", width:size, height:size, objectFit:"contain"}}/>
);

// Rotating word (auto-cycle) — static on mobile, shows first word only
const RotatingWord = ({words, interval=2400, style}) => {
  const [i, setI] = React.useState(0);
  React.useEffect(() => {
    if (IS_MOBILE) return;
    const t = setInterval(() => setI(x => (x+1)%words.length), interval);
    return () => clearInterval(t);
  }, [words.length, interval]);
  return <span style={{...style, display:"inline-block", minWidth:"6ch"}}>{words[i]}</span>;
};

// Gold hairline button — used in all concepts
const HairlineBtn = ({children, filled=false, size="md", onClick, href}) => {
  const sizes = {sm:{p:"10px 18px", f:11}, md:{p:"14px 26px", f:12}, lg:{p:"18px 34px", f:13}}[size];
  const css = {
    background: filled ? "var(--epa-gold)" : "transparent",
    color: filled ? "var(--epa-charcoal)" : "var(--epa-champagne)",
    border:`1px solid ${filled ? "var(--epa-gold)" : "var(--epa-gold-dark)"}`,
    padding:sizes.p, font:`500 ${sizes.f}px/1 var(--font-ui)`,
    letterSpacing:".24em", textTransform:"uppercase", cursor:"pointer",
    transition:"all .22s", borderRadius:0, display:"inline-flex", alignItems:"center", gap:12,
    textDecoration:"none"
  };
  const handlers = {
    onMouseEnter:e=>{if(!filled){e.currentTarget.style.background="var(--epa-gold)";e.currentTarget.style.color="var(--epa-charcoal)"}},
    onMouseLeave:e=>{if(!filled){e.currentTarget.style.background="transparent";e.currentTarget.style.color="var(--epa-champagne)"}}
  };
  if (href) return <a href={href} style={css} {...handlers}>{children}</a>;
  return <button onClick={onClick} style={css} {...handlers}>{children}</button>;
};

// Lang / country pill switcher — hover swaps active side
const LangToggle = ({current = "EN"}) => {
  const [hover, setHover] = React.useState(null);
  const active = hover || current;
  const col = (code) => active === code ? "var(--epa-gold)" : "var(--epa-text-secondary)";
  const itemStyle = (code) => ({
    color: col(code),
    cursor: "pointer",
    transition: "color .35s ease",
    padding: "2px 0",
  });
  return (
    <div style={{display:"flex", gap:2, font:"500 11px/1 var(--font-ui)", letterSpacing:".2em"}}>
      <span style={itemStyle("EN")}
        onMouseEnter={() => setHover("EN")} onMouseLeave={() => setHover(null)}>EN</span>
      <span style={{color:"var(--epa-text-secondary)"}}>/</span>
      <span style={itemStyle("FR")}
        onMouseEnter={() => setHover("FR")} onMouseLeave={() => setHover(null)}>FR</span>
    </div>
  );
};

// Scroll-reveal hook — fades/translates in when element enters viewport.
// On mobile: skip observer, return shown=true immediately (static page).
const useReveal = (threshold = 0.15) => {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(IS_MOBILE);
  React.useEffect(() => {
    if (IS_MOBILE || !ref.current || shown) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setShown(true); io.disconnect(); }
    }, {threshold});
    io.observe(ref.current);
    return () => io.disconnect();
  }, [shown, threshold]);
  return [ref, shown];
};

// Inline reveal wrapper — applies fade+rise on scroll. Pass `d` (seconds) for stagger.
// On mobile: renders immediately, no transitions.
const Reveal = ({children, d=0, y=24, threshold=0.15, style}) => {
  const [ref, shown] = useReveal(threshold);
  if (IS_MOBILE) return <div style={style}>{children}</div>;
  return (
    <div ref={ref} style={{
      opacity: shown ? 1 : 0,
      transform: shown ? "translateY(0)" : `translateY(${y}px)`,
      transition: `opacity .9s cubic-bezier(.22,.61,.36,1) ${d}s, transform 1s cubic-bezier(.22,.61,.36,1) ${d}s`,
      ...style
    }}>{children}</div>
  );
};

// Hover-lift wrapper — subtle rise + border warm on hover. No-op on mobile.
const Lift = ({children, y=-3, style}) => {
  const [h, setH] = React.useState(false);
  if (IS_MOBILE) return <div style={style}>{children}</div>;
  return (
    <div
      onMouseEnter={()=>setH(true)}
      onMouseLeave={()=>setH(false)}
      style={{
        transform: h ? `translateY(${y}px)` : "translateY(0)",
        transition:"transform .5s cubic-bezier(.22,.61,.36,1), box-shadow .5s ease, border-color .4s ease",
        boxShadow: h ? "0 28px 50px -22px rgba(0,0,0,.7)" : "0 0 0 rgba(0,0,0,0)",
        ...style
      }}>{children}</div>
  );
};

Object.assign(window, {Photo, Arabesque, Emblem, RotatingWord, HairlineBtn, LangToggle, useReveal, Reveal, Lift, IS_MOBILE});
