/* global React, ReactDOM, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakToggle, TweakSlider, TweakText, TweakSelect */

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

// ────────────────────────────────────────────────────────────
// Reveal — IntersectionObserver-driven blur+y entrance
// (replaces Framer Motion's <motion.div initial whileInView>)
// ────────────────────────────────────────────────────────────
function Reveal({
  as: Tag = 'div',
  delay = 0,
  blur = 10,
  y = 28,
  x = 0,
  duration = 1000,
  threshold = 0.2,
  once = true,
  className = '',
  style,
  children,
  ...rest
}) {
  // Animation removed sitewide — render content immediately, fully visible.
  return (
    <Tag className={className} style={style} {...rest}>
      {children}
    </Tag>);
}

// ────────────────────────────────────────────────────────────
// BlurWords — splits text into per-word spans and reveals
//   each with a staggered blur+y entrance.
// ────────────────────────────────────────────────────────────
function BlurWords({ text, baseDelay = 0, stagger = 80, className = '' }) {
  const words = text.split(' ');
  return (
    <span className={'blur-words ' + className}>
      {words.map((w, i) =>
        <span key={i} className="blur-word-wrap">
          <Reveal
            as="span"
            delay={baseDelay + i * stagger}
            blur={10}
            y={22}
            duration={2000}
            className="blur-word">
            {w}
          </Reveal>
          {i < words.length - 1 ? '\u00A0' : ''}
        </span>
      )}
    </span>);
}

// ────────────────────────────────────────────────────────────
// MagneticCTA — primary CTA that pulls toward the cursor on hover
// ────────────────────────────────────────────────────────────
function MagneticCTA({ as: Tag = 'a', strength = 0.35, children, className = '', ...rest }) {
  const ref = useRef(null);
  return (
    <Tag
      ref={ref}
      className={'magnetic-cta ' + className}
      {...rest}>
      <span className="cta-inner">{children}</span>
    </Tag>);
}

// ────────────────────────────────────────────────────────────
// Top bar
// ────────────────────────────────────────────────────────────
function TopBar() {
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    document.body.classList.toggle('mobile-nav-open', menuOpen);
  }, [menuOpen]);

  return (
    <>
      <header className="topbar">
        <div className="topbar-left">
        <a href="/" className="brand" aria-label="CenterSet home">
          <img src={(window.__resources && window.__resources.logo) || "assets/logo-reversed.png?v=5"} alt="CenterSet" className="brand-logo" />
        </a>
        <nav className="topnav">
          <a href="about.html">About</a>
          <a href="challenge.html">The Challenge</a>
          <a href="technology.html">Technology</a>
          <a href="news.html">News</a>
          <a href="team.html">Team</a>
        </nav>
        </div>
        <div className="topbar-actions">
        <a href="contact.html" className="nav-cta">Contact</a>
        <button
          className={'mobile-menu-btn' + (menuOpen ? ' open' : '')}
          aria-label="Menu"
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen(o => !o)}>
          <span></span><span></span><span></span>
        </button>
        </div>
      </header>

      <div className={'mobile-nav-overlay' + (menuOpen ? ' open' : '')}>
        <nav>
          <a href="about.html" onClick={() => setMenuOpen(false)}>About</a>
          <a href="challenge.html" onClick={() => setMenuOpen(false)}>The Challenge</a>
          <a href="technology.html" onClick={() => setMenuOpen(false)}>Technology</a>
          <a href="team.html" onClick={() => setMenuOpen(false)}>Team</a>
          <a href="contact.html" onClick={() => setMenuOpen(false)}>Contact</a>
        </nav>
        <div className="statuspill">
          <span className="dot"></span>
          <span>R&amp;D Phase · Prelaunch</span>
        </div>
      </div>
    </>);
}

// ────────────────────────────────────────────────────────────
// Animated dot grid background — fades + drifts subtly
// ────────────────────────────────────────────────────────────
function DotGrid() {
  return <div className="dotgrid" aria-hidden="true"></div>;
}

// ────────────────────────────────────────────────────────────
// Headline variants — split into BlurWords for stagger entrance
// ────────────────────────────────────────────────────────────
function Headline({ variant }) {
  const parts = useMemo(() => {
    if (variant === 'rethink') {
      return {
        a: 'We rethought',
        b: 'the centerline',
        sub: ['A new class of downhole tooling, engineered to redefine how casing finds its true center — by the team behind the last generation of subsea firsts.']
      };
    }
    if (variant === 'never') {
      return {
        a: 'Off-center is acceptable',
        b: 'Not anymore',
        sub: ['A new approach to keeping casing where it belongs — at the center of the hole, all the way down. Coming soon from the team behind a decade of subsea firsts.']
      };
    }
    return {
      a: 'CenterSet',
      b: 'Developing a New Hydrostatically Activated Casing Centralizer',
      sub: [
        'Built in Aberdeen, working directly with the operators and engineers who\u2019ll run it.'
      ]
    };
  }, [variant]);

  return (
    <div className="headline-wrap" style={{ display: 'contents' }}>
      <h1 className="headline headline--sentence" key={variant}>
        {parts.b}
      </h1>
      {parts.sub.map((s, i) =>
        <p key={i} className="subline" style={{ marginTop: i === 0 ? undefined : '12px' }}>
          {s}
        </p>
      )}
    </div>);
}

// ────────────────────────────────────────────────────────────
// Hero CTAs — primary "Request access" jumps to form, secondary "Follow"
// ────────────────────────────────────────────────────────────
function HeroCTAs({ delay = 0 }) {
  return (
    <div className="hero-ctas">
      <MagneticCTA as="a" href="https://form.jotform.com/260543000463040" target="_blank" rel="noopener noreferrer" className="cta-primary" strength={0.28}>
        Join our early access programme
        <span className="cta-arrow">→</span>
      </MagneticCTA>
      <MagneticCTA
        as="a"
        href="https://linkedin.com/company/centerset"
        target="_blank"
        rel="noopener noreferrer"
        className="cta-secondary"
        strength={0.18}>
        View Development Updates
        <span className="cta-arrow">↗</span>
      </MagneticCTA>
    </div>);
}

// ────────────────────────────────────────────────────────────
// Countdown
// ────────────────────────────────────────────────────────────
function Countdown({ targetISO }) {
  const target = useMemo(() => new Date(targetISO).getTime(), [targetISO]);
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, target - now);
  const days = Math.floor(diff / 86400000);
  const hours = Math.floor(diff % 86400000 / 3600000);
  const mins = Math.floor(diff % 3600000 / 60000);
  const secs = Math.floor(diff % 60000 / 1000);
  const pad = (n) => String(n).padStart(2, '0');
  return (
    <div className="countdown">
      <div className="cdown-unit"><span className="cdown-n">{pad(days)}</span><span className="cdown-l">DAYS</span></div>
      <span className="cdown-sep">:</span>
      <div className="cdown-unit"><span className="cdown-n">{pad(hours)}</span><span className="cdown-l">HRS</span></div>
      <span className="cdown-sep">:</span>
      <div className="cdown-unit"><span className="cdown-n">{pad(mins)}</span><span className="cdown-l">MIN</span></div>
      <span className="cdown-sep">:</span>
      <div className="cdown-unit"><span className="cdown-n">{pad(secs)}</span><span className="cdown-l">SEC</span></div>
    </div>);
}

// ────────────────────────────────────────────────────────────
// Capabilities — three cards with hover lift
// ────────────────────────────────────────────────────────────
function Capabilities() {
  const items = [
    { num: '01 / Geometry', title: 'Concentric, by design.',
      body: 'A redesigned profile that resists off-center loading where it matters most — through the curve, through the build, through the long lateral.' },
    { num: '02 / Install', title: 'Run-in without compromise.',
      body: 'Engineered to set itself, hold itself, and stay out of the way of the cement job — repeatably, joint after joint.' },
    { num: '03 / Aftermath', title: 'A better bond.',
      body: 'When casing finds true center, cement does the rest. Our test data points one way. We\'ll be sharing it soon.' }
  ];
  return (
    <section className="capabilities" id="tech">
      {items.map((it, i) =>
        <Reveal key={it.num} className="cap" delay={i * 140} y={32} blur={10} duration={1000}>
          <div className="cap-num">{it.num}</div>
          <div className="cap-title">{it.title}</div>
          <div className="cap-body">{it.body}</div>
        </Reveal>
      )}
    </section>);
}

// ────────────────────────────────────────────────────────────
// Pipe strip — full-width pipe illustration
// ────────────────────────────────────────────────────────────
function PipeStrip() {
  return (
    <section className="pipestrip" aria-hidden="true">
      <Reveal as="img" duration={1400} y={0} blur={14} threshold={0.15}
        src={(window.__resources && window.__resources.pipeImg) || "assets/pipe-illustration-v2.png"}
        alt=""
        className="pipestrip-img"
        style={{ padding: "0px 400px 0px 0px" }} />
      <div className="pipestrip-scan"></div>
    </section>);
}

// ────────────────────────────────────────────────────────────
// Milestones — real updates shared on LinkedIn, paraphrased,
// with a link through to the full feed
// ────────────────────────────────────────────────────────────
function Milestones() {
  const items = [
    { tag: 'Facilities', date: 'April 2026', text: 'CenterSet moves into ETZ\u2019s brand new Energy Works facility in Altens, Aberdeen \u2014 the Energy Transition Zone\u2019s I-Zero 1 building.', image: 'assets/milestones/izero-facility.png', postUrl: 'https://www.linkedin.com/feed/update/urn:li:activity:7452367634320433153' },
    { tag: 'Prototype', date: 'June 2026', text: 'Market research feedback moves through engineering analysis and peer review to prototype testing \u2014 all in a matter of weeks.', image: 'assets/milestones/prototype-machining.png', postUrl: 'https://www.linkedin.com/feed/update/urn:li:activity:7475812661629390848' },
    { tag: 'Founder update', date: 'August 2026', text: 'Founder & CEO Tristam Horn reflects on CenterSet\u2019s first few months \u2014 the strategic decisions, the team coming together, and the market research shaping our R&D.', image: 'assets/milestones/tristam-interview.jpg', postUrl: 'https://www.linkedin.com/feed/update/urn:li:activity:7490399114615037954' }
  ];
  return (
    <section className="content-section" id="milestones">
      <div className="content-inner">
        <div className="section-head">
          <Reveal className="eyebrow" delay={0} y={10} blur={6} duration={700}>
            <span className="dash"></span><span>From LinkedIn</span><span className="dash"></span>
          </Reveal>
          <Reveal as="h2" delay={120} y={20} blur={8} duration={900}>
            Milestones along the way
          </Reveal>
          <Reveal className="section-head-sub" delay={240} y={14} blur={6} duration={900}>
            A running log of what we&rsquo;re building, shared first on LinkedIn.
          </Reveal>
        </div>
        <div className="milestones-grid">
          {items.map((it, i) =>
            <Reveal key={it.tag + i} as="a" href={it.postUrl} target="_blank" rel="noopener noreferrer" className="milestone-card" delay={i * 90} y={14} blur={6} duration={800}>
              <div className="milestone-photo">
                <img src={it.image} alt="" />
                <div className="milestone-photo-overlay"><span>View post on LinkedIn</span><span className="arrow">↗</span></div>
              </div>
              <div className="milestone-card-body">
                <span className="milestone-tag">{it.tag}</span>
                <div className="milestone-text">{it.text}</div>
                <div className="milestone-date">{it.date}</div>
              </div>
            </Reveal>
          )}
        </div>
        <Reveal delay={items.length * 90 + 100} y={12} blur={6} duration={800} style={{ textAlign: 'center', marginTop: '32px' }}>
          <a className="teaser-link" href="https://linkedin.com/company/centerset" target="_blank" rel="noopener noreferrer">
            <span>View all updates on LinkedIn</span>
            <span className="arrow">↗</span>
          </a>

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

function ProgressCarousel() {
  const stages = [
    { state: 'done', label: 'Industry problem identification', status: 'Complete', summary: 'Extensive conversations with operators and engineers confirmed standoff and drag as the priority.' },
    { state: 'done', label: 'Initial concept development', status: 'Complete', summary: 'Early design concepts developed around the trade-offs identified in the field.' },
    { state: 'done', label: 'Market validation and industry feedback', status: 'Complete', summary: 'Ongoing engagement with industry professionals to pressure-test assumptions.' },
    { state: 'current', label: 'Prototype design and development', status: 'In progress', summary: 'Functional prototype in development, moving toward bench and lab testing.' },
    { state: 'todo', label: 'Engineering testing and evaluation', status: 'Upcoming', summary: 'Validating performance against our design objectives.' },
    { state: 'todo', label: 'Field trial programme', status: 'Upcoming', summary: 'Live well testing with operating partners.' },
    { state: 'todo', label: 'Commercial introduction', status: 'Upcoming', summary: 'Full commercial availability.' }
  ];
  const trackRef = useRef(null);
  const cardRefs = useRef([]);
  const currentIndex = stages.findIndex(s => s.state === 'current');
  const [activeIndex, setActiveIndex] = useState(currentIndex);

  const scrollToIndex = useCallback((i, behavior) => {
    const card = cardRefs.current[i];
    const track = trackRef.current;
    if (!card || !track) return;
    const targetLeft = card.offsetLeft - (track.clientWidth - card.offsetWidth) / 2;
    track.scrollTo({ left: targetLeft, behavior: behavior || 'smooth' });
  }, []);

  const goTo = useCallback((i) => {
    const clamped = Math.max(0, Math.min(stages.length - 1, i));
    setActiveIndex(clamped);
    scrollToIndex(clamped);
  }, [scrollToIndex, stages.length]);

  useEffect(() => {
    scrollToIndex(currentIndex, 'auto');
  }, []);

  // Keep activeIndex in sync when the user scrolls/swipes manually,
  // so the arrows always continue from wherever they actually are.
  useEffect(() => {
    const track = trackRef.current;
    if (!track) return undefined;
    let raf = null;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = null;
        const trackCenter = track.scrollLeft + track.clientWidth / 2;
        let closest = 0;
        let closestDist = Infinity;
        cardRefs.current.forEach((card, i) => {
          if (!card) return;
          const cardCenter = card.offsetLeft + card.offsetWidth / 2;
          const dist = Math.abs(cardCenter - trackCenter);
          if (dist < closestDist) { closestDist = dist; closest = i; }
        });
        setActiveIndex(closest);
      });
    };
    track.addEventListener('scroll', onScroll, { passive: true });
    return () => track.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <section className="content-section progress-section" id="roadmap">
      <div className="content-inner">
        <div className="section-head">
          <Reveal className="eyebrow" delay={0} y={10} blur={6} duration={700}>
            <span className="dash"></span><span>Current Progress</span><span className="dash"></span>
          </Reveal>
          <Reveal as="h2" delay={120} y={20} blur={8} duration={900}>
            Tracking Our Journey
          </Reveal>
          <Reveal className="section-head-sub" delay={240} y={14} blur={6} duration={900}>
            We&rsquo;re making steady progress and sharing the journey as we go. Scroll or swipe to explore each stage.
          </Reveal>
        </div>
      </div>
      <div className="progress-carousel-wrap">
        <button className="progress-arrow left" aria-label="Previous stage" onClick={() => goTo(activeIndex - 1)} disabled={activeIndex === 0}>&larr;</button>
        <div className="progress-carousel" ref={trackRef}>
          {stages.map((s, i) =>
            <div
              key={i}
              ref={el => cardRefs.current[i] = el}
              className={'progress-card ' + s.state}>
              <div className="progress-card-mark">{s.state === 'done' ? '✓' : s.state === 'current' ? '●' : ''}</div>
              <div className="progress-card-label">{s.label}</div>
              <div className="progress-card-status">{s.status}</div>
              <div className="progress-card-summary">{s.summary}</div>
            </div>
          )}
        </div>
        <button className="progress-arrow right" aria-label="Next stage" onClick={() => goTo(activeIndex + 1)} disabled={activeIndex === stages.length - 1}>&rarr;</button>
      </div>
    </section>);
}

function GetInvolved() {
  return (
    <section className="content-section get-involved-section" id="get-involved">
      <div className="content-inner">
        <div className="section-head get-involved-box">
          <Reveal className="eyebrow" delay={0} y={10} blur={6} duration={700}>
            <span className="dash"></span><span>Getting Involved</span><span className="dash"></span>
          </Reveal>
          <Reveal as="h2" delay={120} y={20} blur={8} duration={900}>
            Shaping What Comes Next
          </Reveal>
          <Reveal className="section-head-sub" delay={240} y={14} blur={6} duration={900}>
            Whether you&rsquo;re interested in field trials, investment, or joining the team, CenterSet is being built in conversation with the industry it serves. We&rsquo;d like to hear from you.
          </Reveal>
          <Reveal delay={360} y={12} blur={6} duration={800} style={{ marginTop: '28px' }}>
            <MagneticCTA as="a" href="contact.html" className="cta-primary" strength={0.22}>
              Get in touch
              <span className="cta-arrow">→</span>
            </MagneticCTA>
          </Reveal>
        </div>
      </div>
    </section>);
}

function Footer() {
  return (
    <footer className="footer" id="contact">
      <a href="index.html">© 2026 CenterSet Ltd · Aberdeen, Scotland</a>
      <div className="footer-right">
        <a href="index.html" className="footer-tagline">Centralize without the drag</a>
        <a href="privacy.html">Privacy Policy</a>
        <a href="https://www.linkedin.com/company/centerset/" target="_blank" rel="noopener noreferrer">LinkedIn</a>
        <a href="mailto:info@centerset.com">info@centerset.com</a>
      </div>
    </footer>);
}

// ────────────────────────────────────────────────────────────
// Value proposition — problem / difference / benefit
// (reuses the .cap card styling already established by Capabilities)
// ────────────────────────────────────────────────────────────
// ────────────────────────────────────────────────────────────
// ────────────────────────────────────────────────────────────
// Homepage intro sections 1–4 — each its own full-width section,
// following the same centered eyebrow/h2/body pattern used on
// every other page, just kept brief. Optional "Learn more" link.
// ────────────────────────────────────────────────────────────
function HomeIntroSection({ id, eyebrow, heading, body, ctaHref, ctaLabel, ivory, imageSrc, imageAlt, imagePosition, quoteText }) {
  if (quoteText) {
    return (
      <section className={'content-section home-intro-section home-intro-section--split' + (ivory ? ' section-ivory' : '')} id={id}>
        <div className="content-inner">
          <div className="home-intro-split">
            <div className="home-intro-split-text">
              <Reveal className="eyebrow" delay={0} y={10} blur={6} duration={700}>
                <span className="dash"></span><span>{eyebrow}</span><span className="dash"></span>
              </Reveal>
              <Reveal as="h2" delay={120} y={20} blur={8} duration={900}>
                {heading}
              </Reveal>
              <Reveal className="section-head-sub" delay={240} y={14} blur={6} duration={900}>
                {body}
              </Reveal>
              {ctaHref &&
                <Reveal delay={340} y={10} blur={6} duration={700}>
                  <a className="teaser-link" href={ctaHref}>
                    <span>{ctaLabel}</span><span className="arrow">→</span>
                  </a>
                </Reveal>}
            </div>
            <div className="home-intro-split-media">
              <Reveal delay={200} y={20} blur={8} duration={900}>
                <div className="quote-card">
                  <div className="quote-mark">&ldquo;</div>
                  <p>{quoteText}</p>
                  <div className="quote-mark-close">&rdquo;</div>
                </div>
              </Reveal>
            </div>
          </div>
        </div>
      </section>);
  }
  if (imageSrc) {
    const isLeft = imagePosition === 'left';
    return (
      <section className={'content-section home-intro-section home-intro-section--split' + (ivory ? ' section-ivory' : '')} id={id}>
        <div className="content-inner">
          <div className={'home-intro-split' + (isLeft ? ' home-intro-split--reverse' : '')}>
            <div className="home-intro-split-text">
              <Reveal className="eyebrow" delay={0} y={10} blur={6} duration={700}>
                <span className="dash"></span><span>{eyebrow}</span><span className="dash"></span>
              </Reveal>
              <Reveal as="h2" delay={120} y={20} blur={8} duration={900}>
                {heading}
              </Reveal>
              <Reveal className="section-head-sub" delay={240} y={14} blur={6} duration={900}>
                {body}
              </Reveal>
            </div>
            <div className="home-intro-split-media">
              <Reveal delay={200} y={20} blur={8} duration={900}>
                <img src={imageSrc} alt={imageAlt || ''} className="home-intro-split-img" />
              </Reveal>
              {ctaHref &&
                <Reveal delay={340} y={10} blur={6} duration={700}>
                  <a className="teaser-link" href={ctaHref}>
                    <span>{ctaLabel}</span><span className="arrow">→</span>
                  </a>
                </Reveal>}
            </div>
          </div>
        </div>
      </section>);
  }
  return (
    <section className={'content-section home-intro-section' + (ivory ? ' section-ivory' : '')} id={id}>
      <div className="content-inner">
        <div className="section-head">
          <Reveal className="eyebrow" delay={0} y={10} blur={6} duration={700}>
            <span className="dash"></span><span>{eyebrow}</span><span className="dash"></span>
          </Reveal>
          <Reveal as="h2" delay={120} y={20} blur={8} duration={900}>
            {heading}
          </Reveal>
          <Reveal className="section-head-sub" delay={240} y={14} blur={6} duration={900}>
            {body}
          </Reveal>
          {ctaHref &&
            <Reveal delay={340} y={10} blur={6} duration={700}>
              <a className="teaser-link" href={ctaHref}>
                <span>{ctaLabel}</span><span className="arrow">→</span>
              </a>
            </Reveal>}
        </div>
      </div>
    </section>);
}

function HomeIntroGrid() {
  return (
    <>
      <HomeIntroSection
        id="what-is"
        eyebrow="Our Development"
        heading="A New Approach to Centralization"
        body="A casing centralizer is a critical well construction tool that keeps casing centered within the wellbore during cementing. Conventional designs can introduce complexity, risk and compromise in demanding applications. CenterSet&rsquo;s approach is built to address those limitations directly." />
      <HomeIntroSection
        id="value"
        eyebrow="The Problem"
        heading="Challenges Facing Well Construction"
        body="Traditional casing centralisers often require a compromise between standoff performance and running forces, contributing to poor cement placement and inadequate zonal isolation. These challenges are well understood, yet conventional technology has remained largely unchanged for decades."
        imageSrc="assets/problem-illustration.png"
        imageAlt="Line-art illustration of the CenterSet centralizer"
        ctaHref="challenge.html" ctaLabel="See the challenge" ivory />
      <HomeIntroSection
        id="technology-teaser"
        eyebrow="Our Approach"
        heading="Engineered Around the Restriction"
        body="Rather than compromise, CenterSet&rsquo;s centralizer runs low-profile until it reaches the point that matters, then activates under controllable pressure, separating running performance from centralization performance, with standoff that can be progressed in stages to guard against differential sticking."
        imageSrc="assets/approach-product-animated.webp"
        imageAlt="CenterSet centralizer in its activated configuration"
        imagePosition="left"
        ctaHref="technology.html" ctaLabel="Explore the technology" />
      <HomeIntroSection
        id="industry-input"
        eyebrow="Industry Input"
        heading="Grounded in Operator Feedback"
        body="Every stage of CenterSet&rsquo;s development is shaped by direct conversations with the operators and engineers who&rsquo;ll run this technology in the field, not assumptions made in isolation. That ongoing engagement continues to shape our design objectives and priorities."
        quoteText="The priority is reliably getting to bottom first, then achieving adequate stand-off within those constraints."
        ctaHref="about.html" ctaLabel="Read our story" ivory />
    </>);
}

// ────────────────────────────────────────────────────────────
// Explore grid — compact 3-column teaser linking to About /
// Challenge / Insights, replacing three separate full sections
// ────────────────────────────────────────────────────────────
function ExploreGrid() {
  const items = [
    {
      eyebrow: 'About', title: 'Why we started CenterSet.',
      body: 'How we listen to industry before building, the objectives that guide us, and where development stands today.',
      href: 'about.html', label: 'Read our story'
    },
    {
      eyebrow: 'Industry challenges', title: 'The challenges haven\u2019t changed. The solutions should.',
      body: 'Stand-off, drag and torque, restricted IDs, performance \u2014 the same issues, still costing time and money.',
      href: 'challenge.html', label: 'See the challenges with centralizers'
    },
    {
      eyebrow: 'Technology', title: 'Design in Motion.',
      body: 'CAD visualisations exploring how the concept could transition between non-activated and activated states.',
      href: 'technology.html', label: 'See the centralizer technology'
    },
    {
      eyebrow: 'Meet the team', title: 'The people behind CenterSet.',
      body: 'We\u2019re building a team around unique engineering, industry insight and operational understanding.',
      href: 'team.html', label: 'Meet the team'
    },
    {
      eyebrow: 'Contact', title: 'Let\u2019s talk.',
      body: 'Have feedback, an application to discuss, or a question about the company? Get in touch.',
      href: 'contact.html', label: 'Get in touch'
    }
  ];
  return (
    <section className="content-section explore-section" id="explore">
      <div className="content-inner">
        <div className="explore-grid">
          {items.map((it, i) =>
            <Reveal key={it.href} className="explore-card" delay={i * 110} y={22} blur={8} duration={900}>
              <div className="eyebrow"><span className="dash"></span><span>{it.eyebrow}</span></div>
              <h3>{it.title}</h3>
              <p>{it.body}</p>
              <a className="teaser-link" href={it.href}>
                <span>{it.label}</span>
                <span className="arrow">→</span>
              </a>
            </Reveal>
          )}
        </div>
      </div>
    </section>);
}

// ────────────────────────────────────────────────────────────
// Tweaks panel
// ────────────────────────────────────────────────────────────
function Tweaks({ t, setTweak }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Look">
        <TweakRadio
          label="Accent"
          value={t.accent}
          options={[
            { value: 'khaki', label: 'Khaki' },
            { value: 'slate', label: 'Slate' },
            { value: 'amber', label: 'Amber' }
          ]}
          onChange={(v) => setTweak('accent', v)} />
        <TweakToggle
          label="Scanlines"
          value={t.scanlines}
          onChange={(v) => setTweak('scanlines', v)} />
      </TweakSection>

      <TweakSection label="Copy">
        <TweakRadio
          label="Headline"
          value={t.headlineVariant}
          options={[
            { value: 'centerline', label: 'Center' },
            { value: 'rethink', label: 'Rethink' },
            { value: 'never', label: 'Never' }
          ]}
          onChange={(v) => setTweak('headlineVariant', v)} />
      </TweakSection>

      <TweakSection label="Sections">
        <TweakToggle
          label="Show countdown"
          value={t.showCountdown}
          onChange={(v) => setTweak('showCountdown', v)} />
        <TweakToggle
          label="Show capabilities"
          value={t.showCapabilities}
          onChange={(v) => setTweak('showCapabilities', v)} />
        <TweakText
          label="Launch date (ISO)"
          value={t.launchDate}
          onChange={(v) => setTweak('launchDate', v)} />
      </TweakSection>
    </TweaksPanel>);
}

// ────────────────────────────────────────────────────────────
// App
// ────────────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(window.__TWEAK_DEFAULTS__);
  const heroVideoRef = useRef(null);

  useEffect(() => {
    document.documentElement.setAttribute('data-accent', t.accent);
    document.documentElement.setAttribute('data-scan', String(!!t.scanlines));
  }, [t.accent, t.scanlines]);

  // Some mobile browsers (notably iOS Safari and some Android WebViews)
  // check the `muted` HTML attribute before React attaches it as a
  // property, and/or reject an immediate play() call before the video
  // has buffered any data — both silently leave the native "play button"
  // overlay showing on top of the poster. Force muted explicitly, retry
  // play() as data becomes available, and retry once more on first touch
  // as a last-resort fallback.
  useEffect(() => {
    const v = heroVideoRef.current;
    if (!v) return undefined;
    v.muted = true;
    v.defaultMuted = true;
    v.setAttribute('muted', '');
    v.setAttribute('playsinline', '');
    v.setAttribute('webkit-playsinline', '');

    let cancelled = false;
    const tryPlay = () => {
      if (cancelled) return;
      const p = v.play();
      if (p && typeof p.catch === 'function') p.catch(() => {});
    };

    tryPlay();
    v.addEventListener('loadedmetadata', tryPlay);
    v.addEventListener('canplay', tryPlay);
    v.addEventListener('canplaythrough', tryPlay);
    document.addEventListener('touchstart', tryPlay, { once: true, passive: true });
    document.addEventListener('click', tryPlay, { once: true });

    if (v.readyState === 0) v.load();

    return () => {
      cancelled = true;
      v.removeEventListener('loadedmetadata', tryPlay);
      v.removeEventListener('canplay', tryPlay);
      v.removeEventListener('canplaythrough', tryPlay);
      document.removeEventListener('touchstart', tryPlay);
      document.removeEventListener('click', tryPlay);
    };
  }, []);

  return (
    <div className="page">
      {/* DotGrid removed */}
      <div className="bg-grain"></div>
      <div className="bg-scan"></div>
      <div className="bg-spotlight"></div>
      <div className="bg-vignette"></div>
      <div className="blueprint-bg"></div>

      <div className="hero-header-wrap">
        <video
          ref={heroVideoRef}
          className="hero-bg-video-el"
          src="assets/centralizer-orbit.mp4"
          poster="assets/orbit-frame.jpg"
          autoPlay loop muted playsInline
          aria-hidden="true" />
        <div className="hero-bg-overlay"></div>

        <TopBar />

        <main className="hero hero-bg-video">
          {/* Centered text composition on top */}
          <div className="hero-text">
            <Headline variant={t.headlineVariant} />
            <HeroCTAs delay={600} />
            {t.showCountdown && <Countdown targetISO={t.launchDate} />}
          </div>
        </main>
      </div>

      {t.showCapabilities && <Capabilities />}
      <HomeIntroGrid />
      <ProgressCarousel />
      <GetInvolved />
      {/* <Milestones /> — removed per homepage restructure */}
      {/* <ExploreGrid /> — removed per request */}
      {/* <PipeStrip /> — removed per request */}
      {/* <FollowStrip /> — moved to team.html per request */}
      {/* <CareersStrip /> — removed per request; careers CTA now lives on contact.html */}
      <Footer />

      <Tweaks t={t} setTweak={setTweak} />
      <div className="watermark-single"></div>
    </div>);
}

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