/* Genesis DMA — homepage */
const { useMemo: _umemo, useRef: _uref2, useEffect: _ueff2, useState: _ust2 } = React;

const CAP_CARDS = [
  ['paid-media', 'Paid media',       'Meta and Google ad systems that generate qualified leads.',        'Bolt'],
  ['search',     'Search & GEO',     'Rank on Google and get cited by ChatGPT, Claude and Perplexity.',   'Search'],
  ['crm',        'CRM',              'GoHighLevel implementations that close more of the leads you have.', 'Flow'],
  ['automation', 'Automation & AI',  'Custom n8n workflows and AI agents that remove repetitive work.',   'Chip'],
  ['content',    'Content',          'Ad copy, landing pages and scripts engineered for conversion.',     'Pen'],
  ['analytics',  'Analytics',        'Call tracking, attribution and reporting built on real data.',      'Chart'],
];

const VERTICALS = ['Cleaning','Auto detailing','MedSpas','HVAC','Dental','Landscaping','Coworking','Medical','Roofing','Legal','Fitness','Pest control'];

const PHILOSOPHY = [
  ['Systems over tactics.',   'Tactics stop working. Systems keep compounding because they are built to be measured, improved and extended.'],
  ['Data over opinions.',     'We do not argue about creative or channels. We put a number on it, ship the test, and let the data end the conversation.'],
  ['Compound over campaigns.','A campaign ends. A system that generates leads, converts them and learns from every deal keeps paying for years.'],
];

const PROCESS = [
  ['Audit',    'Trace where leads come from, where they stall, and what the real unit economics say.'],
  ['Strategy', 'Pick the channels, offers and targets that fit your economics — not last year\'s playbook.'],
  ['Build',    'Stand up accounts, tracking, CRM, automations and landing pages before spending a dollar.'],
  ['Launch',   'Go live in controlled phases. Daily feedback loops for the first 30 days.'],
  ['Scale',    'Once unit economics are proven, scale spend, expand channels and compound.'],
];

/* --- Manifesto with word-by-word reveal --- */
function Manifesto() {
  const ref = _uref2(null);
  _ueff2(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { el.classList.add('is-visible'); io.disconnect(); } });
    }, { threshold: 0.35 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const line1 = ['We', "don't", 'run', 'ads.'];
  const line2 = ['We', 'build', 'systems', 'that', 'compound.'];
  return (
    <section className="container-x py-16 md:py-24 cv-auto">
      <p ref={ref} className="manifesto font-semibold text-white" style={{ fontSize: 'clamp(2.5rem, 7vw, 6rem)', lineHeight: 1.02, letterSpacing: '-0.03em' }}>
        {line1.map((w, i) => <span key={'a'+i} className="manifesto-word" style={{ ['--i']: i }}>{w}&nbsp;</span>)}
        <br/>
        {line2.map((w, i) => {
          const kw = w === 'systems' || w === 'compound.';
          return <span key={'b'+i} className={`manifesto-word ${kw ? 'kw' : ''}`} style={{ ['--i']: line1.length + i }}>{w}&nbsp;</span>;
        })}
      </p>
    </section>
  );
}

/* --- Hero --- */
function MobileConstellation() {
  // Three orbits tilted at different angles, each carrying one planet.
  // Rendered in SVG, viewBox 400x400, centered at (200, 200).
  // Only visible on mobile via CSS.
  return (
    <div className="mobi-orbit" aria-hidden="true">
      <svg viewBox="0 0 400 400">
        <defs>
          <radialGradient id="mocore" cx="0.5" cy="0.5" r="0.5">
            <stop offset="0%" stopColor="#2dd4bf" stopOpacity="0.9"/>
            <stop offset="45%" stopColor="#22d3ee" stopOpacity="0.5"/>
            <stop offset="100%" stopColor="#2dd4bf" stopOpacity="0"/>
          </radialGradient>
          <radialGradient id="moplanet" cx="0.35" cy="0.35" r="0.65">
            <stop offset="0%" stopColor="#1a1a1a"/>
            <stop offset="100%" stopColor="#050505"/>
          </radialGradient>
        </defs>

        {/* Background stars (static twinkle) */}
        <circle className="mo-star" cx="60"  cy="80"  r="1.2" fill="#2dd4bf"/>
        <circle className="mo-star" cx="340" cy="120" r="1"   fill="#2dd4bf"/>
        <circle className="mo-star" cx="80"  cy="320" r="1.4" fill="#2dd4bf"/>
        <circle className="mo-star" cx="330" cy="300" r="1"   fill="#2dd4bf"/>
        <circle className="mo-star" cx="200" cy="40"  r="1.2" fill="#2dd4bf"/>

        {/* Outer dashed ring (horizontal ellipse) */}
        <g className="mo-spin s3">
          <ellipse className="mo-ring dashed" cx="200" cy="200" rx="170" ry="60"/>
          <g className="mo-planet" transform="translate(370 200)">
            <circle r="12" fill="url(#moplanet)" stroke="rgba(45,212,191,0.5)" strokeWidth="1"/>
            {/* TikTok mark simplified */}
            <path d="M-3 -5 v7 a3 3 0 1 1 -2.5 -3" fill="none" stroke="#fff" strokeWidth="1.4" strokeLinecap="round"/>
            <path d="M-3 -5 a5 5 0 0 0 4 4" fill="none" stroke="#25F4EE" strokeWidth="1.4" strokeLinecap="round"/>
          </g>
        </g>

        {/* Mid ring (tilted ellipse) */}
        <g className="mo-spin s2" style={{ transformOrigin: '200px 200px' }}>
          <g transform="rotate(-22 200 200)">
            <ellipse className="mo-ring" cx="200" cy="200" rx="130" ry="48"/>
            <g className="mo-planet" transform="translate(330 200)">
              <circle r="10" fill="url(#moplanet)" stroke="rgba(45,212,191,0.5)" strokeWidth="1"/>
              {/* Meta infinity */}
              <path d="M-5 0 c0 -3 2 -4 4 -2 s3 4 5 4 s3 -2 3 -4 s-2 -4 -4 -2 s-3 4 -5 4 s-3 -1 -3 -4" fill="none" stroke="#22d3ee" strokeWidth="1.2" strokeLinecap="round"/>
            </g>
          </g>
        </g>

        {/* Inner ring (tilted other way) */}
        <g className="mo-spin s1" style={{ transformOrigin: '200px 200px' }}>
          <g transform="rotate(28 200 200)">
            <ellipse className="mo-ring" cx="200" cy="200" rx="90" ry="32" strokeOpacity="0.5"/>
            <g className="mo-planet" transform="translate(110 200)">
              <circle r="9" fill="url(#moplanet)" stroke="rgba(45,212,191,0.5)" strokeWidth="1"/>
              {/* Google G letter */}
              <text x="0" y="3" textAnchor="middle" fontFamily="sans-serif" fontWeight="700" fontSize="10" fill="#4285F4">G</text>
            </g>
          </g>
        </g>

        {/* Central core — Genesis G */}
        <g className="mo-core">
          <circle cx="200" cy="200" r="34" fill="url(#mocore)"/>
          <circle className="mo-core-pulse" cx="200" cy="200" r="18"
            fill="#0a0a0a" stroke="#2dd4bf" strokeWidth="1.3"/>
          <text x="200" y="206" textAnchor="middle" fontFamily="serif" fontStyle="italic"
            fontWeight="700" fontSize="22" fill="#2dd4bf"
            style={{ letterSpacing: '-0.04em' }}>G</text>
        </g>
      </svg>
    </div>
  );
}

function Hero() {
  return (
    <section className="relative" style={{ minHeight: '100vh' }}>
      <MobileConstellation />
      <div className="container-x relative z-10 flex flex-col justify-center" style={{ minHeight: '100vh', paddingTop: '7rem' }}>
        <Reveal className="text-teal text-xs tracking-[0.25em] uppercase mb-8 flex items-center gap-3">
          <span className="inline-block w-8 h-px bg-teal" /> Growth agency · Houston, TX
        </Reveal>
        <Reveal as="h1" className="font-semibold text-white max-w-5xl" style={{ fontSize: 'clamp(3rem, 8vw, 7rem)', lineHeight: 0.98, letterSpacing: '-0.035em' }}>
          Growth systems for <span className="text-teal">service businesses</span> that refuse to guess.
        </Reveal>
        <Reveal delay={120} className="text-sub text-lg md:text-xl mt-8 max-w-2xl" style={{ lineHeight: 1.55 }}>
          Genesis DMA builds paid media, CRM, automation and content systems that turn budget into predictable pipeline — measured to the dollar.
        </Reveal>
        <Reveal delay={240} className="mt-12 flex flex-wrap gap-4">
          <BtnPrimary href="#/contact">Start a conversation</BtnPrimary>
          <BtnGhost href="#/capabilities/paid-media">See our capabilities</BtnGhost>
        </Reveal>
        <div className="hidden md:flex absolute left-1/2 -translate-x-1/2 bottom-10 flex-col items-center gap-3">
          <span className="text-[10px] tracking-[0.3em] text-muted uppercase">Scroll</span>
          <div className="scroll-ind" aria-hidden="true" />
        </div>
      </div>
    </section>
  );
}

/* --- Capabilities grid --- */
function CapabilitiesGrid() {
  return (
    <Section id="capabilities" label="Capabilities" title="Six disciplines. One connected system."
      intro="Each of these stands alone. None of them should. They compound when they ship together.">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-px bg-line">
        {CAP_CARDS.map(([slug, title, desc, icon], i) => {
          const Ic = Ico[icon];
          return (
            <Reveal key={slug} delay={i * 60}>
              <a href={`#/capabilities/${slug}`} className="cap-card block h-full" aria-label={title}>
                <div className="flex items-start justify-between">
                  <div className="text-teal"><Ic /></div>
                  <span className="text-xs text-muted font-mono">0{i+1}</span>
                </div>
                <h3 className="text-2xl font-semibold text-white mt-10" style={{ letterSpacing: '-0.02em' }}>{title}</h3>
                <p className="text-sub mt-3 leading-relaxed">{desc}</p>
                <div className="mt-10 flex items-center gap-3 text-teal text-sm font-medium">
                  <span>Explore</span>
                  <span className="arrow"><Ico.Arrow /></span>
                </div>
              </a>
            </Reveal>
          );
        })}
      </div>
    </Section>
  );
}

/* --- Marquee of verticals --- */
function Marquee() {
  const items = [...VERTICALS, ...VERTICALS];
  return (
    <section aria-label="Verticals we serve" className="py-10 md:py-14 border-t border-b border-line cv-auto">
      <div className="container-x mb-10 flex items-baseline justify-between gap-6">
        <div className="text-teal text-xs tracking-[0.25em] uppercase">Who we work with</div>
        <div className="text-sub text-sm hidden md:block">Service businesses with strong unit economics and an appetite for scale.</div>
      </div>
      <div className="marquee">
        <div className="marquee-track">
          {items.map((v, i) => (
            <div key={i} className="flex items-center gap-16 text-3xl md:text-5xl font-light text-sub whitespace-nowrap" style={{ letterSpacing: '-0.02em' }}>
              <span>{v}</span>
              <span className="text-teal text-2xl">·</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* --- Philosophy --- */
function Philosophy() {
  return (
    <Section id="philosophy" label="Philosophy" title="Three ideas we refuse to give up on.">
      <div className="grid grid-cols-1 md:grid-cols-3 gap-10 md:gap-8">
        {PHILOSOPHY.map(([t, d], i) => (
          <Reveal key={i} delay={i*100} className="philos-item">
            <h3 className="text-white font-semibold" style={{ fontSize: 'clamp(1.75rem, 2.5vw, 2.25rem)', lineHeight: 1.1, letterSpacing: '-0.02em' }}>{t}</h3>
            <p className="text-sub mt-5 leading-relaxed">{d}</p>
          </Reveal>
        ))}
      </div>
    </Section>
  );
}

/* --- Process timeline (sticky SVG fill) --- */
function ProcessTimeline() {
  const wrapRef = _uref2(null);
  const pathRef = _uref2(null);
  _ueff2(() => {
    const wrap = wrapRef.current, path = pathRef.current; if (!wrap || !path) return;
    const total = path.getTotalLength(); path.style.strokeDasharray = total; path.style.strokeDashoffset = total;
    let raf = 0;
    const update = () => {
      const r = wrap.getBoundingClientRect();
      const vh = window.innerHeight;
      const start = r.top - vh * 0.6;
      const end = r.bottom - vh * 0.4;
      const p = Math.min(1, Math.max(0, (0 - start) / (end - start)));
      path.style.strokeDashoffset = total * (1 - p);
      raf = 0;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    window.addEventListener('scroll', onScroll, { passive: true });
    update();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <Section id="process" label="Process" title="How work actually gets done." intro="Five stages, running in sequence the first time and in parallel from then on.">
      <div ref={wrapRef} className="relative">
        <svg className="hidden md:block absolute left-[47px] top-0 bottom-0" width="2" height="100%" preserveAspectRatio="none" viewBox="0 0 2 1000" aria-hidden="true">
          <line x1="1" y1="0" x2="1" y2="1000" stroke="#1f1f1f" strokeWidth="2" />
          <line ref={pathRef} x1="1" y1="0" x2="1" y2="1000" stroke="#2dd4bf" strokeWidth="2" />
        </svg>
        <ol className="space-y-14 md:space-y-20">
          {PROCESS.map(([t, d], i) => (
            <Reveal as="li" key={t} delay={i*80} className="relative md:pl-28">
              <div className="hidden md:flex absolute left-0 top-1 w-24 items-center gap-4">
                <span className="relative z-10 w-8 h-8 rounded-full bg-bg border-2 border-teal flex items-center justify-center">
                  <span className="w-1.5 h-1.5 bg-teal rounded-full" />
                </span>
              </div>
              <div className="flex items-center gap-4 mb-3">
                <span className="step-num">0{i+1}</span>
                <span className="h-px flex-1 bg-line md:hidden" />
              </div>
              <h3 className="text-white font-semibold" style={{ fontSize: 'clamp(1.75rem, 3vw, 2.5rem)', lineHeight: 1.05, letterSpacing: '-0.02em' }}>{t}</h3>
              <p className="text-sub mt-4 max-w-xl leading-relaxed">{d}</p>
            </Reveal>
          ))}
        </ol>
      </div>
    </Section>
  );
}

/* --- Metrics --- */
function Metrics() {
  const data = [
    [127,  '+', 'Businesses served',             'Across cleaning, HVAC, dental, medspas and more.'],
    [4.2,  'M', 'Ad spend managed',               'Across Meta, Google and partner platforms.', '$', 'in'],
    [6,     '', 'Capability pillars',             'Media, search, CRM, automation, content, analytics.'],
    [247,   '',  'Automated workflows live',       'Handling the repetitive work across our client base.'],
  ];
  return (
    <Section id="metrics" label="Track record" title="The numbers we share out loud.">
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-px bg-line">
        {data.map((row, i) => {
          const [num, suffix, title, caption, prefix = '', mid = ''] = row;
          return (
            <Reveal key={i} delay={i*80} className="bg-bg p-8 md:p-10">
              <div className="text-teal font-semibold" style={{ fontSize: 'clamp(2.5rem, 5vw, 4.5rem)', letterSpacing: '-0.03em', lineHeight: 1 }}>
                {Number.isInteger(num)
                  ? <>{prefix}<Counter to={num} />{suffix}</>
                  : <><Counter to={Math.round(num*10)} prefix={prefix} />{(mid ? '/' : '')}{suffix}</>}
              </div>
              <div className="mt-6 text-white font-medium">{title}</div>
              <div className="mt-1 text-muted text-sm">{caption}</div>
            </Reveal>
          );
        })}
      </div>
    </Section>
  );
}

/* --- Final CTA --- */
function FinalCTA() {
  return (
    <section className="container-x py-16 md:py-24">
      <div className="relative max-w-5xl mx-auto text-center">
        <div aria-hidden="true" className="absolute -inset-20 -z-10 dot-grid opacity-40" />
        <Reveal as="h2" className="text-white font-semibold" style={{ fontSize: 'clamp(2.5rem, 6vw, 5rem)', lineHeight: 1.02, letterSpacing: '-0.03em' }}>
          Ready to build something that <span className="text-teal">compounds?</span>
        </Reveal>
        <Reveal delay={120} className="text-sub mt-6 max-w-2xl mx-auto text-lg">
          Book a 30-minute call. Bring your numbers. Leave with a plan you can run with or without us.
        </Reveal>
        <Reveal delay={220} className="mt-12 flex flex-wrap justify-center gap-4">
          <BtnPrimary href="#/contact">Start a conversation</BtnPrimary>
          <BtnGhost href="#/about">Read the philosophy</BtnGhost>
        </Reveal>
      </div>
    </section>
  );
}

/* --- Home page --- */
function HomePage() {
  useSEO({
    title: 'Genesis DMA — Growth agency for service businesses',
    description: 'Genesis DMA builds paid media, CRM, automation and content systems for service businesses across the United States. Based in Houston, TX.',
    path: '/',
    jsonLd: [
      ldOrganization(),
      ldWebsite(),
      {
        "@context": "https://schema.org",
        "@type": "ItemList",
        "name": "Capabilities",
        "itemListElement": Object.values(SERVICES).map((s, i) => ({
          "@type": "ListItem", "position": i+1, "name": s.title,
          "url": SITE.url + "/capabilities/" + s.slug,
        })),
      },
    ],
  });
  return (
    <main>
      <div className="relative overflow-hidden">
        <Orb />
        {/* fade orbital layer out as Manifesto ends */}
        <div aria-hidden="true" className="absolute inset-x-0 bottom-0 pointer-events-none" style={{ height: '280px', background: 'linear-gradient(to bottom, transparent, #0a0a0a)' }} />
        <Hero />
        <Manifesto />
      </div>
      <CapabilitiesGrid />
      <Marquee />
      <Philosophy />
      <ProcessTimeline />
      <Metrics />
      <FinalCTA />
    </main>
  );
}

Object.assign(window, { HomePage });
