const { useState, useEffect, useRef } = React;
const { Link, NavLink, useLocation } = ReactRouterDOM;
const { COPY, CLIENTS } = window.AF_DATA;

// ---------- Wordmark ----------
function Wordmark({ size = "md", inverse = false }) {
  const big = size === "lg";
  const color = inverse ? "#F8F4ED" : "#1F1A14";
  return (
    <Link to="/" className="inline-flex items-baseline gap-2 leading-none select-none">
      <span className="font-display" style={{ fontWeight: 500, fontStyle: 'italic', color, fontSize: big ? 28 : 21, letterSpacing: '-0.02em' }}>
        Art &amp; Frame
      </span>
      <span aria-hidden className="font-display" style={{ color: '#A0522D', fontSize: big ? 26 : 19, fontWeight: 500, transform: 'translateY(1px)' }}>+</span>
      <span className="font-display" style={{ fontWeight: 500, color, fontSize: big ? 28 : 21, letterSpacing: '-0.02em' }}>
        Signs
      </span>
    </Link>
  );
}

// ---------- Eyebrow ----------
function Eyebrow({ children, className = "" }) {
  return (
    <div className={`eyebrow flex items-center gap-3 ${className}`}>
      <span className="inline-block w-6 h-px bg-[#A0522D]"></span>
      <span>{children}</span>
    </div>
  );
}

// ---------- Utility Bar ----------
function UtilityBar() {
  return (
    <div className="bg-[#1F1A14] text-[#F8F4ED]/85 text-[12px]">
      <div className="max-w-container mx-auto px-5 md:px-8 h-9 flex items-center justify-between">
        <div className="flex items-center gap-2 tracking-wide">
          <span className="w-1.5 h-1.5 rounded-full bg-[#A0522D]"></span>
          <span>McKinney, TX</span>
          <span className="opacity-40 mx-1">·</span>
          <span>Since 1994</span>
        </div>
        <div className="flex items-center gap-4">
          <a href={COPY.smsHref} className="hidden sm:inline-flex items-center gap-1.5 hover:text-white">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
            Text us
          </a>
          <a href={COPY.phoneHref} className="inline-flex items-center gap-1.5 hover:text-white">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
            {COPY.phone}
          </a>
        </div>
      </div>
    </div>
  );
}

// ---------- Navbar ----------
const NAV_LINKS = [
  { to: "/what-we-do", label: "What We Do" },
  { to: "/about-us", label: "About" },
  { to: "/location", label: "Location" },
  { to: "/are-you-a-business", label: "Business" },
];
// External pages outside the hash router (static HTML at site root)
const EXTERNAL_LINKS = [
  { href: "/visualizer.html", label: "Visualizer" },
];

function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const loc = useLocation();
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => { setOpen(false); }, [loc.pathname]);
  return (
    <header className={`sticky top-0 z-40 transition-all ${scrolled ? 'bg-[#F8F4ED]/95 backdrop-blur border-b hairline' : 'bg-[#F8F4ED] border-b border-transparent'}`}>
      <div className="max-w-container mx-auto px-5 md:px-8 h-[68px] flex items-center justify-between">
        <Wordmark />
        <nav className="hidden md:flex items-center gap-8">
          {NAV_LINKS.map(l => (
            <NavLink key={l.to} to={l.to} className={({isActive}) => `text-[14px] tracking-wide transition-colors ${isActive ? 'text-[#1F1A14]' : 'text-[#3A332A] hover:text-[#A0522D]'}`}>
              {({isActive}) => (
                <span className="relative">
                  {l.label}
                  {isActive && <span className="absolute -bottom-1.5 left-0 right-0 h-px bg-[#A0522D]"></span>}
                </span>
              )}
            </NavLink>
          ))}
          {EXTERNAL_LINKS.map(l => (
            <a key={l.href} href={l.href} className="text-[14px] tracking-wide transition-colors text-[#3A332A] hover:text-[#A0522D]">
              {l.label}
            </a>
          ))}
          <Link to="/book" className="btn-primary !py-2.5 !px-4 !text-[13px]">Book Appointment</Link>
        </nav>
        <button className="md:hidden inline-flex items-center justify-center w-10 h-10 -mr-2" onClick={() => setOpen(true)} aria-label="Open menu">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#1F1A14" strokeWidth="1.8"><path d="M4 7h16M4 12h16M4 17h16"/></svg>
        </button>
      </div>
      {/* Mobile drawer */}
      {open && (
        <div className="fixed inset-0 z-50 md:hidden">
          <div className="absolute inset-0 bg-[#1F1A14]/40" onClick={() => setOpen(false)}></div>
          <div className="absolute right-0 top-0 bottom-0 w-[86%] max-w-sm bg-[#F8F4ED] shadow-2xl flex flex-col">
            <div className="h-[68px] px-5 flex items-center justify-between border-b hairline">
              <Wordmark />
              <button className="w-10 h-10 -mr-2 inline-flex items-center justify-center" onClick={() => setOpen(false)} aria-label="Close">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#1F1A14" strokeWidth="1.8"><path d="M6 6l12 12M18 6l-12 12"/></svg>
              </button>
            </div>
            <nav className="flex-1 overflow-y-auto px-5 py-6 flex flex-col gap-1">
              {NAV_LINKS.map(l => (
                <NavLink key={l.to} to={l.to} className="py-3 font-display text-[26px] ink border-b hairline">
                  {l.label}
                </NavLink>
              ))}
              {EXTERNAL_LINKS.map(l => (
                <a key={l.href} href={l.href} className="py-3 font-display text-[26px] ink border-b hairline">
                  {l.label}
                </a>
              ))}
              <Link to="/book" className="btn-primary mt-6 justify-center">Book Appointment</Link>
              <a href={COPY.smsHref} className="btn-ghost mt-3 justify-center">Text us: {COPY.phone}</a>
              <a href={COPY.phoneHref} className="mt-4 text-center text-[14px] text-[#807466]">
                Or call <span className="ink">{COPY.phone}</span>
              </a>
            </nav>
          </div>
        </div>
      )}
    </header>
  );
}

// ---------- Footer ----------
function Footer() {
  return (
    <footer className="bg-[#1F1A14] text-[#F8F4ED] mt-24">
      <div className="max-w-container mx-auto px-5 md:px-8 py-16 md:py-20">
        <div className="grid md:grid-cols-3 gap-12">
          <div>
            <Wordmark inverse />
            <p className="mt-5 text-[14px] text-[#F8F4ED]/60 leading-relaxed">
              McKinney, TX · Since 1994<br/>
              Custom framing for the memories that matter.
            </p>
          </div>
          <div>
            <div className="eyebrow !text-[#F8F4ED]/50">Sitemap</div>
            <ul className="mt-4 space-y-2 text-[15px]">
              <li><Link to="/" className="hover:text-[#A0522D]">Home</Link></li>
              <li><Link to="/what-we-do" className="hover:text-[#A0522D]">What We Do</Link></li>
              <li><Link to="/about-us" className="hover:text-[#A0522D]">About</Link></li>
              <li><Link to="/location" className="hover:text-[#A0522D]">Location</Link></li>
              <li><Link to="/are-you-a-business" className="hover:text-[#A0522D]">Business</Link></li>
              <li><a href="/visualizer.html" className="hover:text-[#A0522D]">Frame Visualizer</a></li>
              <li><Link to="/book" className="hover:text-[#A0522D]">Book an Appointment</Link></li>
            </ul>
          </div>
          <div>
            <div className="eyebrow !text-[#F8F4ED]/50">Get in touch</div>
            <ul className="mt-4 space-y-2 text-[15px]">
              <li><a href={COPY.phoneHref} className="hover:text-[#A0522D]">Call · {COPY.phone}</a></li>
              <li><a href={COPY.smsHref} className="hover:text-[#A0522D]">Text · {COPY.phone}</a></li>
              <li className="text-[#F8F4ED]/60 pt-2">Monday – Saturday<br/><span className="text-[12px] opacity-70">{/* TODO: Confirm hours */}Hours by appointment & walk-in</span></li>
              <li className="text-[#F8F4ED]/60 pt-1 text-[13px]">Closed June 6–10, 2026</li>
            </ul>
          </div>
        </div>
        <div className="mt-14 pt-6 border-t border-white/10 flex flex-col md:flex-row gap-3 md:items-center md:justify-between text-[12px] text-[#F8F4ED]/45">
          <div>© 2025 Art &amp; Frame + Signs. All rights reserved.</div>
          <div>Hand-framed in McKinney, Texas.</div>
        </div>
      </div>
    </footer>
  );
}

// ---------- Image Placeholder ----------
function ImagePlaceholder({ label = "Photo", aspect = "4/5", note = "" }) {
  return (
    <div className="relative ph-stripes border hairline overflow-hidden" style={{ aspectRatio: aspect }}>
      <div className="absolute inset-0 flex flex-col items-center justify-center text-center px-4">
        <div className="w-10 h-10 border hairline flex items-center justify-center mb-3 bg-[#F8F4ED]/60">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#A0522D" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18"/><path d="M3 16l5-5 4 4 3-3 6 6"/><circle cx="9" cy="9" r="1.5"/></svg>
        </div>
        <div className="font-mono text-[11px] uppercase tracking-wider text-[#807466]">{label}</div>
        {note && <div className="font-mono text-[10px] text-[#807466]/70 mt-1.5 max-w-[180px]">{note}</div>}
      </div>
    </div>
  );
}

// ---------- Real Image with frame matting ----------
function FramedImage({ src, alt, aspect = "4/5", caption = "" }) {
  return (
    <figure>
      <div className="relative overflow-hidden border hairline" style={{ aspectRatio: aspect }}>
        <img src={src} alt={alt} className="absolute inset-0 w-full h-full object-cover" />
      </div>
      {caption && <figcaption className="mt-3 text-[12px] font-mono uppercase tracking-wider text-[#807466]">{caption}</figcaption>}
    </figure>
  );
}

// ---------- Client list block ----------
function ClientListBlock({ title = "Trusted by", showCategories = false, dense = false }) {
  return (
    <div>
      <Eyebrow>{title}</Eyebrow>
      <ul className={`mt-6 ${dense ? 'space-y-2' : 'space-y-4'}`}>
        {CLIENTS.map((c, i) => (
          <li key={c.name} className="flex items-baseline gap-4">
            <span className="font-mono text-[11px] text-[#807466] w-6">0{i+1}</span>
            <span className="font-display ink text-[clamp(22px,3.4vw,38px)]" style={{ fontStyle: 'italic', fontWeight: 500, lineHeight: 1.1 }}>{c.name}</span>
            {showCategories && <span className="hidden md:inline text-[12px] text-[#807466] ml-auto pl-4">{c.category}</span>}
          </li>
        ))}
      </ul>
    </div>
  );
}

// ---------- Closure Notice ----------
function ClosureNotice({ tight = false }) {
  return (
    <div className={`border hairline bg-white/60 ${tight ? 'px-5 py-3 text-[13px]' : 'px-6 py-4 text-[14px]'} flex items-center gap-3`}>
      <span className="w-2 h-2 rounded-full bg-[#A0522D] flex-shrink-0"></span>
      <div>
        <span className="font-mono uppercase tracking-wider text-[11px] text-[#A0522D] mr-2">Notice</span>
        <span className="ink">{COPY.closure}</span>
        <span className="text-[#807466] ml-2 hidden sm:inline">Sorry for the inconvenience.</span>
      </div>
    </div>
  );
}

// ---------- Section header for inner pages ----------
function PageHeader({ eyebrow, title, italicWord, lead }) {
  // title may include the italicWord; we'll split by it
  let parts = [title];
  if (italicWord && title.includes(italicWord)) {
    const idx = title.indexOf(italicWord);
    parts = [title.slice(0, idx), italicWord, title.slice(idx + italicWord.length)];
  }
  return (
    <section className="pt-14 md:pt-20 pb-10 md:pb-14 border-b hairline">
      <div className="max-w-container mx-auto px-5 md:px-8">
        <Eyebrow>{eyebrow}</Eyebrow>
        <h1 className="font-display ink mt-5 text-[clamp(44px,7vw,84px)] leading-[1.02]" style={{ fontWeight: 500, letterSpacing: '-0.02em' }}>
          {parts.length === 3
            ? (<><span>{parts[0]}</span><em className="text-[#A0522D]" style={{ fontStyle: 'italic' }}>{parts[1]}</em><span>{parts[2]}</span></>)
            : title}
        </h1>
        {lead && <p className="mt-6 max-w-[58ch] text-[18px] md:text-[19px] body-ink">{lead}</p>}
      </div>
    </section>
  );
}

// ---------- Reveal on scroll ----------
function Reveal({ children, delay = 0, className = "" }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) { setShown(true); io.disconnect(); }
      });
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <div ref={ref} className={className} style={{ opacity: shown ? 1 : 0, transform: shown ? 'translateY(0)' : 'translateY(14px)', transition: `opacity .7s ease ${delay}s, transform .7s ease ${delay}s` }}>
      {children}
    </div>
  );
}

// ---------- Scroll restoration ----------
function ScrollToTop() {
  const { pathname } = useLocation();
  useEffect(() => { window.scrollTo({ top: 0, behavior: 'instant' }); }, [pathname]);
  return null;
}

Object.assign(window, {
  Wordmark, Eyebrow, UtilityBar, Navbar, Footer,
  ImagePlaceholder, FramedImage, ClientListBlock,
  ClosureNotice, PageHeader, Reveal, ScrollToTop,
});
