/* ============================================================
   CSL Landing — Sections A: Header, Hero, Marquee, Founder, Work
   ============================================================ */
const { useState, useEffect, useRef } = React;
const NS = window.ContentStackLabDesignSystem_cbb53c;
const { Button } = NS;
const Ic = window.Icons;
const D = window.CSL;
const A = window.CSLAdmin || {};
function adminHero(pageSlug) {
  return A.heroes && A.heroes[pageSlug] ? A.heroes[pageSlug] : null;
}

/* reveal-on-scroll using GSAP & ScrollTrigger for high-performance animations, falling back to a scroll event observer if GSAP is unavailable. */
function useReveal() {
  React.useLayoutEffect(() => {
    if (window.gsap && window.ScrollTrigger) {
      window.gsap.registerPlugin(window.ScrollTrigger);

      // All motion (including smooth scroll) is skipped for users who ask for
      // reduced motion — CSS reveals are already transform-only and harmless.
      const mm = window.gsap.matchMedia();
      mm.add("(prefers-reduced-motion: no-preference)", () => {
      let lenis = null;
      let rafCallback = null;
      let handleAnchorClick = null;

      // Initialize Lenis smooth scroll
      if (window.Lenis) {
        lenis = new window.Lenis({
          duration: 1.2,
          easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)), // easeOutExpo
          orientation: 'vertical',
          gestureOrientation: 'vertical',
          smoothWheel: true,
        });

        // Sync ScrollTrigger on scroll
        lenis.on('scroll', window.ScrollTrigger.update);

        // Sync Lenis RAF with GSAP ticker
        rafCallback = (time) => {
          lenis.raf(time * 1000);
        };
        window.gsap.ticker.add(rafCallback);
        window.gsap.ticker.lagSmoothing(0);

        // Intercept anchor links for smooth kinetic scrolling to target
        handleAnchorClick = (e) => {
          const href = e.currentTarget.getAttribute('href');
          if (href && href.startsWith('#')) {
            e.preventDefault();
            if (href === '#top') {
              lenis.scrollTo(0);
            } else {
              const target = document.querySelector(href);
              if (target) {
                lenis.scrollTo(target);
              }
            }
          }
        };

        const anchors = document.querySelectorAll('a[href^="#"]');
        anchors.forEach(a => a.addEventListener('click', handleAnchorClick));
      }

      // 1. Initial page load stagger for Hero & Header
      const tl = window.gsap.timeline({ delay: 0.1 });
      
      // Animate header components (logo, navigation links, and CTA button)
      tl.fromTo(".hdr__logo, .hdr__link, .hdr .btn", 
        { opacity: 0, y: -15 },
        { opacity: 1, y: 0, duration: 0.6, stagger: 0.05, ease: "power2.out" }
      );
      
      // Animate Hero text and primary CTA buttons
      const heroInner = document.querySelector(".hero__inner");
      if (heroInner) {
        heroInner.classList.remove("reveal"); // Remove standard reveal behavior
        heroInner.style.transition = "none";
        
        tl.fromTo([".hero__copy h1, .hero-rich-heading", ".hero__lead", ".hero__cta .btn"],
          { opacity: 0, y: 35 },
          { opacity: 1, y: 0, duration: 0.9, stagger: 0.12, ease: "power3.out" },
          "-=0.45"
        );
      }
      
      // Section-Specific Storytelling Animations

      // Marquee scrubbing
      const marquee = document.querySelector('.marq__track');
      if (marquee) {
        window.gsap.to(marquee, {
          xPercent: -20,
          ease: "none",
          scrollTrigger: {
            trigger: ".marq",
            start: "top bottom",
            end: "bottom top",
            scrub: 1
          }
        });
      }

      // Founder photo parallax (the one continuous scroll effect we keep)
      const founderPhoto = document.querySelector('.founder__photo image-slot');
      if (founderPhoto) {
        window.gsap.fromTo(founderPhoto,
          { yPercent: -15, scale: 1.1 },
          { yPercent: 15, scale: 1, ease: "none", scrollTrigger: { trigger: ".founder__media", start: "top bottom", end: "bottom top", scrub: true } }
        );
      }

      // Per-section entrances (see HOME-ANIMATIONS.md) — transform ONLY,
      // never opacity, same safety rule as the generic reveals below.
      const enter = (sel, from, to, trigger, start) => {
        const els = document.querySelectorAll(sel);
        if (!els.length) return;
        els.forEach((el) => { el.style.transition = "none"; });
        window.gsap.fromTo(els, from, Object.assign({}, to, {
          clearProps: "transform",
          scrollTrigger: { trigger: trigger || els[0], start: start || "top 85%", once: true }
        }));
      };

      enter(".founder__quote, .founder__body p", { x: -30 }, { x: 0, duration: 0.8, stagger: 0.15, ease: "power2.out" }, ".founder__copy", "top 80%");
      enter(".work__card", { x: 50 }, { x: 0, duration: 0.8, stagger: 0.1, ease: "power3.out" }, ".work__scroller");
      enter(".svc__item", { x: -20 }, { x: 0, duration: 0.7, stagger: 0.1, ease: "power2.out" }, ".svc", "top 80%");
      enter(".rec__logo", { scale: 0.8 }, { scale: 1, duration: 0.7, stagger: 0.08, ease: "back.out(1.5)" }, ".rec__logos", "top 90%");
      enter(".tst", { scale: 0.95 }, { scale: 1, duration: 1, ease: "power2.out" });
      document.querySelectorAll(".step-row").forEach((el, i) => {
        el.style.transition = "none";
        window.gsap.fromTo(el,
          { x: i % 2 ? 40 : -40 },
          { x: 0, duration: 0.8, ease: "power2.out", clearProps: "transform", scrollTrigger: { trigger: el, start: "top 85%", once: true } }
        );
      });

      // Why cards keep their CSS resting rotation — clearProps hands the
      // transform back to the stylesheet after the entrance finishes.
      const whyCards = document.querySelectorAll('.why__card');
      if (whyCards.length) {
        window.gsap.fromTo(whyCards,
          { y: 40, rotationX: -15 },
          { y: 0, rotationX: 0, duration: 0.8, stagger: 0.1, ease: "power2.out", clearProps: "transform", scrollTrigger: { trigger: ".why__grid", start: "top 85%", once: true } }
        );
      }

      // One motion vocabulary: everything else enters with the same slide-up.
      // NOTE: scroll-triggered tweens animate transform ONLY — never opacity.
      // If they included opacity:0, any ScrollTrigger stall (crawler render,
      // CDN hiccup) would leave the whole page invisible. See csl.css .reveal.
      const els = document.querySelectorAll(".reveal");
      els.forEach((el) => {
        if (el.closest('.hero__inner') || el.closest('.why__card') || el.matches('.founder__copy, .svc__item, .step-row, .tst')) return;
        el.style.transition = "none";
        window.gsap.fromTo(el,
          { y: 30 },
          { y: 0, duration: 0.85, ease: "power2.out", scrollTrigger: { trigger: el, start: "top 90%", once: true } }
        );
      });

      return () => {
        if (lenis) {
          lenis.destroy();
        }
        if (rafCallback) {
          window.gsap.ticker.remove(rafCallback);
        }
        if (handleAnchorClick) {
          const anchors = document.querySelectorAll('a[href^="#"]');
          anchors.forEach(a => a.removeEventListener('click', handleAnchorClick));
        }
      };
      });

      return () => mm.revert();
    } else {
      // Fallback scroll check observer if GSAP is not available
      const els = [...document.querySelectorAll(".reveal")];
      els.forEach((el) => el.classList.add("pre"));
      const check = () => {
        const vh = window.innerHeight || document.documentElement.clientHeight;
        els.forEach((el) => {
          if (!el.classList.contains("pre")) return;
          const r = el.getBoundingClientRect();
          if (r.top < vh * 0.92 && r.bottom > 0) el.classList.remove("pre");
        });
      };
      check();
      window.addEventListener("scroll", check, { passive: true });
      window.addEventListener("resize", check);
      const t = setTimeout(() => els.forEach((el) => el.classList.remove("pre")), 1400);
      return () => {
        window.removeEventListener("scroll", check);
        window.removeEventListener("resize", check);
        clearTimeout(t);
      };
    }
  }, []);
}
window.useReveal = useReveal;

const Arrow = (p) => Ic.arrow({ width: 18, height: 18, ...p });

function hasHtmlMarkup(value) {
  return /<\/?[a-z][\s\S]*>/i.test(String(value || ""));
}

function RichHeroHeading({ value, fallback }) {
  const heading = value || fallback;
  if (hasHtmlMarkup(heading)) {
    return <div className="hero-rich-heading" role="heading" aria-level="1" dangerouslySetInnerHTML={{ __html: heading }} />;
  }
  const text = String(heading || "").trim();
  const needsDot = text && !/[.!?]$/.test(text);
  return <h1>{text}{needsDot ? <span className="dot">.</span> : null}</h1>;
}

function normalizeInlineHeroHtml(value) {
  return String(value || "")
    .replace(/<p><br><\/p>/gi, "")
    .replace(/<\/p>\s*<p>/gi, "<br>")
    .replace(/<\/?(p|div)[^>]*>/gi, "")
    .trim();
}

function RichDotTitle({ as = "h1", text, fallback, ...props }) {
  const Tag = as;
  const value = text || fallback || "";
  if (hasHtmlMarkup(value)) {
    const html = normalizeInlineHeroHtml(value);
    return <Tag {...props} dangerouslySetInnerHTML={{ __html: `${html}<span class="dot">.</span>` }} />;
  }
  return <Tag {...props}>{value}<span className="dot">.</span></Tag>;
}

window.CSLRichDotTitle = RichDotTitle;
function ConsultationCard({ slotId = "consultation-card-avatar", className = "" }) {
  const booking = (window.CSLAdmin && window.CSLAdmin.bookingCard) || {};
  const title = booking.heading || "Your Next 30 Minutes Could Change Your Marketing.";
  const ctaText = booking.ctaText || "Book a Free Call";
  const ctaLink = booking.calLink || "https://cal.com/contentstacklab/30min";
  const foot = booking.subheading || "Prefer email?";
  return (
    <div className={`faq-card faq-card--primary ${className}`.trim()}>
      <div className="faq-card__ava">
        <image-slot id={slotId} src="uploads/img-block.jpeg" shape="circle" fit="cover" placeholder="Photo"></image-slot>
      </div>
      <h3 className="faq-card__title">{title}</h3>
      <Button as="a" href={ctaLink} variant="inverse" block className="faq-card__btn">{ctaText}</Button>
      <div className="faq-card__foot">
        <span>{foot}{String(foot).includes("@") ? null : <><br/><a href="mailto:connect@contentstacklab.com">connect@contentstacklab.com</a></>}</span>
        <span className="arr" aria-hidden="true">{Ic.arrow({ width: 18, height: 18 })}</span>
      </div>
    </div>
  );
}

function SiteFooter() {
  const path = window.location.pathname;
  const isHome = path.endsWith("/") || path.includes("index");
  const quick = [
    ["case-studies", "Case Studies"],
    ["portfolio", "Portfolio"],
    ["services", "Services"],
    ["about", "About"],
    ["blog", "Blog"],
    ["contact", "Contact"]
  ];

  return (
    <footer className="ftr">
      <div className="wrap ftr__top">
        <div className="ftr__brand">
          <img className="ftr__logo" src="csl/assets/logo-wordmark.png" alt="Content Stack Lab"
            style={{ filter: "brightness(0) invert(1)" }} />
          <p className="ftr__about">Content Stack Lab is a B2B growth studio offering fractional marketing leadership, strategic projects, and AI readiness for tech companies worldwide.</p>
          <div style={{ marginTop: "var(--space-5)" }}>
            <Button as="a" href="contact" size="sm" iconRight={<Arrow />}>Get Started</Button>
          </div>
        </div>
        <div className="ftr__col">
          <h4>Quick links</h4>
          {quick.map(([href, label]) => <a key={label} href={href}>{label}</a>)}
        </div>
        <div className="ftr__col">
          <h4>Connect</h4>
          <a href="https://linkedin.com/in/sairaishtiaqahmad" target="_blank" rel="noopener">LinkedIn</a>
          <a href="https://youtube.com/@myorganisingstories" target="_blank" rel="noopener">Podcast</a>
          <a href="mailto:connect@contentstacklab.com">connect@contentstacklab.com</a>
        </div>
      </div>
      <div className="wrap ftr__bot">
        <span>© 2026 Content Stack Lab. All Rights Reserved.</span>
        <span style={{ display: "flex", gap: "var(--space-5)" }}><a href="privacy">Privacy Policy</a><a href="terms">Terms of Service</a></span>
      </div>
    </footer>
  );
}

/* ---------------- Header ---------------- */
function Header() {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 12);
    on(); window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => { if (e.key === "Escape") setMenuOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [menuOpen]);

  const isServicesPage = window.location.pathname.includes("services");
  const isServicesIndexPage = /\/services(\.html)?\/?$/.test(window.location.pathname);
  const isAboutPage = window.location.pathname.includes("about");
  const isContactPage = window.location.pathname.includes("contact");
  const isCaseStudiesIndexPage = window.location.pathname.includes("case-studies");
  const isCaseStudyDetailPage = window.location.pathname.includes("case-study") && !isCaseStudiesIndexPage;
  const isCaseStudiesPage = isCaseStudiesIndexPage || isCaseStudyDetailPage;
  const isPortfolioPage = window.location.pathname.includes("portfolio");
  const isBlogIndexPage = /\/blog(\.html)?\/?$/.test(window.location.pathname);
  const isBlogPostPage = window.location.pathname.includes("blog-post");
  const isBlogPage = isBlogIndexPage || isBlogPostPage;
  const isLegalPage = window.location.pathname.includes("privacy") || window.location.pathname.includes("terms");
  const isErrorPage = window.location.pathname.includes("404");

  const links = [
    ["work", "Case Studies", isCaseStudiesIndexPage ? "#top" : "case-studies"],
    ["services", "Services", isServicesIndexPage ? "#top" : "services"],
    ["about", "About", isAboutPage ? "#top" : "about"],
    ["portfolio", "Portfolio", isPortfolioPage ? "#top" : "portfolio"],
    ["blog", "Blog", isBlogIndexPage ? "#top" : "blog"]
  ];

  const isActive = (id) =>
    (isServicesPage && id === "services") || (isAboutPage && id === "about") || (isCaseStudiesPage && id === "work") || (isPortfolioPage && id === "portfolio") || (isBlogPage && id === "blog");

  return (
    <header className={"hdr" + (scrolled ? " scrolled" : "") + (menuOpen ? " menu-open" : "")}>
      <div className="wrap hdr__in">
        <a href={(isServicesPage || isAboutPage || isContactPage || isCaseStudiesPage || isPortfolioPage || isBlogPage || isLegalPage || isErrorPage) ? "./" : "#top"} aria-label="Content Stack Lab home">
          <img className="hdr__logo" src="csl/assets/logo-wordmark.png" alt="Content Stack Lab" />
        </a>
        <nav className="hdr__nav">
          {links.map(([id, label, href]) => (
            <a
              key={id}
              className={`hdr__link${isActive(id) ? " active" : ""}`}
              href={href}
              aria-current={isActive(id) ? "page" : undefined}
            >
              {label}
            </a>
          ))}
          <Button as="a" href="contact" size="sm" iconRight={<Arrow />}>
            Get Started
          </Button>
        </nav>
        <button
          className="hdr__burger"
          aria-label={menuOpen ? "Close menu" : "Open menu"}
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen(!menuOpen)}
        >
          {menuOpen ? (
            <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="4" y1="4" x2="18" y2="18" /><line x1="18" y1="4" x2="4" y2="18" /></svg>
          ) : (
            <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="3" y1="6" x2="19" y2="6" /><line x1="3" y1="11" x2="19" y2="11" /><line x1="3" y1="16" x2="19" y2="16" /></svg>
          )}
        </button>
      </div>
      <nav className={"hdr__menu" + (menuOpen ? " open" : "")} aria-label="Mobile">
        {links.map(([id, label, href]) => (
          <a
            key={id}
            className={"hdr__menu-link" + (isActive(id) ? " active" : "")}
            href={href}
            aria-current={isActive(id) ? "page" : undefined}
            onClick={() => setMenuOpen(false)}
          >
            {label}
          </a>
        ))}
        <a className="hdr__menu-link" href="contact" onClick={() => setMenuOpen(false)}>Contact</a>
        <div className="hdr__menu-cta">
          <Button as="a" href="contact" size="lg" iconRight={<Arrow />}>Get Started</Button>
        </div>
      </nav>
    </header>
  );
}

/* ---------------- Hero ---------------- */
function Hero() {
  const hero = adminHero("home");
  return (
    <section className="hero" id="top">
      <window.HeroShader />
      <div className="wrap hero__inner reveal">
        <div className="hero__copy">

          <RichHeroHeading value={hero && hero.heading} fallback={"I help <em>B2B tech</em> brands stop blending in and start <em>breaking through.</em>"} />
          <p className="hero__lead">{hero && hero.subheading ? hero.subheading : "Strategy, content, and visibility, built to generate pipeline, not just posts. For B2B tech companies done with random acts of marketing."}</p>
          <div className="hero__cta">
            <Button as="a" href={(hero && hero.ctaLink) || "contact"} size="lg" iconRight={<Arrow />}>{(hero && hero.ctaText) || "Let's talk growth"}</Button>
            <Button as="a" href="case-studies" size="lg" variant="secondary">See What That Looks Like</Button>
          </div>

        </div>
      </div>
    </section>
  );
}

/* ---------------- Marquee ---------------- */
function Marquee() {
  const row = [...D.brands, ...D.brands];
  return (
    <div className="marq">
      <div className="marq__label">Brands I've worked with. <b>Yes, the real ones.</b></div>
      <div className="marq__track">
        {row.map((b, i) => <span className="marq__item" key={i}>{b}</span>)}
      </div>
    </div>
  );
}

/* ---------------- Founder ---------------- */
function Founder() {
  return (
    <section className="sec sec--tint" id="about">
      <div className="founder__grid">
        <div className="founder__copy reveal">
          <p className="eyebrow">The human behind the strategy</p>
          <p className="founder__quote">I've been the in-house marketer. The agency hire. The founder figuring it out. That's why I get it<span className="dot">.</span></p>
          <div className="founder__body">
            {D.founderBody.map((t, i) => <p key={i}>{t}</p>)}
          </div>

          <Button as="a" href="about" variant="inverse" iconRight={<Arrow />}>Read the full story</Button>
        </div>
        <div className="founder__media reveal">
          <div className="founder__photo">
            <image-slot id="founder-portrait" src="uploads/img1.png" shape="rect" fit="cover"></image-slot>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Work carousel ---------------- */
function Work() {
  const { useRef: uR, useEffect: uE } = React;
  const ref = uR(null);
  const hovered = uR(false);
  const stopped = uR(false); // set on any manual interaction — auto-play never resumes
  const caseLinks = {
    OTNexus: "case-study?case=otnexus",
    "Sentinel EHS": "case-study?case=sentinel-ehs",
    "Sapphire Finishing Mills": "case-study?case=sapphire-finishing-mills",
    "Fatima Group": "case-study?case=fatima-group",
    "Irinatech Digital": "case-study?case=irinatech-digital"
  };

  const step = (dir) => {
    const el = ref.current;
    if (!el) return;
    const card = el.querySelector(".work__card");
    const dx = card ? card.offsetWidth + 24 : 360; // card width + gap
    el.scrollBy({ left: dir * dx, behavior: "smooth" });
  };

  uE(() => {
    const id = setInterval(() => {
      const el = ref.current;
      if (!el || hovered.current || stopped.current) return;
      if (el.scrollLeft + el.clientWidth >= el.scrollWidth - 10) {
        el.scrollTo({ left: 0, behavior: "smooth" });
      } else {
        step(1);
      }
    }, 4000);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="sec" id="work">
      <div className="wrap">
        <div className="work__head reveal">
          <div className="sec-head">
            <p className="eyebrow">Recent work</p>
            <h2>The proof is in the pipeline<span className="dot">.</span></h2>
            <p>Real brands. Real problems. Real outcomes.</p>
          </div>
          <div className="work__nav">
            <button className="work__nav-btn" aria-label="Previous projects" onClick={() => { stopped.current = true; step(-1); }}>{Ic.chevL({ width: 20, height: 20 })}</button>
            <button className="work__nav-btn" aria-label="Next projects" onClick={() => { stopped.current = true; step(1); }}>{Ic.chevR({ width: 20, height: 20 })}</button>
          </div>
        </div>
        <div
          className="work__scroller"
          ref={ref}
          onMouseEnter={() => { hovered.current = true; }}
          onMouseLeave={() => { hovered.current = false; }}
          onPointerDown={() => { stopped.current = true; }}
        >
          {D.work.map((w) => (
            <a className="work__card" href={w.href || "case-studies"} key={w.href || w.brand}>
              <div className="work__thumb" style={{ background: w.g }}>
                <image-slot src={w.image || ""} shape="rect" placeholder="Drop project image" fit="cover"></image-slot>
              </div>
              <div className="work__info">
                <h3 className="work__title">{w.brand}</h3>
                <span className="work__tag">{w.tag}</span>
              </div>
            </a>
          ))}
        </div>
        <div style={{ marginTop: "var(--space-6)" }} className="reveal">
          <Button as="a" href="case-studies" variant="ghost" iconRight={<Arrow />}>See all case studies</Button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Header, Hero, Marquee, Founder, Work, Arrow, ConsultationCard, SiteFooter });
