/* Casa Khanya — Hi-fi shared system */

const CK = {
  estateGreen: '#2D4A1F',
  estateGreenDeep: '#1F361417',
  sage: '#4A6B3A',
  brass: '#C9A961',
  brassDeep: '#A8884A',
  ivory: '#FAF7F2',
  ivoryDim: '#F4EFE5',
  stone: '#EDE8DC',
  stoneDeep: '#DDD6C4',
  slate: '#6B6B5E',
  charcoal: '#1F2419',
};

/* Photo — uses real Unsplash imagery, falls back to warm gradient */
const PHOTO_LIBRARY = {
  green:  'https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80',     // modern villa exterior
  brass:  'https://images.unsplash.com/photo-1564013799919-ab600027ffc6?w=1600&q=80',     // warm-lit modern home
  stone:  'https://images.unsplash.com/photo-1518780664697-55e3ad937233?w=1600&q=80',     // luxury exterior
  night:  'https://images.unsplash.com/photo-1512917774080-9991f1c4c750?w=1600&q=80',     // home at dusk
  dawn:   'https://images.unsplash.com/photo-1613490493576-7fde63acd811?w=1600&q=80',     // contemporary home golden
  villa:  'https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?w=1600&q=80',     // villa
  pool:   'https://images.unsplash.com/photo-1582268611958-ebfd161ef9cf?w=1600&q=80',     // pool home
  aerial: 'https://images.unsplash.com/photo-1570129477492-45c003edd2be?w=1920&q=85',     // estate aerial
  plan:   'https://images.unsplash.com/photo-1503387762-592deb58ef4e?w=1600&q=80',        // architect plan
  fynbos: 'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=1600&q=80',     // landscape
  drone:  'https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?w=1600&q=80',        // aerial estate
  arch3d: 'https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?w=1600&q=80',
  cafe:   'https://images.unsplash.com/photo-1554118811-1e0d58224f24?w=1200&q=80',
  gym:    'https://images.unsplash.com/photo-1534438327276-14e5300c3a48?w=1200&q=80',
  kids:   'https://images.unsplash.com/photo-1597656015419-91eba974f649?w=1200&q=80',
};

const Photo = ({ caption = '', credit, tone = 'green', src, style, children, aspect, radius = 4, overlay = true, objectPosition = 'center' }) => {
  const url = src || PHOTO_LIBRARY[tone] || PHOTO_LIBRARY.green;
  return (
    <div style={{
      position: 'relative',
      background: '#1f2419',
      borderRadius: radius,
      overflow: 'hidden',
      aspectRatio: aspect,
      ...style,
    }}>
      <img src={url} alt={caption} loading="lazy"
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition }} />
      {overlay && (
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(31,36,25,0.05) 0%, rgba(31,36,25,0.15) 100%)', pointerEvents: 'none' }} />
      )}
      {credit && (
        <div style={{
          position: 'absolute', bottom: 14, right: 18,
          font: '10px "JetBrains Mono", monospace',
          color: 'rgba(250,247,242,0.7)',
          letterSpacing: '0.14em',
          textShadow: '0 1px 2px rgba(0,0,0,0.6)',
        }}>{credit}</div>
      )}
      {children}
    </div>
  );
};

/* Brass-detail rule */
const Rule = ({ color = CK.charcoal, opacity = 0.16, style }) => (
  <div style={{ height: 1, background: color, opacity, ...style }} />
);

/* Section eyebrow */
const Eyebrow = ({ children, color = CK.brass }) => (
  <div style={{
    font: '500 11px "JetBrains Mono", monospace',
    color, letterSpacing: '0.22em', textTransform: 'uppercase',
  }}>
    {children}
  </div>
);

/* Display heading */
const Display = ({ children, size = 96, color = CK.charcoal, weight = 400, italic = false, style, ...rest }) => (
  <h2 {...rest} style={{
    font: `${weight} ${size}px "Fraunces", serif`,
    fontStyle: italic ? 'italic' : 'normal',
    fontVariationSettings: '"SOFT" 50, "opsz" 144',
    color, lineHeight: 0.95, letterSpacing: '-0.025em',
    margin: 0, textWrap: 'pretty', ...style,
  }}>{children}</h2>
);

/* Body */
const Body = ({ children, size = 16, color = CK.slate, style }) => (
  <p style={{
    font: `400 ${size}px "DM Sans", sans-serif`,
    color, lineHeight: 1.55, margin: 0, textWrap: 'pretty', ...style,
  }}>{children}</p>
);

/* Mono label */
const Mono = ({ children, size = 12, color = CK.slate, style }) => (
  <span style={{
    font: `500 ${size}px "JetBrains Mono", monospace`,
    color, letterSpacing: '0.14em', textTransform: 'uppercase', ...style,
  }}>{children}</span>
);

/* Pill */
const Tag = ({ children, variant = 'outline', icon, style }) => {
  const variants = {
    outline: { bg: 'transparent', border: CK.charcoal, color: CK.charcoal },
    solid:   { bg: CK.estateGreen, border: CK.estateGreen, color: CK.ivory },
    brass:   { bg: CK.brass, border: CK.brass, color: CK.charcoal },
    ghost:   { bg: 'rgba(45,74,31,0.06)', border: 'transparent', color: CK.estateGreen },
    sage:    { bg: 'transparent', border: CK.sage + '88', color: CK.sage },
  };
  const v = variants[variant];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '6px 14px',
      background: v.bg, color: v.color,
      border: `1px solid ${v.border}`,
      borderRadius: 999,
      font: '500 13px "DM Sans", sans-serif',
      letterSpacing: '0.01em',
      ...style,
    }}>
      {icon && <span style={{ fontSize: 12 }}>{icon}</span>}
      {children}
    </span>
  );
};

/* Button */
const Button = ({ children, variant = 'primary', size = 'md', style, after }) => {
  const variants = {
    primary: { bg: CK.estateGreen, color: CK.ivory, border: CK.estateGreen },
    brass:   { bg: CK.brass, color: CK.charcoal, border: CK.brass },
    ghost:   { bg: 'transparent', color: CK.charcoal, border: CK.charcoal },
    soft:    { bg: CK.stone, color: CK.charcoal, border: CK.stoneDeep },
  };
  const v = variants[variant];
  const sizes = {
    sm: { p: '8px 16px', fs: 13 },
    md: { p: '12px 22px', fs: 14 },
    lg: { p: '16px 28px', fs: 15 },
  };
  const s = sizes[size];
  return (
    <button style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      padding: s.p,
      background: v.bg, color: v.color,
      border: `1px solid ${v.border}`,
      borderRadius: 999,
      font: `500 ${s.fs}px "DM Sans", sans-serif`,
      letterSpacing: '0.01em',
      cursor: 'pointer',
      ...style,
    }}>
      {children}
      {after && <span style={{ fontSize: s.fs - 1 }}>{after}</span>}
    </button>
  );
};

/* Compact icon: square, circle, diamond — primitives only */
const Glyph = ({ shape = 'circle', size = 12, color = CK.brass, fill = false }) => {
  const stroke = color, fillC = fill ? color : 'none';
  return (
    <svg width={size} height={size} viewBox="0 0 12 12" aria-hidden style={{ flexShrink: 0 }}>
      {shape === 'circle' && <circle cx="6" cy="6" r="4.5" fill={fillC} stroke={stroke} strokeWidth="1.2" />}
      {shape === 'square' && <rect x="1.5" y="1.5" width="9" height="9" fill={fillC} stroke={stroke} strokeWidth="1.2" />}
      {shape === 'diamond' && <rect x="3" y="3" width="6" height="6" transform="rotate(45 6 6)" fill={fillC} stroke={stroke} strokeWidth="1.2" />}
      {shape === 'arrow' && <path d="M2,6 L10,6 M7,3 L10,6 L7,9" fill="none" stroke={stroke} strokeWidth="1.2" strokeLinecap="round" />}
    </svg>
  );
};

Object.assign(window, { CK, Photo, Rule, Eyebrow, Display, Body, Mono, Tag, Button, Glyph });

/* ── Animation primitives ─────────────────────────────────────────────
 * Reveal — fades + lifts a node into view on scroll (IntersectionObserver, fires once).
 * Stagger — wraps children with incremental delays.
 * useParallax — returns a translateY based on element's scroll position.
 * <HoverCard> — subtle lift / shadow on hover.
 */
const { useState: __useState, useEffect: __useEffect, useRef: __useRef, Children: __Children, cloneElement: __cloneElement, isValidElement: __isValidElement } = React;

const Reveal = ({ children, delay = 0, y = 28, duration = 900, threshold = 0.15, once = true, as: Tag = 'div', style, className, ...rest }) => {
  const ref = __useRef(null);
  const [shown, setShown] = __useState(false);
  __useEffect(() => {
    const el = ref.current; if (!el) return;
    if (typeof IntersectionObserver === 'undefined') { setShown(true); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) { setShown(true); if (once) io.unobserve(e.target); }
        else if (!once) setShown(false);
      });
    }, { threshold, rootMargin: '0px 0px -8% 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, [once, threshold]);
  return (
    <Tag ref={ref} className={className} {...rest} style={{
      opacity: shown ? 1 : 0,
      transform: shown ? 'translate3d(0,0,0)' : `translate3d(0, ${y}px, 0)`,
      transition: `opacity ${duration}ms cubic-bezier(0.22, 1, 0.36, 1) ${delay}ms, transform ${duration}ms cubic-bezier(0.22, 1, 0.36, 1) ${delay}ms`,
      willChange: 'opacity, transform',
      ...style,
    }}>{children}</Tag>
  );
};

const Stagger = ({ children, gap = 90, initialDelay = 0, y = 22, duration = 800, threshold = 0.12, as: Tag = 'div', style, className, ...rest }) => {
  const arr = __Children.toArray(children).filter(Boolean);
  return (
    <Tag className={className} {...rest} style={style}>
      {arr.map((child, i) => (
        <Reveal key={i} delay={initialDelay + i * gap} y={y} duration={duration} threshold={threshold}>
          {child}
        </Reveal>
      ))}
    </Tag>
  );
};

/* useParallax — returns a number to use in translateY(...) — small magnitudes only */
const useParallax = (strength = 0.15) => {
  const ref = __useRef(null);
  const [y, setY] = __useState(0);
  __useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const el = ref.current; if (!el) return;
        const rect = el.getBoundingClientRect();
        const center = rect.top + rect.height / 2;
        const offset = center - window.innerHeight / 2;
        setY(-offset * strength);
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); };
  }, [strength]);
  return [ref, y];
};

/* HoverCard — gentle lift + shadow on hover. Wrap any block. */
const HoverCard = ({ children, lift = 6, scale = 1.0, glow = '0 24px 60px rgba(31,36,25,0.16)', style, className, as: Tag = 'div', ...rest }) => {
  const [hover, setHover] = __useState(false);
  return (
    <Tag
      className={className}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        transform: hover ? `translate3d(0, -${lift}px, 0) scale(${scale})` : 'translate3d(0,0,0) scale(1)',
        boxShadow: hover ? glow : 'none',
        transition: 'transform 480ms cubic-bezier(0.22, 1, 0.36, 1), box-shadow 480ms cubic-bezier(0.22, 1, 0.36, 1)',
        willChange: 'transform',
        ...style,
      }}
      {...rest}
    >{children}</Tag>
  );
};

Object.assign(window, { Reveal, Stagger, useParallax, HoverCard });

