// site-router.jsx, turns the "Full Site (B+)" design prototype into a real,
// navigable website.
//
// The prototype shipped its pages as React components laid out side-by-side on a
// DesignCanvas (see site-app.jsx). This file replaces that editor chrome with a
// lightweight hash router, re-wires the prototype's placeholder href="#" links to
// real destinations, and applies the design's tweak defaults as CSS variables.
// All page components (BHome, BWeddings, BAbout, service/content/support pages...)
// are reused verbatim, nothing about the visual design changes.

// ── Tweak defaults (mirrors the EDITMODE block in site-app.jsx) ───────────────
const TWEAKS = { serifB: 'Playfair Display', goldPct: 55, washPct: 55 };

// Home and Weddings rely on the canvas wrapper that prepends the topbar; every
// other page already includes its own. Replicate that wrapper here.
function wrapBx(Component) {
  return (
    <div className="bx">
      <BTopbar />
      <Component />
    </div>
  );
}

// ── Route table ───────────────────────────────────────────────────────────────
const ROUTES = {
  home: () => wrapBx(BHome),
  about: () => <BAbout />,
  services: () => <BServicesLanding />,
  weddings: () => wrapBx(BWeddings),
  engagement: () => <BEngagement />,
  corporate: () => <BCorporate />,
  'baby-showers': () => <BBabyShowers />,
  receptions: () => <BReceptions />,
  birthdays: () => <BBirthdays />,
  portfolio: () => <BPortfolio />,
  contact: () => <BContact />,
  faq: () => <BFaqPage />,
  privacy: () => <BPrivacy />,
  terms: () => <BTerms />,
};

// Maps human labels (nav text, button text, service names) → route keys.
const LABEL_ROUTES = {
  'home': 'home', 'back to home': 'home', 'return home': 'home',
  'about': 'about', 'about sam set events': 'about', 'our story': 'about',
  'services': 'services', 'our services': 'services',
  'portfolio': 'portfolio', 'view full portfolio': 'portfolio', 'view our work': 'portfolio',
  'journal': 'journal',
  'contact': 'contact',
  'start planning': 'contact', 'book a consultation': 'contact', 'get started': 'contact',
  'faq': 'faq', 'faqs': 'faq', 'view all faqs': 'faq',
  'privacy policy': 'privacy', 'privacy': 'privacy',
  'terms & conditions': 'terms', 'terms and conditions': 'terms', 'terms': 'terms',
  'weddings': 'weddings',
  'engagement parties': 'engagement',
  'corporate events': 'corporate',
  'baby showers': 'baby-showers',
  'receptions': 'receptions',
  'birthday celebrations': 'birthdays',
};

function currentRoute() {
  const h = (window.location.hash || '').replace(/^#\/?/, '').trim().toLowerCase();
  return h || 'home';
}
function go(route) {
  window.location.hash = '#/' + route;
}

// ── Route-aware chrome (overrides the prototype's href="#" versions) ──────────
// These globals were declared by dir-b-home.jsx. Because Babel-standalone runs
// each script in global scope, reassigning window.X rebinds the global the page
// components reference at render time.
// Social profiles — clean line icons. Set `href` to the real profile URL to
// turn each into a live link; null renders a non-clickable placeholder icon.
const SS_SOCIALS = [
  {
    name: 'Instagram',
    href: null,
    icon: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <rect x="3" y="3" width="18" height="18" rx="5" />
        <circle cx="12" cy="12" r="4" />
        <circle cx="17.2" cy="6.7" r="1.1" fill="currentColor" stroke="none" />
      </svg>
    ),
  },
  {
    name: 'Facebook',
    href: null,
    icon: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M16 3h-3a4 4 0 0 0-4 4v3H6v4h3v7h4v-7h3l1-4h-4V7a1 1 0 0 1 1-1h3z" />
      </svg>
    ),
  },
];
function BSocial({ className }) {
  return (
    <div className={'ss-social' + (className ? ' ' + className : '')}>
      {SS_SOCIALS.map((s) => (
        s.href ? (
          <a key={s.name} href={s.href} target="_blank" rel="noopener noreferrer" aria-label={s.name}>
            {s.icon}
          </a>
        ) : (
          <span key={s.name} className="ss-icon" role="img" aria-label={s.name}>
            {s.icon}
          </span>
        )
      ))}
    </div>
  );
}

window.BNav = function BNav({ active }) {
  const [open, setOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  // Close the mobile menu whenever the route changes.
  React.useEffect(() => {
    const close = () => setOpen(false);
    window.addEventListener('hashchange', close);
    return () => window.removeEventListener('hashchange', close);
  }, []);
  // Condense the nav (shrink + hairline/shadow) once the page is scrolled.
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={'db-nav' + (open ? ' nav-open' : '') + (scrolled ? ' scrolled' : '')}>
      <a className="db-brand" href="#/home">
        <img src="assets/monogram-burgundy.png" alt="SS monogram" />
        <span className="bt"><b>SAM SET</b><i>EVENTS</i></span>
      </a>
      <button
        className="db-burger"
        type="button"
        aria-label={open ? 'Close menu' : 'Open menu'}
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
      >
        <span></span><span></span><span></span>
      </button>
      <nav>
        {SS_COPY.navLinks.map((l) => (
          <a
            key={l}
            href={'#/' + (LABEL_ROUTES[l.toLowerCase()] || 'home')}
            className={l === active ? 'active' : ''}
          >
            {l}
          </a>
        ))}
        <BSocial className="in-menu" />
      </nav>
      <a className="btn" href="#/contact">Start Planning</a>
    </header>
  );
};

window.BFooter = function BFooter() {
  return (
    <footer className="db-footer">
      <div className="cols">
        <div>
          <img src="assets/logo-ivory.png" alt="Sam Set Events" />
          <p className="tag">Luxury wedding &amp; event planning in New York, warm, intentional, and beautifully composed.</p>
        </div>
        <div>
          <h6>Explore</h6>
          <ul>{SS_COPY.footerExplore.map((l) => (
            <li key={l}><a href={'#/' + (LABEL_ROUTES[l.toLowerCase()] || 'home')}>{l}</a></li>
          ))}</ul>
        </div>
        <div>
          <h6>Services</h6>
          <ul>{SS_COPY.services.map((s) => (
            <li key={s.n}><a href={'#/' + (LABEL_ROUTES[s.name.toLowerCase()] || 'services')}>{s.name}</a></li>
          ))}</ul>
        </div>
        <div>
          <h6>Contact</h6>
          <ul>
            <li>hello@samsetevents.com</li>
            <li className="ss-social-li"><BSocial /></li>
          </ul>
        </div>
      </div>
      <div className="legal">
        <span>© 2026 Sam Set Events, samsetevents.com</span>
        <span className="links">
          <a href="#/privacy">Privacy Policy</a>
          <a href="#/terms">Terms &amp; Conditions</a>
        </span>
      </div>
    </footer>
  );
};

window.BCta = function BCta({ title, body, cta }) {
  return (
    <div className="db-cta-wrap">
      <section className="db-cta">
        <div className="glow"></div>
        <img src="assets/monogram-ivory.png" alt="" />
        <h2 className="display">{title}</h2>
        <p>{body}</p>
        <a className="btn" href="#/contact">{cta}</a>
      </section>
    </div>
  );
};

// ── In-page link resolution ───────────────────────────────────────────────────
// The page bodies still contain many href="#" links (service cards, "View Full
// Portfolio", journal posts, hero CTAs...). Resolve them by context/text so they
// navigate instead of jumping to the top of the page.
function resolveAnchorRoute(a) {
  const card = a.closest && a.closest('.db-svc-card');
  if (card) {
    const h = card.querySelector('h4');
    const r = h && LABEL_ROUTES[h.textContent.trim().toLowerCase()];
    if (r) return r;
  }
  if (a.closest && (a.closest('.db-journal-grid') || a.classList.contains('post'))) {
    return 'journal-post';
  }
  const txt = (a.textContent || '').replace(/[→›»\s]+$/g, '').trim().toLowerCase();
  return LABEL_ROUTES[txt] || null;
}

function handleDelegatedClick(e) {
  const a = e.target.closest && e.target.closest('a');
  if (!a) return;
  if (a.getAttribute('href') !== '#') return; // real routes & external links pass through
  e.preventDefault(); // a bare "#" should never scroll to top
  const r = resolveAnchorRoute(a);
  if (r) go(r);
}

// ── SEO: inject JSON-LD built from the canonical site data ────────────────────
function injectStructuredData() {
  if (document.getElementById('ss-jsonld')) return;
  const business = {
    '@context': 'https://schema.org',
    '@type': 'ProfessionalService',
    name: 'Sam Set Events',
    description: 'Luxury wedding and event planning in New York, weddings, engagement parties, corporate events, baby showers, receptions, and birthday celebrations.',
    areaServed: 'New York, Tri-State & Destination',
    email: 'hello@samsetevents.com',
    founder: { '@type': 'Person', name: 'Samia Tayar' },
    url: window.location.origin + window.location.pathname,
    // Add telephone, postal address, and sameAs (social) when available.
  };
  const faqGroups = (window.SSX && SSX.faq && SSX.faq.groups) || [];
  const faq = {
    '@context': 'https://schema.org',
    '@type': 'FAQPage',
    mainEntity: faqGroups.flatMap((g) => g.items).map((it) => ({
      '@type': 'Question',
      name: it.q,
      acceptedAnswer: { '@type': 'Answer', text: (it.a || '').trim() },
    })),
  };
  const s = document.createElement('script');
  s.type = 'application/ld+json';
  s.id = 'ss-jsonld';
  s.textContent = JSON.stringify([business, faq]);
  document.head.appendChild(s);
}

// ── App shell ─────────────────────────────────────────────────────────────────
function App() {
  const [route, setRoute] = React.useState(currentRoute());
  React.useEffect(() => {
    const onHash = () => {
      setRoute(currentRoute());
      window.scrollTo(0, 0);
    };
    window.addEventListener('hashchange', onHash);
    injectStructuredData();
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const vars = {
    '--serif-b': "'" + TWEAKS.serifB + "', serif",
    '--gold-pct': TWEAKS.goldPct + '%',
    '--wash-pct': TWEAKS.washPct,
  };
  const render = ROUTES[route] || (() => <B404 />);
  return (
    <div style={vars} onClickCapture={handleDelegatedClick}>
      {render()}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
