// shared.jsx — small shared building blocks

const { useState, useEffect, useRef, useCallback, useMemo } = React;

// === Brand colors used inline ===
const COLORS = {
  navy: '#1f3a5f',
  navyDeep: '#16294a',
  gold: '#b89968',
  bone: '#f6f2ec',
  paper: '#faf8f4'
};

// === Inline SVG logo (uses currentColor) ===
function RigginsLogo({ color = '#1f3a5f', height = 84 }) {
  // Use the user-supplied logo PNG directly — white variant for dark backgrounds
  const isWhite = color === '#fff' || color === '#ffffff' || color === 'white';
  const src = isWhite ? 'assets/riggins-logo-white.png' : 'assets/riggins-logo.png';
  return (
    <img
      src={src}
      alt="Riggins Design + Build"
      style={{ height, width: 'auto', display: 'block' }}
    />
  );
}

// === Navigation ===
function Nav({ page, onNavigate, transparent }) {
  const [solid, setSolid] = useState(!transparent);
  const [drawerOpen, setDrawerOpen] = useState(false);

  useEffect(() => {
    if (!transparent) {
      setSolid(true);
      return;
    }
    const onScroll = () => setSolid(window.scrollY > 80);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [transparent]);

  useEffect(() => {
    document.body.classList.toggle('drawer-open', drawerOpen);
    return () => document.body.classList.remove('drawer-open');
  }, [drawerOpen]);

  const go = (id) => {
    setDrawerOpen(false);
    onNavigate(id);
  };

  return (
    <React.Fragment>
      <nav className={`nav ${solid ? 'is-solid' : 'is-overlay'}`}>
        <div className="nav__group nav__group--left">
          <a className={`nav__link ${page === 'portal' ? 'is-active' : ''}`} onClick={() => go('portal')}>
            Client Portal
          </a>
          <a className={`nav__link ${page === 'projects' ? 'is-active' : ''}`} onClick={() => go('projects')}>
            Projects
          </a>
        </div>
        <a
          className="nav__logo"
          onClick={() => go('home')}
          aria-label="Riggins Design + Build — Home"
        >
          <RigginsLogo color={solid ? COLORS.navy : '#fff'} height="100%" />
        </a>
        <div className="nav__group nav__group--right">
          <a className={`nav__link ${page === 'about' ? 'is-active' : ''}`} onClick={() => go('about')}>
            About
          </a>
          <a className={`nav__link ${page === 'reps' ? 'is-active' : ''}`} onClick={() => go('reps')}>
            Builder Reps
          </a>
          <a className={`nav__link ${page === 'contact' ? 'is-active' : ''}`} onClick={() => go('contact')}>
            Contact
          </a>
          <button
            className="nav__hamburger"
            onClick={() => setDrawerOpen(true)}
            aria-label="Open menu"
          >
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <line x1="3" y1="6" x2="21" y2="6" />
              <line x1="3" y1="12" x2="21" y2="12" />
              <line x1="3" y1="18" x2="21" y2="18" />
            </svg>
          </button>
        </div>
      </nav>

      <div className={`drawer ${drawerOpen ? 'is-open' : ''}`}>
        <button className="drawer__close" onClick={() => setDrawerOpen(false)} aria-label="Close">
          ×
        </button>
        <nav className="drawer__nav">
          <a onClick={() => go('home')}>Home</a>
          <a onClick={() => go('portal')}>Client Portal</a>
          <a onClick={() => go('projects')}>Projects</a>
          <a onClick={() => go('about')}>About</a>
          <a onClick={() => go('reps')}>Builder Reps</a>
          <a onClick={() => go('contact')}>Contact</a>
        </nav>
      </div>
    </React.Fragment>
  );
}

// === Footer ===
function Footer({ onNavigate }) {
  const SocialIcon = ({ d }) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d={d} />
    </svg>
  );

  return (
    <footer className="footer">
      <div className="footer__logo" style={{ display: 'grid', placeItems: 'center' }}>
        <RigginsLogo height={84} />
      </div>

      <nav className="footer__nav">
        <a onClick={() => onNavigate('home')}>Home</a>
        <a onClick={() => onNavigate('projects')}>Projects</a>
        <a onClick={() => onNavigate('about')}>About</a>
        <a onClick={() => onNavigate('reps')}>Builder Reps</a>
        <a onClick={() => onNavigate('contact')}>Contact</a>
      </nav>

      <div className="footer__social">
        <a
          aria-label="Instagram"
          href="https://www.instagram.com/rigginsdesignbuild/"
          target="_blank"
          rel="noopener noreferrer"
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
            <rect x="3" y="3" width="18" height="18" rx="5" />
            <circle cx="12" cy="12" r="4" />
            <circle cx="17.5" cy="6.5" r="0.6" fill="currentColor" />
          </svg>
        </a>
        <a
          aria-label="Facebook"
          href="https://www.facebook.com/RigginsDesignBuild"
          target="_blank"
          rel="noopener noreferrer"
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
            <path d="M14 8h2.5V5H14c-2 0-3.5 1.5-3.5 3.5V11H8v3h2.5v7H14v-7h2.5l.5-3H14V8.5c0-.3.2-.5.5-.5z" />
          </svg>
        </a>
        <a
          aria-label="LinkedIn"
          href="https://www.linkedin.com/company/riggins-design-build"
          target="_blank"
          rel="noopener noreferrer"
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
            <rect x="3" y="3" width="18" height="18" rx="2" />
            <line x1="8" y1="10" x2="8" y2="17" />
            <circle cx="8" cy="7" r="0.8" fill="currentColor" />
            <path d="M12 17v-4a2 2 0 014 0v4" />
            <line x1="12" y1="10" x2="12" y2="17" />
          </svg>
        </a>
      </div>

      <p className="footer__copy">
        © 2026 Riggins Design + Build · Gainesville, FL
        <br />
        <span style={{ opacity: 0.7, fontSize: '0.85em' }}>
          Formerly Spain &amp; Cooper Homes
        </span>
      </p>
    </footer>
  );
}

// === Reveal-on-scroll wrapper ===
function Reveal({ children, delay = 0, as = 'div', ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setSeen(true);
            io.disconnect();
          }
        });
      },
      { threshold: 0.15 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const Tag = as;
  return (
    <Tag
      ref={ref}
      style={{
        opacity: seen ? 1 : 0,
        transform: seen ? 'translateY(0)' : 'translateY(24px)',
        transition: `opacity 0.9s ease ${delay}s, transform 0.9s ease ${delay}s`
      }}
      {...rest}
    >
      {children}
    </Tag>
  );
}

// Project + image catalog (uses Wexford photo for everything else falls back to placeholder gradients)
const STOCK = {
  wexford: 'assets/wexford.png'
};

// SVG placeholder generator — striped tone-on-tone with a tag
function placeholder(label, hue = 215, lit = 35) {
  const svg = `
    <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 800 1000'>
      <defs>
        <pattern id='p' patternUnits='userSpaceOnUse' width='40' height='40' patternTransform='rotate(35)'>
          <rect width='40' height='40' fill='hsl(${hue}, 18%, ${lit}%)'/>
          <line x1='0' y1='0' x2='0' y2='40' stroke='hsl(${hue}, 22%, ${lit + 6}%)' stroke-width='2'/>
        </pattern>
      </defs>
      <rect width='800' height='1000' fill='url(#p)'/>
      <g fill='hsla(0,0%,100%,0.7)' font-family='ui-monospace, monospace' font-size='18' letter-spacing='4'>
        <text x='40' y='40'>[ PLACEHOLDER ]</text>
        <text x='40' y='970'>${label}</text>
      </g>
    </svg>
  `;
  return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;
}

function projectGallery(slug, count) {
  const arr = [];
  for (let i = 1; i <= count; i++) {
    arr.push(`assets/projects/${slug}/${String(i).padStart(2, '0')}.jpg`);
  }
  return arr;
}

const PROJECTS = [
  { id: 'heathrow',         name: 'Heathrow Estate',         location: 'Heathrow',         height: 1.15, gallery: projectGallery('heathrow', 58) },
  { id: 'thomas',           name: 'Modern Farmhouse',        location: 'Wexford',          height: 1.0,  gallery: projectGallery('thomas', 19) },
  { id: 'martin',           name: 'Wexford Estate',          location: 'Wexford',          height: 1.3,  gallery: projectGallery('martin', 23) },
  { id: 'parade-2025',      name: '2025 Parade Home',        location: 'Wexford',          height: 1.1,  gallery: projectGallery('2025-parade-1', 76),  coverIdx: 19 },
  { id: 'old-oak-estates',  name: 'Old Oak Estates',         location: 'Old Oak Estates',  height: 1.05, gallery: projectGallery('old-oak-estates', 19) },
  { id: 'flint-rock',       name: 'Flint Rock Estate',       location: 'Flint Rock',       height: 1.2,  gallery: projectGallery('flint-rock', 25) },
  { id: 'rossidis',         name: 'Modern Custom Home',      location: 'Gainesville, FL', height: 1.25, gallery: projectGallery('rossidis', 12),       coverIdx: 5 },
  { id: 'wilds-plantation', name: 'Wilds Plantation Custom', location: 'Wilds Plantation', height: 1.1,  gallery: projectGallery('wilds-plantation', 32), coverIdx: 27 },
  { id: 'dennis',           name: 'Wexford Cottage',         location: 'Wexford',          height: 0.95, gallery: projectGallery('dennis', 9) },
  { id: 'heritage-modern',  name: 'Heritage Estate',         location: 'Florida',          height: 1.15, gallery: projectGallery('heritage-modern', 25), coverIdx: 2 },
  { id: 'caputo',           name: 'Custom Home at Wexford',  location: 'Wexford',          height: 1.15, gallery: projectGallery('caputo', 16) },
  { id: 'greystone',        name: 'Greystone Custom',        location: 'Greystone',        height: 1.0,  gallery: projectGallery('greystone', 10),      coverIdx: 4 },
  { id: 'shaio',            name: 'Hill Country Retreat',    location: 'Wimberley',        height: 1.2,  gallery: projectGallery('shaio', 11) },
  { id: 'nappo',            name: 'Craftsman Custom',        location: 'Wexford',          height: 1.0,  gallery: projectGallery('nappo', 9) },
  { id: 'lakeside',         name: 'Farmhouse Custom',        location: 'Florida',          height: 1.1,  gallery: projectGallery('lakeside', 25),       coverIdx: 1 },
  { id: 'riggins',          name: 'Coastal Modern',          location: 'Wexford',          height: 1.05, gallery: projectGallery('riggins', 10) },
  { id: 'old-oak',          name: 'Old Oak Custom',          location: 'Gainesville, FL', height: 1.1,  gallery: projectGallery('riggins-old-oak', 8), coverIdx: 2 },
  { id: 'ratliff',          name: 'California Custom',       location: 'California',       height: 1.25, gallery: projectGallery('ratliff', 12) },
  { id: 'merricks',         name: 'Wimberley Estate',        location: 'Gainesville, FL', height: 1.1,  gallery: projectGallery('merricks', 10),       coverIdx: 2 },
].map((p) => ({ ...p, cover: p.gallery[p.coverIdx || 0] }));

// expose to global so other Babel scripts can use
Object.assign(window, {
  React,
  COLORS,
  RigginsLogo,
  Nav,
  Footer,
  Reveal,
  PROJECTS,
  placeholder,
  STOCK
});
