/* ============================================================
   Services — Onyx-style pinned horizontal rail.
   Uses the same structural pattern as the sample services section.
   ============================================================ */
const { useEffect, useRef } = React;

const SERVICES = [
  {
    num: '[ 01 ]',
    title: 'Modern business websites',
    body: 'A premium, mobile-first website that makes your business look trustworthy, explains your offer clearly and turns visitors into enquiries.',
    href: '#contact',
    tags: ['Custom design', 'Mobile-first', 'SEO ready', 'Enquiry focused'],
    media: 'linear-gradient(145deg, #9be8dd 0%, #8ad0e6 48%, #7fd8e0 100%)',
  },
  {
    num: '[ 02 ]',
    title: 'AI chatbots & WhatsApp automation',
    body: 'Smart chat and WhatsApp flows that answer common questions, capture leads, route enquiries and help customers get faster responses.',
    href: '#contact',
    tags: ['AI chat', 'WhatsApp flows', 'Lead capture', 'Fast replies'],
    media: 'linear-gradient(145deg, #8b5cf6 0%, #9be8dd 50%, #ffffff 100%)',
  },
  {
    num: '[ 03 ]',
    title: 'CRM & lead management systems',
    body: 'A simple system to track enquiries, follow-ups, customer status and team activity — so good leads do not get lost in calls or spreadsheets.',
    href: '#contact',
    tags: ['CRM', 'Lead tracking', 'Follow-ups', 'Customer records'],
    media: 'linear-gradient(145deg, #0A0C18 5%, #1b1e30 60%, #262b47 100%)',
  },
  {
    num: '[ 04 ]',
    title: 'Dashboards & workflow automation',
    body: 'Clear dashboards and automated workflows for sales, operations and support — giving owners better visibility with less manual checking.',
    href: '#contact',
    tags: ['Dashboards', 'Workflows', 'Reports', 'Operations'],
    media: 'linear-gradient(145deg, #141827 0%, #8b5cf6 52%, #9be8dd 100%)',
  },
  {
    num: '[ 05 ]',
    title: 'Hosting, integrations & ongoing support',
    body: 'We keep your digital system online, secure and improving — including hosting, backups, integrations, monitoring and optimization.',
    href: '#contact',
    tags: ['Hosting', 'Integrations', 'Backups', 'Optimization'],
    media: 'linear-gradient(145deg, #111827 0%, #26324d 48%, #9be8dd 100%)',
  },
];

function ServicesCard({ item }) {
  return (
    <article className="svc_card">
      <div className="svc_card-content">
        <div className="svc_num">{item.num}</div>
        <div className="svc_card-info">
          <h3>{item.title}</h3>
          <p>{item.body}</p>
        </div>
        <a href={item.href} className="svc_link">
          View details
          <svg viewBox="0 0 12 12" fill="none"><path d="M4.7.75h5.83v5.8M.53 10.75 10.29.99" stroke="currentColor" strokeWidth="1.5" /></svg>
        </a>
      </div>
      <div className="svc_card-media" style={{ backgroundImage: item.media }}>
        <div className="svc_tags" aria-hidden="true">
          {item.tags.map((tag) => <span key={tag}>{tag}</span>)}
        </div>
      </div>
    </article>
  );
}

function serviceScrollTo(e, href) {
  e.preventDefault();
  const el = document.querySelector(href);
  if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 72, behavior: 'smooth' });
}

function Services() {
  const triggerRef = useRef(null);
  const trackRef = useRef(null);

  useEffect(() => {
    const trigger = triggerRef.current;
    const track = trackRef.current;
    if (!trigger || !track) return;

    let isTicking = false;
    let maxX = 0;
    let lastHeight = 0;
    let lastX = null;
    let rafId = null;
    let resizeRaf = null;

    const isDesktop = () => window.innerWidth >= 992;
    const clamp = (v, min, max) => Math.max(min, Math.min(max, v));

    function measure() {
      if (!isDesktop()) {
        trigger.style.height = '';
        track.style.transform = '';
        maxX = 0;
        lastHeight = 0;
        lastX = null;
        return;
      }

      const viewport = track.parentElement || track;
      maxX = Math.ceil(Math.max(0, track.scrollWidth - viewport.clientWidth));
      const nextHeight = Math.ceil(window.innerHeight + maxX);
      if (nextHeight !== lastHeight) {
        trigger.style.height = `${nextHeight}px`;
        lastHeight = nextHeight;
      }
    }

    function update() {
      isTicking = false;
      rafId = null;

      if (!isDesktop()) {
        track.style.transform = '';
        return;
      }

      if (maxX <= 0) {
        track.style.transform = 'translate3d(0,0,0)';
        lastX = 0;
        return;
      }

      const sectionTop = trigger.getBoundingClientRect().top + window.scrollY;
      const p = clamp((window.scrollY - sectionTop) / maxX, 0, 1);
      const x = Math.round(-(maxX * p));

      if (x !== lastX) {
        track.style.transform = `translate3d(${x}px,0,0)`;
        lastX = x;
      }
    }

    function onScroll() {
      if (!isTicking) {
        isTicking = true;
        rafId = requestAnimationFrame(update);
      }
    }

    function onResize() {
      if (resizeRaf) cancelAnimationFrame(resizeRaf);
      resizeRaf = requestAnimationFrame(() => {
        measure();
        update();
      });
    }

    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onResize);

    measure();
    update();

    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onResize);
      if (rafId) cancelAnimationFrame(rafId);
      if (resizeRaf) cancelAnimationFrame(resizeRaf);
    };
  }, []);

  return (
    <section className="section_services" id="services" data-screen-label="Services">
      <div className="svc_sticky-trigger" ref={triggerRef} id="svcTrigger">
        <div className="svc_sticky-camera">
          <div className="section-padding">
            <div className="container">
              <div className="sec-head pinned-head">
                <div className="stack">
                  <div className="section_tag"><span className="dot" /> What we do</div>
                  <h2>Everything your business needs to <span className="text-accent">grow online</span></h2>
                </div>
                <div className="sec-head_aside">
                  <p className="body-18">One partner for your website, bots, WhatsApp flows, CRM, dashboards and automation — built clearly, maintained properly and improved over time.</p>
                  <a href="#contact" onClick={(e) => serviceScrollTo(e, '#contact')} className="svc_link svc_link-primary">
                    Explore services
                    <svg viewBox="0 0 12 12" fill="none"><path d="M4.7.75h5.83v5.8M.53 10.75 10.29.99" stroke="currentColor" strokeWidth="1.5" /></svg>
                  </a>
                </div>
              </div>
            </div>
          </div>

          <div className="svc_viewport">
            <div className="svc_track" ref={trackRef} id="svcTrack">
              {SERVICES.map((item) => <ServicesCard key={item.num} item={item} />)}
            </div>
          </div>

          <p className="svc_hint">Keep scrolling to explore our services →</p>
        </div>
      </div>

      <style>{`
        .section_services {
          background: #0b0d19;
          position: relative;
          padding: 0;
        }
        .svc_sticky-trigger {
          position: relative;
        }
        .svc_sticky-camera {
          position: sticky;
          top: 0;
          min-height: 100svh;
          height: 100svh;
          overflow: hidden;
          display: flex;
          flex-direction: column;
          justify-content: center;
          gap: 30px;
          padding: 56px 0;
          transform: translateZ(0);
          backface-visibility: hidden;
          contain: paint;
        }
        .svc_sticky-camera .section-padding,
        .svc_sticky-camera .container { position: relative; z-index: 1; }
        .section-padding {
          padding-left: 5vw;
          padding-right: 5vw;
        }
        .container {
          width: 100%;
          max-width: 1180px;
          margin-inline: auto;
        }
        .sec-head {
          display: grid;
          grid-template-columns: 1.25fr .75fr;
          gap: 48px;
          align-items: end;
          margin-bottom: 54px;
        }
        .sec-head h2 {
          margin: 0;
          font-family: var(--font-heading);
          font-weight: 700;
          font-size: clamp(2.3rem, 4.7vw, 4rem);
          line-height: 1.04;
          letter-spacing: -0.015em;
          color: #fff;
        }
        .sec-head_aside {
          display: flex;
          flex-direction: column;
          gap: 20px;
          align-items: flex-start;
        }
        .body-18 {
          margin: 0;
          color: rgba(236,234,242,0.82);
          font-size: 1.02rem;
          line-height: 1.55;
        }
        .section_tag {
          display: inline-flex;
          align-items: center;
          gap: 9px;
          border: 1px solid rgba(155, 232, 221, 0.35);
          border-radius: 999px;
          padding: 9px 16px;
          color: #9be8dd;
          background: rgba(155, 232, 221, 0.1);
          font-weight: 600;
          font-size: 0.82rem;
          letter-spacing: 0.04em;
          text-transform: uppercase;
        }
        .section_tag .dot {
          width: 7px;
          height: 7px;
          border-radius: 50%;
          background: #9be8dd;
        }
        .text-accent { color: #9be8dd; }

        .svc_viewport {
          width: 100%;
          overflow: hidden;
          flex: 1;
          display: flex;
          align-items: stretch;
        }
        .svc_track {
          display: flex;
          gap: 30px;
          padding: 0 5vw;
          will-change: transform;
          backface-visibility: hidden;
          transform: translate3d(0, 0, 0);
        }
        .svc_card {
          flex: 0 0 clamp(520px, 62vw, 900px);
          display: grid;
          grid-template-columns: 1fr 1.45fr;
          gap: 30px;
          border-radius: 30px;
          padding: clamp(24px, 2.8vw, 50px);
          min-height: clamp(380px, 54vh, 520px);
          border: 1px solid rgba(255,255,255,0.09);
          overflow: hidden;
          position: relative;
        }
        .svc_card-content {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          gap: 26px;
        }
        .svc_num {
          font-size: 1.02rem;
          font-weight: 600;
          letter-spacing: 0.22em;
          color: rgba(255,255,255,0.42);
        }
        .svc_card-info h3 {
          margin: 0 0 12px;
          font-family: var(--font-heading);
          font-weight: 700;
          font-size: clamp(1.75rem, 2.4vw, 2.45rem);
          line-height: 1.04;
          color: #fff;
        }
        .svc_card-info p {
          margin: 0;
          color: rgba(236,234,242,0.84);
          font-size: 1rem;
          line-height: 1.6;
          max-width: 44ch;
        }
        .svc_link {
          display: inline-flex;
          align-items: center;
          gap: 10px;
          align-self: flex-start;
          border: 1px solid rgba(255,255,255,0.2);
          border-radius: 999px;
          padding: 12px 22px;
          font-weight: 600;
          font-size: 0.92rem;
          color: #fff;
          text-decoration: none;
          transition: background .28s ease, color .28s ease, border-color .28s ease, transform .28s ease;
        }
        .svc_link svg { width: 12px; height: 12px; transition: transform .3s ease; }
        .svc_link:hover { background: #fff; color: #0A0C18; border-color: #fff; transform: translateY(-2px); }
        .svc_link:hover svg { transform: translate(2px, -2px); }
        .svc_link-primary {
          background: var(--grad-accent);
          border-color: transparent;
          color: #0A0C18;
        }
        .svc_link-primary:hover {
          background: #fff;
          color: #0A0C18;
        }
        .svc_card-media {
          position: relative;
          border-radius: 22px;
          min-height: 300px;
          background-size: cover;
          background-repeat: no-repeat;
          background-position: center;
          overflow: hidden;
          isolation: isolate;
        }
        .svc_card-media::after {
          content: '';
          position: absolute;
          inset: 0;
          background: linear-gradient(180deg, transparent 52%, rgba(1, 12, 12, .74));
        }
        .svc_tags {
          position: absolute;
          left: 18px;
          right: 18px;
          bottom: 18px;
          z-index: 2;
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
        }
        .svc_tags span {
          background: rgba(8, 28, 32, 0.55);
          border: 1px solid rgba(255, 255, 255, 0.34);
          color: #fff;
          border-radius: 999px;
          padding: 7px 15px;
          font-size: 0.82rem;
          font-weight: 500;
        }
        .svc_hint {
          text-align: center;
          color: rgba(255, 255, 255, 0.5);
          font-size: 0.85rem;
          margin: 0;
        }

        @media (max-width: 992px) {
          .svc_sticky-camera {
            position: relative;
            top: auto;
            min-height: auto;
            height: auto;
            overflow: visible;
            padding: clamp(88px, 12vw, 110px) 0;
          }
          .svc_sticky-trigger {
            height: auto !important;
          }
          .sec-head {
            grid-template-columns: 1fr;
            gap: 16px;
            margin-bottom: 34px;
          }
          .svc_viewport { overflow: visible; }
          .svc_track {
            padding: 0;
            flex-direction: column;
          }
          .svc_card {
            flex: 0 0 auto;
            min-height: auto;
            grid-template-columns: 1fr;
            padding: 22px;
          }
          .svc_card-media {
            min-height: 240px;
            order: -1;
          }
        }
      `}</style>
    </section>
  );
}

Object.assign(window, { Services });
