/*
 * AEI — Operational Intelligence for Service-Based Businesses
 * ------------------------------------------------------------
 * PRE-LAUNCH CHECKLIST
 *
 * 1. SITE_CONFIG tokens to replace before launch:
 *    - domain, email, phone, founderFirstName
 *    - calcomUsername, calcomEventSlug
 *    - loopsFormIds (dental, specialtyMedical, propertyManagement, professionalServices)
 *    - capacity counts per industry
 *
 * 2. Backend connections needed:
 *    - Cal.com account (30-minute consultation event)
 *    - Loops.so account with four form endpoints, one per industry
 *    - Four industry-specific operational-audit PDFs hosted by Loops
 *
 * 3. Legal:
 *    - Privacy Policy and Terms of Service generated via Termly or iubenda
 *    - Footer hrefs replaced once URLs exist
 *
 * 4. Analytics: Plausible or Fathom, injected at deploy time only.
 *
 * 5. Deployment: Vercel free tier. Connect domain once secured.
 */

const SITE_CONFIG = {
  domain: "aeisystems.com",
  email: "contact@aeisystems.com",
  phone: "(602) 555-0100",
  founderFirstName: "[FOUNDER]",
  calcomUsername: "aei",
  calcomEventSlug: "30min",
  loopsFormIds: {
    dental: "",
    specialtyMedical: "",
    propertyManagement: "",
    professionalServices: ""
  },
  capacity: {
    dental: { total: 5, available: 3 },
    specialtyMedical: { total: 5, available: 5 },
    propertyManagement: { total: 5, available: 4 },
    professionalServices: { total: 5, available: 5 }
  }
};

const calcomUrl = "https://calendar.proton.me/bookings#KFoY3yVBvTAuQRaMlegln6miXJ96Xp7foqiKrPfpDzs=";

/* ----------------------------------------------------------------
 * Booking modal — Cal.com iframe, lazy-loaded on open only.
 * ---------------------------------------------------------------- */
function BookingModal({ open, onClose }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div
      className="fixed inset-0 z-50 flex items-stretch md:items-center justify-center bg-ink/70 backdrop-blur-sm"
      role="dialog"
      aria-modal="true"
      aria-label="Book a 30-minute consultation"
      onClick={onClose}>
      
      <div
        className="bg-white w-full md:w-[900px] md:max-w-[92vw] md:h-[720px] md:max-h-[88vh] md:rounded md:shadow-2xl flex flex-col"
        onClick={(e) => e.stopPropagation()}>
        
        <div className="flex items-center justify-between px-5 h-14 border-b border-rule shrink-0">
          <div className="flex items-baseline gap-3">
            <span className="font-medium tracking-tighter2">AEI</span>
            <span className="text-sm text-muted">30-minute consultation</span>
          </div>
          <button
            onClick={onClose}
            aria-label="Close booking"
            className="w-9 h-9 -mr-2 flex items-center justify-center rounded hover:bg-paper text-muted hover:text-ink">
            
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
              <path d="M3 3L13 13M13 3L3 13" stroke="currentColor" strokeWidth="1.5" />
            </svg>
          </button>
        </div>
        <iframe
          src={calcomUrl}
          title="Cal.com — 30-minute consultation"
          className="flex-1 w-full border-0" />
        
      </div>
    </div>);

}

/* ----------------------------------------------------------------
 * Header — floating glass pill with an animated indicator that slides
 * between nav items (hover / scroll-spy active). Mobile collapses to
 * a drawer. Wordmark left, anchors center, glass CTA right.
 * ---------------------------------------------------------------- */
const NAV_LINKS = [
{ id: "workflows", label: "Workflows" },
{ id: "engagement", label: "How it Works" },
{ id: "pricing", label: "Pricing" },
{ id: "faq", label: "FAQ" }];


function Header({ onBook }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [active, setActive] = React.useState(null);
  const [hover, setHover] = React.useState(null);
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const [indicator, setIndicator] = React.useState({ x: 0, w: 0, visible: false });
  const navRef = React.useRef(null);
  const itemRefs = React.useRef({});

  // Scroll state for header chrome + simple scroll-spy.
  React.useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 4);

      // Scroll-spy: pick the section whose top is closest above a threshold.
      const threshold = 120;
      let current = null;
      for (const link of NAV_LINKS) {
        const el = document.getElementById(link.id);
        if (!el) continue;
        const rect = el.getBoundingClientRect();
        if (rect.top <= threshold) current = link.id;
      }
      setActive(current);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Position the sliding indicator behind the hovered or active link.
  const target = hover || active;
  React.useLayoutEffect(() => {
    if (!target || !navRef.current) {
      setIndicator((i) => ({ ...i, visible: false }));
      return;
    }
    const item = itemRefs.current[target];
    if (!item) return;
    const navRect = navRef.current.getBoundingClientRect();
    const itemRect = item.getBoundingClientRect();
    setIndicator({
      x: itemRect.left - navRect.left,
      w: itemRect.width,
      visible: true
    });
  }, [target]);

  // Close the drawer on route hash change or resize to desktop.
  React.useEffect(() => {
    const onResize = () => {
      if (window.innerWidth >= 768) setDrawerOpen(false);
    };
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  return (
    <header className="sticky top-0 z-40">
      {/* Top band — transparent until scroll, then adds subtle divider */}
      <div
        className={
        "absolute inset-0 -z-10 transition-colors " + (
        scrolled ? "bg-white/60 backdrop-blur-md border-b border-rule" : "")
        } />
      
      <div className="max-w-[1200px] mx-auto px-4 md:px-8 pt-4">
        <div className="nav-pill h-14 rounded-full flex items-center justify-between pl-5 pr-2">
          {/* Wordmark with status dot */}
          <a
            href="#top"
            className="group flex items-center gap-2.5 text-[22px] md:text-[30px] font-semibold tracking-tightest text-ink"
            aria-label="AEI — back to top">
            
            <span style={{ fontSize: "30px" }}>AEI</span>
          </a>

          {/* Desktop nav with sliding indicator */}
          <nav
            ref={navRef}
            className="relative hidden md:flex items-stretch h-10"
            onMouseLeave={() => setHover(null)}
            aria-label="Primary">
            
            <div
              aria-hidden="true"
              className="nav-indicator absolute top-1/2 -translate-y-1/2 h-8 rounded-full"
              style={{
                transform: `translate(${indicator.x}px, -50%)`,
                width: indicator.w,
                opacity: indicator.visible ? 1 : 0
              }} />
            
            {NAV_LINKS.map((link) => {
              const isActive = active === link.id;
              const isHover = hover === link.id;
              return (
                <a
                  key={link.id}
                  href={`#${link.id}`}
                  ref={(el) => itemRefs.current[link.id] = el}
                  onMouseEnter={() => setHover(link.id)}
                  onFocus={() => setHover(link.id)}
                  onBlur={() => setHover(null)}
                  data-active={isActive}
                  data-hover={isHover}
                  className={
                  "nav-link relative flex items-center px-4 text-sm " + (
                  isActive || isHover ? "text-ink" : "text-muted")
                  }>
                  
                  <span className="relative z-[1]">{link.label}</span>
                  <span className="dot" aria-hidden="true" />
                </a>);

            })}
          </nav>

          {/* Right cluster */}
          <div className="flex items-center gap-2">
            {/* Start Here ghost button — desktop only */}
            <a
              href="#lead-magnet"
              className="hidden md:inline-flex items-center h-10 px-4 rounded-full text-sm font-medium border transition-colors hover:bg-navy/5"
              style={{ borderColor: "#1E3A5F", color: "#1E3A5F" }}>
              
              Start Here
            </a>
            <button
              onClick={onBook}
              className="glass-cta glass-cta--sm inline-flex items-center h-10 px-4 rounded-full text-sm font-medium overflow-hidden">
              
              <span className="relative z-[1] flex items-center gap-2">
                Book consultation
                <svg
                  width="12"
                  height="12"
                  viewBox="0 0 12 12"
                  fill="none"
                  aria-hidden="true">
                  
                  <path
                    d="M1 6h10M7 2l4 4-4 4"
                    stroke="currentColor"
                    strokeWidth="1.5" />
                  
                </svg>
              </span>
            </button>

            {/* Mobile burger */}
            <button
              className="burger md:hidden flex flex-col justify-center w-10 h-10 rounded-full border border-rule hover:border-ink transition-colors"
              aria-label={drawerOpen ? "Close menu" : "Open menu"}
              aria-expanded={drawerOpen}
              data-open={drawerOpen}
              onClick={() => setDrawerOpen((v) => !v)}>
              
              <span className="mx-auto block w-4 h-px bg-ink" />
              <span className="mx-auto block w-4 h-px bg-ink mt-1" />
              <span className="mx-auto block w-4 h-px bg-ink mt-1" />
            </button>
          </div>
        </div>

        {/* Mobile drawer */}
        <div
          className="drawer md:hidden mt-2"
          data-open={drawerOpen}
          aria-hidden={!drawerOpen}>
          
          <div className="nav-pill rounded-2xl p-2">
            {NAV_LINKS.map((link) =>
            <a
              key={link.id}
              href={`#${link.id}`}
              onClick={() => setDrawerOpen(false)}
              className="flex items-center justify-between px-4 rounded-xl text-[17px] text-ink hover:bg-paper"
              style={{ minHeight: "52px" }}>
                <span>{link.label}</span>
                <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true" className="text-muted">
                  <path d="M1 6h10M7 2l4 4-4 4" stroke="currentColor" strokeWidth="1.5" />
                </svg>
              </a>
            )}
            {/* Mobile CTAs */}
            <div className="mt-4 space-y-2">
              <a
                href="#lead-magnet"
                onClick={() => setDrawerOpen(false)}
                className="flex items-center justify-center w-full rounded-xl text-[15px] font-medium border transition-colors hover:bg-navy/5"
                style={{ borderColor: "#1E3A5F", color: "#1E3A5F", minHeight: "52px" }}>
                Start Here
              </a>
              <button
                onClick={() => {setDrawerOpen(false);onBook();}}
                className="glass-cta w-full flex items-center justify-center rounded-xl text-[15px] font-medium overflow-hidden"
                style={{ minHeight: "52px" }}>
                <span className="relative z-[1]">Book consultation</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </header>);

}

/* ----------------------------------------------------------------
 * Hero — above the fold. Declarative, no persuasion.
 * ---------------------------------------------------------------- */
function Hero({ onBook }) {
  const facts = [
  {
    label: "Engagement length",
    value: "90 days minimum, month-to-month after"
  },
  {
    label: "Reporting cadence",
    value: "Weekly written report, every Friday"
  },
  {
    label: "Ownership transfer",
    value: "Full handoff at day 90, no dependencies"
  },
  {
    label: "Month-one guarantee",
    value: "No measurable results, month two not invoiced"
  }];


  return (
    <section
      id="top"
      style={{ border: "0.5px solid #1A1A1A" }}
      className="flex flex-col md:flex-row">
      
      {/* LEFT PANEL */}
      <div
        className="relative flex-1 md:flex-[1.15] flex flex-col justify-between px-6 md:px-14 py-10 md:py-20 overflow-hidden"
        style={{ background: "#080A0F" }}>
        
        {/* Navy radial glow bottom-right */}
        <div
          aria-hidden="true"
          className="absolute bottom-0 right-0 w-[420px] h-[420px] pointer-events-none"
          style={{
            background:
            "radial-gradient(circle at 100% 100%, rgba(30,58,95,0.5), transparent 65%)"
          }} />
        

        <div className="relative">
          {/* Eyebrow */}
          <div
            className="text-[11px] font-medium uppercase tracking-[0.1em]"
            style={{ color: "#4A7FA5" }}>
            
            An operational intelligence firm
          </div>

          {/* Headline */}
          <h1
            className="mt-5 text-[22px] md:text-[28px] font-semibold leading-[1.2]"
            style={{ color: "#F0F4F8", letterSpacing: "-0.025em", fontSize: "40px" }}>
            
            Operational systems designed, deployed, and documented. Yours permanently at day 90.
          </h1>

          {/* Body */}
          <p
            className="mt-5 text-[13px] leading-[1.7] max-w-[52ch]"
            style={{ color: "#6B7A8A", fontSize: "21px" }}>
            
            A structured 90-day engagement. Operational workflows identified, built, and deployed against a measured baseline from week one. Weekly written reporting. Full ownership transferred at day 90. If month one does not demonstrate measurable results, month two is not invoiced.
          </p>
        </div>
      </div>

      {/* Vertical divider — desktop only */}
      <div
        className="hidden md:block w-px shrink-0"
        style={{ background: "#1A1A1A" }}
        aria-hidden="true" />
      
      {/* Horizontal divider — mobile only */}
      <div
        className="md:hidden h-px w-full"
        style={{ background: "#1A1A1A" }}
        aria-hidden="true" />
      

      {/* RIGHT PANEL */}
      <div
        className="flex-1 flex flex-col justify-between px-6 md:px-10 py-10 md:py-16"
        style={{ background: "#F8F9FA" }}>
        
        {/* Four fact blocks */}
        <div className="flex flex-col gap-8">
          {facts.map((f, i) =>
          <div key={i} className={i > 0 ? "pt-8 border-t" : ""} style={i > 0 ? { borderColor: "#E5E7EB" } : {}}>
              <div
              className="text-[10px] font-semibold uppercase tracking-[0.08em]"
              style={{ color: "#9CA3AF" }}>
              
                {f.label}
              </div>
              <div
              className="mt-1.5 text-[14px] font-medium leading-[1.4]"
              style={{ color: "#0A0A0A" }}>
              
                {f.value}
              </div>
            </div>
          )}
        </div>

        {/* CTA */}
        <div className="mt-10">
          <button
            onClick={onBook}
            className="w-full md:w-auto inline-flex items-center justify-center gap-2 h-12 px-5 text-[14px] font-medium text-white transition-opacity hover:opacity-90"
            style={{ background: "#1E3A5F" }}>
            
            Book a 30-minute consultation
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
              <path d="M1 7h12M8 2l5 5-5 5" stroke="currentColor" strokeWidth="1.5" />
            </svg>
          </button>
        </div>
      </div>
    </section>);

}

/* ----------------------------------------------------------------
 * Floating back-to-top button — appears after 400px scroll.
 * Glass treatment, navy accent, subtle fade+slide animation.
 * ---------------------------------------------------------------- */
function BackToTop() {
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 400);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const scrollToTop = () => window.scrollTo({ top: 0, behavior: "smooth" });

  return (
    <button
      onClick={scrollToTop}
      aria-label="Back to top"
      style={{
        position: "fixed",
        bottom: "1.5rem",
        right: "1.5rem",
        zIndex: 50,
        width: "40px",
        height: "40px",
        borderRadius: "50%",
        background: "linear-gradient(180deg, rgba(46,82,128,0.92) 0%, rgba(30,58,95,0.95) 100%)",
        border: "1px solid rgba(255,255,255,0.18)",
        boxShadow: "inset 0 1px 0 rgba(255,255,255,0.28), 0 8px 24px -8px rgba(30,58,95,0.55)",
        backdropFilter: "blur(14px)",
        WebkitBackdropFilter: "blur(14px)",
        color: "white",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        cursor: "pointer",
        opacity: visible ? 1 : 0,
        transform: visible ? "translateY(0)" : "translateY(10px)",
        transition: "opacity 260ms ease, transform 260ms ease",
        pointerEvents: visible ? "auto" : "none",
      }}
    >
      <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
        <path d="M7 12V2M2 7l5-5 5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    </button>
  );
}

/* ----------------------------------------------------------------
 * Shell — Iteration 1. Below-the-fold sections follow in next passes.
 * ---------------------------------------------------------------- */
function App() {
  const [bookingOpen, setBookingOpen] = React.useState(false);
  const [verticalId, setVerticalId] = React.useState(null);
  const openBooking = React.useCallback(() => window.open(calcomUrl, "_blank", "noopener,noreferrer"), []);
  const closeBooking = React.useCallback(() => setBookingOpen(false), []);
  const vertical = verticalId ?
  window.VERTICALS.find((v) => v.id === verticalId) :
  null;

  return (
    <>
      <Header onBook={openBooking} />
      <main>
        <Hero onBook={openBooking} />
        <window.Problem vertical={vertical} />
        <window.VerticalSelector
          activeId={verticalId}
          onSelect={setVerticalId} />
        
        <window.Workflows vertical={vertical} />
        <window.EngagementStructure />
        <window.FridayReport />
        <window.Founder />
        <window.Pricing onBook={openBooking} />
        <window.FAQ />
        <window.LeadMagnet
          activeVerticalId={verticalId}
          onSelectVertical={setVerticalId} />
        
        <window.FinalCTA onBook={openBooking} />
      </main>
      <window.Footer />
      <BookingModal open={bookingOpen} onClose={closeBooking} />
      <BackToTop />
    </>);

}

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