/* AIReady™ Services — sections */
(function () {
  const { Button, Badge, Eyebrow, Card } = window.GaiaAlliesDesignSystem_6e4515;
  const wrap = { maxWidth: 1180, margin: '0 auto', padding: '0 40px' };
  const DIAG = 'https://diagnostic.gaiaallies.com/score';
  const OH = '/office-hours';

  function HeroSvc() {
    return (
      <section id="top" className="s-midnight" style={{ paddingBlock: 96 }}>
        <div style={wrap}>
          <Eyebrow>AIReady™ · Services</Eyebrow>
          <h1 style={{ fontSize: 'clamp(2.5rem, 4.6vw, 3.8rem)', margin: '20px 0 0', maxWidth: 900 }}>
            From owning your AI to <em>hours back on every matter.</em>
          </h1>
          <p className="lead" style={{ marginTop: 22, maxWidth: 600 }}>
            The return is hours back on every matter, faster turnarounds, and fewer errors, from the AI your firm can already reach.
          </p>
          <div style={{ display: 'flex', gap: 14, marginTop: 32, flexWrap: 'wrap', alignItems: 'center' }}>
            <Button variant="primary" size="lg" href={DIAG}>Take the free benchmark</Button>
            <span style={{ fontSize: 14, color: 'var(--fg-quiet)' }}>No pressure, no commitment. The benchmark is always free.</span>
          </div>
        </div>
      </section>
    );
  }

  const CAL = 'https://calendly.com/amy-adams/discovery';
  const ACAD = '/academy';

  // One service = one self-explanatory panel. No separate pages.
  const SERVICES = [
    {
      id: 'office-hours', tab: 'Office Hours', audience: 'For you and your firm',
      summary: 'The simplest way to work with me: bring a real decision and leave with a clear next step.',
      get: [
        'A 60-minute working session on a decision in front of you right now: a tool choice, a workflow, a policy question, or a vendor contract.',
        'A specific, reasoned recommendation you can act on the same week, not a list of options to weigh later.',
        'A written follow-up the next day: the recommendation, the reasoning behind it, and the exact next steps.',
        'Any templates, prompts, or vetted vendor shortlists from prior firm engagements that apply to your question.',
      ],
      who: 'Firms not ready for a full engagement, or anyone who wants a fast, expert read on a single decision.',
      cta: 'Book Office Hours', href: OH,
    },
    {
      id: 'roadmap', tab: 'Roadmap', audience: 'For you and your firm',
      summary: 'A scored diagnosis of where your firm stands, and a prioritized 90-day plan to move.',
      get: [
        'A full audit of your current tools, workflows, and data practices, mapped against where AI can safely create leverage.',
        'A scored AIReady baseline across people, process, and technology, benchmarked against comparable firms.',
        'A prioritized 90-day implementation plan with named tools, assigned owners, and the hours each workflow is expected to save.',
        'An AI use policy and governance framework drafted to your jurisdiction and bar rules, ready for the firm to adopt.',
        'A live working session to walk partners and staff through the plan and answer questions in the room.',
      ],
      who: 'Firms ready to commit to a plan and put AI to work with confidence.',
      cta: 'Book a consult', href: CAL,
    },
    {
      id: 'advisor', tab: 'Advisory', audience: 'For you and your firm',
      summary: 'An ongoing partner who keeps your firm current as the tools, the rules, and your team evolve.',
      get: [
        'A named advisor on call for tool questions, vendor reviews, and judgment calls as they come up.',
        'Quarterly strategy reviews that reset priorities as your firm and the technology change.',
        'The Pulse, a continuous intelligence read on legal-AI tools, rulings, and bar guidance, delivered to your inbox.',
        'Governance and policy updates kept current as regulations and ethics opinions shift.',
        'First look at new tools, evaluated hands-on before they ever reach a client matter.',
      ],
      who: 'Firms that want AI handled, not managed: a partner who stays ahead so they do not have to.',
      cta: 'Book a consult', href: CAL,
    },
    {
      id: 'training', tab: 'Training', audience: 'For your team',
      summary: 'Live, role-based training on your firm’s real matters, for attorneys, paralegals, and staff.',
      get: [
        'Live, hands-on sessions built around your firm’s actual matters and document types, not generic demos.',
        'Separate role-based tracks for attorneys, paralegals, and administrative staff, each scoped to their work.',
        'A firm-specific prompt library and workflow playbook your team keeps and reuses after the sessions end.',
        'Recorded sessions and reference guides you can hand to every new hire.',
        'A post-training competency check, so you know the skills actually landed.',
      ],
      who: 'Firms that want their whole team confident and consistent with AI.',
      cta: 'Book a consult', href: CAL,
    },
    {
      id: 'academy', tab: 'Academy', audience: 'For your team',
      summary: 'Self-paced, CLE-track certification for the whole firm, built around the work your team does every day.',
      get: [
        'Self-paced video modules covering legal-specific AI workflows, available the moment a team member needs them.',
        'CLE-track certification on completion, documented for each participant.',
        'A firm dashboard to track every team member’s progress and certification status.',
        'A library that grows and updates as the tools, rulings, and bar guidance change.',
        'Whole-firm licensing at a flat rate, so cost does not cap who gets trained.',
      ],
      who: 'Firms that want scalable, always-on AI training. Launching soon.',
      cta: 'Join the waitlist', href: ACAD,
    },
  ];

  function scrollToServicesSection(behavior) {
    const sec = document.getElementById('services');
    if (!sec) return;
    const header = document.querySelector('header');
    const offset = 0;
    const top = sec.getBoundingClientRect().top + window.scrollY - offset;
    window.scrollTo({ top, behavior: behavior || 'auto' });
  }

  function ServicesList() {
    const idx = (h) => Math.max(0, SERVICES.findIndex(s => s.id === h));
    const [active, setActive] = React.useState(
      () => idx((typeof location !== 'undefined' ? location.hash : '').replace('#', ''))
    );
    const applyServiceHash = React.useCallback((behavior) => {
      const h = location.hash.replace('#', '');
      if (!SERVICES.some(s => s.id === h)) return;
      setActive(idx(h));
      requestAnimationFrame(() => {
        requestAnimationFrame(() => scrollToServicesSection(behavior));
      });
    }, []);
    React.useLayoutEffect(() => {
      applyServiceHash('auto');
      window.addEventListener('hashchange', onHash);
      window.addEventListener('load', onLoad);
      return () => {
        window.removeEventListener('hashchange', onHash);
        window.removeEventListener('load', onLoad);
      };
      function onHash() { applyServiceHash('smooth'); }
      function onLoad() { applyServiceHash('auto'); }
    }, [applyServiceHash]);
    const tablistRef = React.useRef(null);
    const wrapRef = React.useRef(null);
    const tabRefs = React.useRef([]);
    const firstTabScroll = React.useRef(true);
    const updateScrollState = React.useCallback(() => {
      const list = tablistRef.current;
      const wrap = wrapRef.current;
      if (!list || !wrap) return;
      if (!window.matchMedia('(max-width: 860px)').matches) {
        wrap.classList.remove('at-start', 'at-end', 'no-overflow');
        return;
      }
      const atStart = list.scrollLeft <= 2;
      const atEnd = list.scrollLeft + list.clientWidth >= list.scrollWidth - 2;
      const noOverflow = list.scrollWidth <= list.clientWidth + 2;
      wrap.classList.toggle('at-start', atStart);
      wrap.classList.toggle('at-end', atEnd);
      wrap.classList.toggle('no-overflow', noOverflow);
    }, []);
    const scrollActiveTabIntoView = React.useCallback((behavior) => {
      if (!window.matchMedia('(max-width: 860px)').matches) return;
      const tab = tabRefs.current[active];
      if (!tab) return;
      tab.scrollIntoView({ behavior: behavior || 'smooth', block: 'nearest', inline: 'center' });
    }, [active]);
    const scrollTabsBy = (direction) => {
      const list = tablistRef.current;
      const tabs = tabRefs.current.filter(Boolean);
      if (!list || !tabs.length) return;
      const center = list.getBoundingClientRect().left + list.clientWidth / 2;
      let nearest = 0;
      let minDist = Infinity;
      tabs.forEach((tab, i) => {
        const rect = tab.getBoundingClientRect();
        const dist = Math.abs(rect.left + rect.width / 2 - center);
        if (dist < minDist) {
          minDist = dist;
          nearest = i;
        }
      });
      const next = Math.max(0, Math.min(tabs.length - 1, nearest + direction));
      tabs[next].scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
    };
    React.useLayoutEffect(() => {
      scrollActiveTabIntoView(firstTabScroll.current ? 'auto' : 'smooth');
      firstTabScroll.current = false;
      requestAnimationFrame(updateScrollState);
    }, [scrollActiveTabIntoView, updateScrollState]);
    React.useEffect(() => {
      const list = tablistRef.current;
      if (!list) return;
      updateScrollState();
      list.addEventListener('scroll', updateScrollState, { passive: true });
      window.addEventListener('resize', updateScrollState);
      return () => {
        list.removeEventListener('scroll', updateScrollState);
        window.removeEventListener('resize', updateScrollState);
      };
    }, [updateScrollState]);
    const s = SERVICES[active];
    return (
      <section id="services" className="s-white" style={{ paddingTop: 40, paddingBottom: 96 }}>
        <div style={wrap}>
          <Eyebrow>Services</Eyebrow>
          <h2 style={{ marginTop: 18, maxWidth: 640 }}>
            <span style={{ whiteSpace: 'nowrap' }}>Enter wherever your firm is,</span>{' '}
            <em>and grow from there.</em>
          </h2>

          <div ref={wrapRef} className="services-tablist-wrap">
            <button
              type="button"
              className="services-tablist-nav services-tablist-nav--prev"
              aria-label="Scroll tabs left"
              onClick={() => scrollTabsBy(-1)}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" aria-hidden="true">
                <path d="M15 18l-6-6 6-6" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          <div ref={tablistRef} role="tablist" className="services-tablist" style={{ marginTop: 36, display: 'flex', flexWrap: 'nowrap', gap: 8, borderBottom: '1px solid var(--border)', paddingBottom: 0 }}>
            {SERVICES.map((t, i) => {
              const on = i === active;
              return (
                <button
                  key={t.id}
                  ref={(el) => { tabRefs.current[i] = el; }}
                  role="tab"
                  aria-selected={on}
                  onClick={() => { setActive(i); if (history.replaceState) history.replaceState(null, '', '#' + t.id); }}
                  style={{
                    appearance: 'none', cursor: 'pointer', background: 'none', border: 'none',
                    font: 'inherit', fontSize: 15, fontWeight: on ? 700 : 500, whiteSpace: 'nowrap', flexShrink: 0,
                    color: on ? 'var(--ink-green)' : 'var(--fg-muted)',
                    padding: '12px 18px', position: 'relative', marginBottom: -1,
                    borderBottom: on ? '2px solid var(--gold-deep)' : '2px solid transparent',
                  }}
                >
                  {t.tab}
                </button>
              );
            })}
          </div>
            <button
              type="button"
              className="services-tablist-nav services-tablist-nav--next"
              aria-label="Scroll tabs right"
              onClick={() => scrollTabsBy(1)}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" aria-hidden="true">
                <path d="M9 18l6-6-6-6" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          </div>

          <div style={{ marginTop: 40, display: 'grid', gridTemplateColumns: '1.05fr 0.95fr', gap: 56, alignItems: 'start' }}>
            <div>
              <h3 style={{ margin: 0, fontSize: 'clamp(1.8rem, 2.6vw, 2.4rem)', color: 'var(--ink-green)', lineHeight: 1.1 }}>{s.tab}</h3>
              <p className="lead" style={{ margin: '16px 0 0', maxWidth: '46ch' }}>{s.summary}</p>
              <p style={{ margin: '20px 0 0', fontSize: 14.5, color: 'var(--fg-muted)', maxWidth: '46ch' }}><strong style={{ color: 'var(--ink-green)' }}>Who it serves:</strong> {s.who}</p>
              <div style={{ marginTop: 30 }}>
                <Button variant="primary" size="lg" href={s.href}>{s.cta}</Button>
              </div>
            </div>
            <Card variant="outline" style={{ padding: 32 }}>
              <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--gold-deep)' }}>What you receive</span>
              <ul style={{ listStyle: 'none', margin: '18px 0 0', padding: 0, display: 'flex', flexDirection: 'column', gap: 14 }}>
                {s.get.map((g, gi) => (
                  <li key={gi} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', fontSize: 15.5, color: 'var(--ink-green)', lineHeight: 1.5 }}>
                    <span aria-hidden="true" style={{ color: 'var(--gold-deep)', fontWeight: 700, lineHeight: 1.5, flex: 'none' }}>✓</span>
                    <span>{g}</span>
                  </li>
                ))}
              </ul>
            </Card>
          </div>
        </div>
      </section>
    );
  }

  function TrustStandardSvc() {
    const points = [
      ['Governance architecture', 'A documented AI governance architecture: use policies, decision rights, approval workflows, and an audit trail, drafted to your jurisdiction and bar rules.'],
      ['Confidentiality & privilege', 'Client confidentiality and privilege protected by default: data residency, retention, and vendor terms reviewed before anything touches a matter.'],
      ['Professional responsibility', 'Duties of competence, supervision, and candor addressed up front, so adoption holds up to bar scrutiny, not just internal review.'],
      ['Embedded, not bolted on', 'Woven through every engagement, across the roadmap, training, and advisory, so defensibility stays continuous as tools and rules change.'],
    ];
    return (
      <section className="s-deep" style={{ paddingBlock: 96 }}>
        <div style={{ ...wrap, display: 'grid', gridTemplateColumns: '0.9fr 1.1fr', gap: 56, alignItems: 'start' }}>
          <div>
            <Eyebrow>The AI Trust Standard</Eyebrow>
            <h2 style={{ marginTop: 18 }}>Defensible by design, <em>from the first matter.</em></h2>
            <p style={{ marginTop: 16, maxWidth: 440 }}>
              AI only creates leverage when it can withstand scrutiny. The AI Trust Standard is the governance layer beneath every engagement: the policies, controls, and ethical guardrails that let your firm adopt new tools without exposing client data, privilege, or your license.
            </p>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            {points.map(([h, b]) => (
              <Card key={h} variant="outline" style={{ padding: 22 }}>
                <h3 style={{ color: 'var(--ice)', margin: '0 0 6px', fontSize: '1.05rem' }}>{h}</h3>
                <p style={{ margin: 0, fontSize: 14 }}>{b}</p>
              </Card>
            ))}
          </div>
        </div>
      </section>
    );
  }

  function CTASvc() {
    return (
      <section id="benchmark" className="s-green" style={{ paddingBlock: 96 }}>
        <div style={{ ...wrap, textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <h2 style={{ maxWidth: 800 }}>See your firm clearly, <em>then move with conviction.</em></h2>
          <p className="lead" style={{ marginTop: 16, textAlign: 'center', maxWidth: 660 }}>
            Every sound AI strategy begins with an honest assessment. The AIReady benchmark measures your firm across people, process, and technology in five minutes and returns a scored baseline with your highest-return next step, at no cost and no commitment.
          </p>
          <div style={{ marginTop: 30 }}>
            <Button variant="primary" size="lg" href={DIAG}>Take the free benchmark</Button>
          </div>
        </div>
      </section>
    );
  }

  Object.assign(window, { HeroSvc, ServicesList, TrustStandardSvc, CTASvc });
})();
