// Shared UI primitives + nav + footer + reveal-on-scroll hook.

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

// ----- Reveal on scroll -----
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(
      '.reveal:not(.in), .reveal-left:not(.in), .reveal-right:not(.in), .reveal-scale:not(.in)'
    );
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.10 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

// ----- Buttons -----
const PrimaryButton = ({ children, className = "", icon, ...rest }) => (
  <button
    className={`btn group inline-flex items-center gap-2 rounded-full bg-bone-50 text-ink-950 px-6 py-3.5 text-[13px] font-medium tracking-wide hover:bg-accent-soft ${className}`}
    {...rest}
  >
    {children}
    {icon !== false && <Icon.ArrowUpRight size={16} className="transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5" />}
  </button>
);

const GhostButton = ({ children, className = "", icon, ...rest }) => (
  <button
    className={`btn group inline-flex items-center gap-2 rounded-full bg-transparent text-bone-50 border border-bone-50/30 hover:border-bone-50/70 px-6 py-3.5 text-[13px] font-medium tracking-wide ${className}`}
    {...rest}
  >
    {icon}
    {children}
  </button>
);

// ----- Eyebrow label -----
const Eyebrow = ({ children, className = "" }) => (
  <div className={`inline-flex items-center gap-3 text-[13px] uppercase tracking-[0.22em] text-bone-50/55 ${className}`}>
    <span className="block h-px w-6 bg-bone-50/30" />
    <span>{children}</span>
  </div>
);

// ----- Section heading -----
const SectionTitle = ({ kicker, title, sub, align = "left" }) => (
  <div className={`max-w-3xl ${align === "center" ? "mx-auto text-center" : ""}`}>
    {kicker && <Eyebrow className={align === "center" ? "justify-center" : ""}>{kicker}</Eyebrow>}
    <h2 className="font-display text-[34px] sm:text-[40px] lg:text-[56px] leading-[1.02] tracking-tightest text-bone-50 mt-5">
      {title}
    </h2>
    {sub && <p className="mt-5 font-display text-bone-50/60 text-[16px] leading-relaxed max-w-xl">{sub}</p>}
  </div>
);

// ----- Marker placeholder (architectural) -----
const ArchPh = ({ variant = 1, label, className = "" }) => (
  <div className={`relative overflow-hidden ph-${variant} grain ${className}`}>
    {/* layered architectural shapes */}
    <svg viewBox="0 0 600 400" preserveAspectRatio="xMidYMid slice" className="absolute inset-0 w-full h-full opacity-[0.55]">
      <defs>
        <linearGradient id={`g${variant}`} x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#C8A86B" stopOpacity="0.18"/>
          <stop offset="100%" stopColor="#C8A86B" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {variant === 1 && (
        <g>
          <rect x="60" y="180" width="80" height="220" fill="#1a1a1c" stroke="#3a3a41"/>
          <rect x="160" y="120" width="120" height="280" fill="#1f1e1a" stroke="#3a3a41"/>
          <rect x="300" y="60" width="160" height="340" fill="#22201b" stroke="#3a3a41"/>
          <rect x="480" y="160" width="90" height="240" fill="#1c1c1f" stroke="#3a3a41"/>
          {[...Array(20)].map((_,i)=>(<line key={i} x1="0" y1={i*22} x2="600" y2={i*22} stroke="#ffffff" strokeOpacity="0.02"/>))}
          <rect x="0" y="0" width="600" height="400" fill={`url(#g${variant})`}/>
        </g>
      )}
      {variant === 2 && (
        <g>
          <path d="M0 320 L150 220 L300 280 L450 180 L600 240 L600 400 L0 400 Z" fill="#1c1b18" stroke="#3a3a41"/>
          <circle cx="120" cy="120" r="60" fill="#22201b" stroke="#3a3a41"/>
          <rect x="220" y="80" width="220" height="160" fill="#1a1916" stroke="#3a3a41"/>
          <rect x="460" y="120" width="120" height="120" fill="#1f1d18" stroke="#3a3a41"/>
          <rect x="0" y="0" width="600" height="400" fill={`url(#g${variant})`}/>
        </g>
      )}
      {variant === 3 && (
        <g>
          <path d="M50 360 L150 200 L250 360 Z" fill="#1f1d18" stroke="#3a3a41"/>
          <path d="M260 360 L380 140 L500 360 Z" fill="#1a1916" stroke="#3a3a41"/>
          <rect x="0" y="340" width="600" height="60" fill="#0e0d0c"/>
          {[...Array(18)].map((_,i)=>(<rect key={i} x={i*34} y="370" width="20" height="6" fill="#26241f"/>))}
          <rect x="0" y="0" width="600" height="400" fill={`url(#g${variant})`}/>
        </g>
      )}
      {variant === 4 && (
        <g>
          <rect x="0" y="220" width="600" height="180" fill="#13120f"/>
          <g opacity="0.85">
            <path d="M40 220 Q80 180 120 220 T200 220 T280 220 T360 220 T440 220 T520 220 T600 220" fill="none" stroke="#3a3a41"/>
            <path d="M40 240 Q80 200 120 240 T200 240 T280 240 T360 240 T440 240 T520 240 T600 240" fill="none" stroke="#3a3a41"/>
          </g>
          <g>
            <rect x="80" y="120" width="40" height="100" fill="#22201b" stroke="#3a3a41"/>
            <rect x="180" y="80" width="60" height="140" fill="#1c1b18" stroke="#3a3a41"/>
            <rect x="300" y="100" width="80" height="120" fill="#1f1d18" stroke="#3a3a41"/>
            <rect x="440" y="60" width="60" height="160" fill="#26241f" stroke="#3a3a41"/>
          </g>
          <rect x="0" y="0" width="600" height="400" fill={`url(#g${variant})`}/>
        </g>
      )}
    </svg>
    {label && (
      <div className="absolute left-5 bottom-5 text-[10px] uppercase tracking-[0.22em] text-bone-50/40">
        {label}
      </div>
    )}
  </div>
);

// ----- Logo -----
const Logo = ({ className = "", onClick }) => (
  <div onClick={onClick} className={`flex items-center gap-3 group ${onClick ? 'cursor-pointer' : ''} ${className}`} data-track="nav-home-logo">
    <div className="relative h-10 w-10 p-1.5 grid place-items-center overflow-visible">
    <img
      src="/images/logos/amg-logo-cut.png"
      alt="AMG Logo"
      className="h-full w-full object-contain"
    />
    </div>
    <div className="leading-tight">
      <div className="font-display text-[19px] tracking-tight text-bone-50">AMG</div>
      <div className="text-[9px] uppercase tracking-[0.28em] text-bone-50/45 -mt-0.5">Ashok Malhotra Group</div>
    </div>
  </div>
);

// ----- Theme toggle -----
const ThemeToggle = ({ colorMode, toggle }) => (
  <button
    onClick={toggle}
    aria-label={colorMode === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
    className="btn h-9 w-9 rounded-full border border-bone-50/15 grid place-items-center text-bone-50/70 hover:text-bone-50 hover:border-bone-50/35 hover:bg-bone-50/5 transition-colors"
  >
    {colorMode === 'dark' ? <Icon.Sun size={15}/> : <Icon.Moon size={15}/>}
  </button>
);

// ----- Nav -----
const NAV = [
  { id: 'home',        label: 'Home' },
  { id: 'commercial',  label: 'Commercial' },
  { id: 'residential', label: 'Residential' },
  { id: 'brands',      label: 'Brands' },
  { id: 'leadership',  label: 'Leadership' },
  { id: 'contact',     label: 'Contact' },
];

const Nav = ({ page, setPage, colorMode, toggleColorMode }) => {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  useEffect(() => {
    const onS = () => setScrolled(window.scrollY > 16);
    onS(); window.addEventListener('scroll', onS, { passive: true });
    return () => window.removeEventListener('scroll', onS);
  }, []);
  const go = (id) => { setPage(id); setMobileOpen(false); window.scrollTo({ top: 0, behavior: 'smooth' }); };

  const unscrolledCls = colorMode === 'light'
    ? 'py-2 bg-white/40 backdrop-blur-md border border-black/10 shadow-[0_4px_24px_rgba(0,0,0,0.10)]'
    : 'py-2 bg-black/30 backdrop-blur-md border border-white/10 shadow-[0_4px_32px_rgba(0,0,0,0.45)]';

  return (
    <header className={`fixed inset-x-0 top-0 z-50 transition-all duration-500 ${scrolled ? 'py-2' : 'py-5'}`}>
      <div className="mx-auto max-w-[1320px] px-5 sm:px-8">
        <div className={`relative flex items-center justify-between rounded-full px-4 sm:px-5 transition-all duration-500 ${scrolled ? 'glass py-2.5' : unscrolledCls}`}>
          <Logo onClick={() => go('home')} />

          <nav className="hidden md:flex items-center gap-1 absolute left-1/2 -translate-x-1/2">
            {NAV.map((n) => (
              <button
                key={n.id}
                onClick={() => go(n.id)}
                data-track={`nav-${n.id}`}
                className={`relative px-4 py-2 text-[13px] tracking-wide transition-colors ${page === n.id ? 'nav-active' : 'text-bone-50/60 hover:text-bone-50/95'}`}
              >
                {n.label}
              </button>
            ))}
          </nav>

          <div className="hidden md:flex items-center gap-2">
            <ThemeToggle colorMode={colorMode} toggle={toggleColorMode}/>
            <a
              href="https://wa.me/918968566656?text=Hi%20AMG%2C%20I%27d%20like%20to%20know%20more."
              target="_blank"
              rel="noopener noreferrer"
              data-track="nav-cta-whatsapp"
              aria-label="Chat on WhatsApp"
              className="btn group inline-flex items-center gap-2 rounded-full border border-bone-50/15 px-3.5 py-2 text-[12px] tracking-wide text-bone-50/80 hover:text-bone-50 hover:border-bone-50/35 hover:bg-bone-50/5"
            >
              <span>WhatsApp</span>
            </a>
            <button onClick={() => go('contact')} data-track="nav-cta-enquire" className="btn rounded-full bg-bone-50 text-ink-950 px-4 py-2 text-[12px] font-medium tracking-wide hover:bg-accent-soft">
              Enquire
            </button>
          </div>

          <button className="md:hidden p-2 text-bone-50" onClick={() => setMobileOpen(v => !v)} aria-label="Menu">
            {mobileOpen ? <Icon.X size={20}/> : <Icon.Menu size={20}/>}
          </button>
        </div>

        {/* mobile sheet */}
        {mobileOpen && (
          <div className="md:hidden mt-2 glass rounded-3xl p-4">
            <div className="flex flex-col">
              {NAV.map((n) => (
                <button
                  key={n.id}
                  onClick={() => go(n.id)}
                  data-track={`nav-${n.id}-mobile`}
                  className={`text-left px-3 py-3 rounded-xl text-[15px] ${page === n.id ? 'bg-bone-50/5 text-bone-50' : 'text-bone-50/70'}`}
                >
                  {n.label}
                </button>
              ))}
              <button onClick={() => go('contact')} data-track="nav-cta-enquire-mobile" className="mt-2 w-full rounded-full bg-bone-50 text-ink-950 py-3 text-[13px] font-medium">
                Enquire
              </button>
              <a
                href="https://wa.me/918968566656?text=Hi%20AMG%2C%20I%27d%20like%20to%20know%20more."
                target="_blank"
                rel="noopener noreferrer"
                data-track="nav-cta-whatsapp-mobile"
                className="mt-2 w-full inline-flex items-center justify-center gap-2 rounded-full border border-bone-50/30 text-bone-50 py-3 text-[13px] font-medium hover:bg-bone-50/10"
              >
                <Icon.WhatsApp size={14} strokeWidth={2}/>
                Chat on WhatsApp
              </a>
              <button
                onClick={toggleColorMode}
                className="mt-2 w-full inline-flex items-center justify-center gap-2 rounded-full border border-bone-50/15 py-3 text-[13px] text-bone-50/70"
              >
                {colorMode === 'dark' ? <Icon.Sun size={15}/> : <Icon.Moon size={15}/>}
                {colorMode === 'dark' ? 'Light mode' : 'Dark mode'}
              </button>
            </div>
          </div>
        )}
      </div>
    </header>
  );
};

// ----- Marquee strip -----
const Marquee = ({ items }) => (
  <div className="overflow-hidden border-y border-bone-50/15 bg-ink-900">
    <div className="flex gap-14 marquee py-5 whitespace-nowrap will-change-transform">
      {[...items, ...items, ...items].map((t, i) => (
        <div key={i} className="flex items-center gap-4 text-bone-50 text-[13px] uppercase tracking-[0.3em] font-medium">
          <span className="h-1.5 w-1.5 rounded-full flex-shrink-0 bg-accent" />
          {t}
        </div>
      ))}
    </div>
  </div>
);

// ----- Footer -----
const Footer = ({ setPage }) => {
  const go = (id) => { setPage(id); window.scrollTo({ top: 0, behavior: 'smooth' }); };
  return (
    <footer className="relative bg-ink-950 border-t border-bone-50/10 mt-12 sm:mt-24 overflow-hidden">
      <div className="relative z-10 mx-auto max-w-[1320px] px-5 sm:px-8 pt-14 sm:pt-20">

        {/* ── Hero row: tagline left, CTA cards right ── */}
        <div className="flex flex-col lg:flex-row lg:items-end justify-between gap-10 pb-12 border-b border-bone-50/10">
          <div className="max-w-xl">
            <Logo onClick={() => go('home')} />
            <p className="mt-8 font-display text-[28px] sm:text-[36px] lg:text-[42px] leading-[1.08] text-bone-50">
              Building Punjab's next architectural chapter.
            </p>
            </div>

          {/* CTA cards */}
          <div className="flex flex-col sm:flex-row gap-3 shrink-0">
            <a href="https://wa.me/918968566656?text=Hi%20AMG%2C%20I%27d%20like%20to%20know%20more."
               target="_blank" rel="noopener noreferrer"
               className="group flex items-center justify-between gap-10 rounded-2xl border border-bone-50/15 px-6 py-5 hover:border-bone-50/25 hover:bg-bone-50/5 transition-all"
               data-track="footer-cta-whatsapp">
              <div>
                <div className="text-[15px] font-medium text-bone-50 leading-tight">WhatsApp Us</div>
                <div className="text-[12px] text-bone-50/45 mt-1">Chat with our team</div>
              </div>
              <div className="h-9 w-9 rounded-full bg-accent/15 border border-accent/25 grid place-items-center text-accent shrink-0 group-hover:bg-accent group-hover:text-ink-950 transition-all">
                <Icon.ArrowUpRight size={14}/>
              </div>
            </a>
            <button onClick={() => go('contact')}
               className="group flex items-center justify-between gap-10 rounded-2xl border border-bone-50/15 px-6 py-5 hover:border-bone-50/25 hover:bg-bone-50/5 transition-all"
               data-track="footer-cta-enquire">
              <div>
                <div className="text-[15px] font-medium text-bone-50 leading-tight">Enquire Now</div>
                <div className="text-[12px] text-bone-50/45 mt-1">Find your property</div>
              </div>
              <div className="h-9 w-9 rounded-full bg-bone-50/8 border border-bone-50/20 grid place-items-center text-bone-50/70 shrink-0 group-hover:bg-accent group-hover:border-accent group-hover:text-ink-950 transition-all">
                <Icon.ArrowUpRight size={14}/>
              </div>
            </button>
          </div>
        </div>

        {/* ── Nav row ── */}
        <div className="grid grid-cols-2 lg:grid-cols-12 gap-x-6 gap-y-10 py-12">

          {/* Company A — 2 cols */}
          <div className="lg:col-span-2">
            <div className="text-[11px] uppercase tracking-[0.22em] text-bone-50/40 mb-5">Company</div>
            <ul className="space-y-3 text-[14px]">
              {[
                { label: 'Home',       id: 'home'       },
                { label: 'About',      id: 'about'      },
                { label: 'Leadership', id: 'leadership' },
                { label: 'Brands',     id: 'brands'     },
                { label: 'News',       id: 'news'       },
              ].map((n) => (
                <li key={n.id}>
                  <button onClick={() => go(n.id)} className="ulink text-bone-50/65 hover:text-bone-50 text-left transition-colors">{n.label}</button>
                </li>
              ))}
            </ul>
          </div>

          {/* Company B — 2 cols */}
          <div className="lg:col-span-2">
            <div className="text-[11px] uppercase tracking-[0.22em] text-bone-50/40 mb-5 select-none invisible" aria-hidden="true">·</div>
            <ul className="space-y-3 text-[14px]">
              {[
                { label: 'Contact',    id: 'contact'    },
                { label: 'FAQ',        id: 'faq'        },
                { label: 'Disclaimer', id: 'disclaimer' },
              ].map((n) => (
                <li key={n.id}>
                  <button onClick={() => go(n.id)} className="ulink text-bone-50/65 hover:text-bone-50 text-left transition-colors">{n.label}</button>
                </li>
              ))}
            </ul>
          </div>

          {/* Commercial — 2 cols */}
          <div className="lg:col-span-2">
            <div className="text-[11px] uppercase tracking-[0.22em] text-bone-50/40 mb-5">Commercial</div>
            <ul className="space-y-3 text-[14px]">
              {[
                { label: 'Palm Marina', id: 'palm-marina' },
                { label: 'One AMG',     id: 'one-amg'     },
              ].map((p) => (
                <li key={p.id}>
                  <button onClick={() => go(p.id)} className="ulink text-bone-50/65 hover:text-bone-50 text-left transition-colors">{p.label}</button>
                </li>
              ))}
            </ul>
          </div>

          {/* Residential — 2 cols */}
          <div className="lg:col-span-2">
            <div className="text-[11px] uppercase tracking-[0.22em] text-bone-50/40 mb-5">Residential</div>
            <ul className="space-y-3 text-[14px]">
              {[
                { label: 'Palm Garden',     id: 'palm-garden'     },
                { label: 'Palm City',       id: 'palm-city-2'     },
                { label: 'Palm Enclave',    id: 'palm-enclave'    },
                { label: 'Maurya Greens',   id: 'maurya-greens'   },
                { label: 'Palm City Ph II', id: 'palm-city-ph-ii' },
              ].map((p) => (
                <li key={p.id}>
                  <button onClick={() => go(p.id)} className="ulink text-bone-50/65 hover:text-bone-50 text-left transition-colors">{p.label}</button>
                </li>
              ))}
            </ul>
          </div>

          {/* Address — 4 cols, pushed right */}
          <div className="col-span-2 lg:col-span-4 lg:pl-8 lg:border-l lg:border-bone-50/10">
            <div className="text-[11px] uppercase tracking-[0.22em] text-bone-50/40 mb-5">Corporate Office</div>
            <address className="not-italic text-[14px] text-bone-50/65 leading-relaxed">
              Shop No 14-15, Palm Heights,<br/>
              VPO Jaspal Bangar, Sidhwan Canal Road,<br/>
              Ludhiana – 141122
            </address>
            <div className="mt-5 space-y-2 text-[14px] text-bone-50/65">
              <a href="tel:+917087215304" className="flex items-center gap-2 ulink hover:text-bone-50 transition-colors"><Icon.Phone size={13}/> +91 70872-15304</a>
              <a href="mailto:info@amgrealty.in" className="flex items-center gap-2 ulink hover:text-bone-50 transition-colors"><Icon.Mail size={13}/> info@amgrealty.in</a>
            </div>
          </div>

        </div>

        {/* ── Bottom bar ── */}
        <div className="border-t border-bone-50/10 py-6 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 text-[12px] text-bone-50/38">
          <div className="flex items-center gap-4">
            <span>© {new Date().getFullYear()} Ashok Malhotra Group · All rights reserved.</span>
            <span className="h-3 w-px bg-bone-50/20 hidden sm:block"/>
            <div className="flex items-center gap-2">
              <a href="https://www.instagram.com/amgrealty.in" target="_blank" rel="noopener noreferrer"
                 className="h-7 w-7 rounded-full border border-bone-50/15 grid place-items-center text-bone-50/50 hover:text-bone-50 hover:border-bone-50/35 transition"
                 data-track="footer-social-instagram">
                <Icon.Instagram size={12}/>
              </a>
              <a href="https://wa.me/918968566656" target="_blank" rel="noopener noreferrer"
                 className="h-7 w-7 rounded-full border border-bone-50/15 grid place-items-center text-bone-50/50 hover:text-bone-50 hover:border-bone-50/35 transition"
                 data-track="footer-social-whatsapp">
                <Icon.WhatsApp size={12}/>
              </a>
            </div>
          </div>
          <div className="flex items-center gap-5">
            <button onClick={() => go('faq')} className="ulink hover:text-bone-50/70 transition-colors">FAQ</button>
            <button onClick={() => go('disclaimer')} className="ulink hover:text-bone-50/70 transition-colors">Disclaimer</button>
          </div>
        </div>

      </div>


    </footer>
  );
};

// ----- Centered modal portal (escapes Framer Motion transform stacking context) -----
const ModalPortal = ({ onClose, children }) => {
  React.useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, []);
  return ReactDOM.createPortal(
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4"
      style={{ background: 'color-mix(in srgb, var(--bg-base) 80%, transparent)' }}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div
        className="relative w-full max-w-md rounded-3xl overflow-y-auto p-8 sm:p-10"
        style={{ background: 'var(--bg-elev)', border: '1px solid var(--ink-faint)', color: 'var(--ink-fg)', maxHeight: '90dvh' }}
      >
        {children}
      </div>
    </div>,
    document.body
  );
};

// Expose
Object.assign(window, {
  useReveal, PrimaryButton, GhostButton, Eyebrow, SectionTitle, ArchPh, Logo, Nav, Marquee, Footer, NAV, ThemeToggle, ModalPortal,
});
