// ===== What We Do — service panels =====
// Three full-viewport panels. On desktop (motion on, GSAP present) the section
// pins and the panels sweep horizontally while the header fades behind panel 01.
// Otherwise the panels stack vertically (the fallback path).

// --- Right-side visuals ---------------------------------------------------

// Panel 02: small node graph with dots traveling along the links (SMIL).
function ServiceNodeGraph() {
  const links = [
    { id: 'lk1', d: 'M60,150 C120,90 180,90 240,150' },
    { id: 'lk2', d: 'M240,150 C300,210 360,210 420,150' },
    { id: 'lk3', d: 'M60,150 C150,260 330,260 420,150' },
    { id: 'lk4', d: 'M240,40 L240,150' },
  ];
  const nodes = [
    { cx: 60, cy: 150 }, { cx: 240, cy: 150 }, { cx: 420, cy: 150 },
    { cx: 240, cy: 40 },
  ];
  return (
    <svg className="svc-graph" viewBox="0 0 480 300" fill="none" aria-hidden="true">
      <defs>
        <linearGradient id="svcGraphStroke" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%" stopColor="#20C8A2" />
          <stop offset="100%" stopColor="#1E82D2" />
        </linearGradient>
        <filter id="svcGraphGlow" x="-60%" y="-60%" width="220%" height="220%">
          <feGaussianBlur stdDeviation="2.6" result="b" />
          <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
        </filter>
      </defs>
      {links.map((l) => (
        <path key={l.id} id={l.id} className="svc-graph-link" d={l.d}
          stroke="url(#svcGraphStroke)" strokeWidth="1.5" opacity="0.5" />
      ))}
      {links.map((l, i) => (
        <circle key={'t' + l.id} r="4.5" fill="#20C8A2" filter="url(#svcGraphGlow)">
          <animateMotion dur={`${3 + i * 0.6}s`} begin={`${i * 0.4}s`} repeatCount="indefinite" rotate="auto">
            <mpath href={`#${l.id}`} />
          </animateMotion>
        </circle>
      ))}
      {nodes.map((n, i) => (
        <g key={'n' + i} className="svc-graph-node"
          style={{ animationDelay: (i * 0.5) + 's' }}>
          <circle cx={n.cx} cy={n.cy} r="9"
            fill="#0E121E" stroke="url(#svcGraphStroke)" strokeWidth="2" filter="url(#svcGraphGlow)" />
        </g>
      ))}
    </svg>
  );
}

// Panel "Foundation": an isometric building foundation (slab + rebar grid +
// footings) that draws itself in. Matches the construction/blueprint theme.
function ServiceFoundation() {
  // top-face diamond vertices
  const top = [240, 86], right = [402, 170], bottom = [240, 254], left = [78, 170];
  const lerp = (a, b, t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
  const grid = [];
  [0.25, 0.5, 0.75].forEach((t, i) => {
    // family 1: parallel to the top-left edge
    const p = lerp(left, bottom, t), q = lerp(top, right, t);
    grid.push({ k: 'a' + i, x1: p[0], y1: p[1], x2: q[0], y2: q[1] });
    // family 2: parallel to the top-right edge
    const a = lerp(left, top, t), b = lerp(bottom, right, t);
    grid.push({ k: 'b' + i, x1: a[0], y1: a[1], x2: b[0], y2: b[1] });
  });
  const topDiamond = `M${top} L${right} L${bottom} L${left} Z`;
  return (
    <svg className="svc-foundation" viewBox="0 0 480 340" fill="none" aria-hidden="true">
      <defs>
        <linearGradient id="svcFoundStroke" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#20C8A2" />
          <stop offset="100%" stopColor="#1E82D2" />
        </linearGradient>
        <filter id="svcFoundGlow" x="-40%" y="-40%" width="180%" height="180%">
          <feGaussianBlur stdDeviation="3" result="b" />
          <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
        </filter>
      </defs>
      {/* top-face soft fill */}
      <path d={topDiamond} fill="url(#svcFoundStroke)" opacity="0.06" />
      {/* slab depth faces */}
      <path className="svc-found-draw" pathLength="1" style={{ animationDelay: '.05s' }}
        d="M78,170 L78,206 L240,290 L240,254 Z"
        stroke="url(#svcFoundStroke)" strokeWidth="2" opacity="0.5" />
      <path className="svc-found-draw" pathLength="1" style={{ animationDelay: '.1s' }}
        d="M240,254 L240,290 L402,206 L402,170 Z"
        stroke="url(#svcFoundStroke)" strokeWidth="2" opacity="0.5" />
      {/* footings */}
      {[[78, 206], [240, 290], [402, 206]].map((f, i) => (
        <line key={'ft' + i} className="svc-found-draw" pathLength="1"
          style={{ animationDelay: (0.15 + i * 0.05) + 's' }}
          x1={f[0]} y1={f[1]} x2={f[0]} y2={f[1] + 26}
          stroke="url(#svcFoundStroke)" strokeWidth="3" opacity="0.5" />
      ))}
      {/* rebar grid on the top face */}
      {grid.map((g, i) => (
        <line key={g.k} className="svc-found-draw" pathLength="1"
          style={{ animationDelay: (0.3 + i * 0.06) + 's' }}
          x1={g.x1} y1={g.y1} x2={g.x2} y2={g.y2}
          stroke="url(#svcFoundStroke)" strokeWidth="1" opacity="0.3" />
      ))}
      {/* top-face outline (glowing) */}
      <path className="svc-found-draw" pathLength="1" style={{ animationDelay: '.6s' }}
        d={topDiamond} stroke="url(#svcFoundStroke)" strokeWidth="2.5"
        filter="url(#svcFoundGlow)" />
      {/* survey dot tracing the perimeter */}
      <path id="svcFoundPerim" d={topDiamond} stroke="none" fill="none" />
      <circle r="4.5" fill="#20C8A2" filter="url(#svcFoundGlow)">
        <animateMotion dur="6s" repeatCount="indefinite" rotate="auto">
          <mpath href="#svcFoundPerim" />
        </animateMotion>
      </circle>
      {/* pulsing corner survey markers */}
      {[top, right, bottom, left].map((c, i) => (
        <circle key={'sv' + i} className="svc-found-survey"
          style={{ animationDelay: (i * 0.4) + 's' }}
          cx={c[0]} cy={c[1]} r="4.5" fill="none"
          stroke="url(#svcFoundStroke)" strokeWidth="1.5" />
      ))}
    </svg>
  );
}

// Brand panel: a 3x3 grid of geometric logo-marks that cycle a highlight,
// suggesting identity exploration.
function ServiceLogoGrid() {
  const cells = [];
  for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) cells.push({ r, c, i: r * 3 + c });
  const mark = (i, x, y) => {
    switch (i % 9) {
      case 0: return <circle cx={x} cy={y} r="22" />;
      case 1: return <rect x={x - 20} y={y - 20} width="40" height="40" rx="6" />;
      case 2: return <path d={`M${x},${y - 24} L${x + 22},${y + 18} L${x - 22},${y + 18} Z`} />;
      case 3: return <path d={`M${x},${y - 24} L${x + 24},${y} L${x},${y + 24} L${x - 24},${y} Z`} />;
      case 4: return <g><circle cx={x} cy={y} r="22" /><circle cx={x} cy={y} r="10" /></g>;
      case 5: return <path d={`M${x - 20},${y} H${x + 20} M${x},${y - 20} V${y + 20}`} />;
      case 6: return <path d={`M${x - 22},${y - 11} L${x},${y - 24} L${x + 22},${y - 11} L${x + 22},${y + 11} L${x},${y + 24} L${x - 22},${y + 11} Z`} />;
      case 7: return <path d={`M${x - 22},${y + 14} A24,24 0 0 1 ${x + 22},${y + 14}`} />;
      default: return <circle cx={x} cy={y} r="11" />;
    }
  };
  return (
    <svg className="svc-logogrid" viewBox="0 0 360 360" fill="none" aria-hidden="true">
      <defs>
        <linearGradient id="svcLogoStroke" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#20C8A2" />
          <stop offset="55%" stopColor="#1E82D2" />
          <stop offset="100%" stopColor="#6E50C8" />
        </linearGradient>
        <filter id="svcLogoGlow" x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="2.4" result="b" />
          <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
        </filter>
      </defs>
      {cells.map(({ i }) => {
        const x = 60 + (i % 3) * 120;
        const y = 60 + Math.floor(i / 3) * 120;
        return (
          <g key={i} className="svc-logogrid-cell" filter="url(#svcLogoGlow)"
            style={{ animationDelay: (i * 0.4) + 's', transformOrigin: `${x}px ${y}px` }}>
            <g stroke="url(#svcLogoStroke)" strokeWidth="2" fill="none" strokeLinejoin="round">
              {mark(i, x, y)}
            </g>
          </g>
        );
      })}
    </svg>
  );
}

// Software Unbundling: several faded subscription tiles funnel into the one
// custom module you own (traveling dots carry the consolidation).
function ServiceUnbundle() {
  const subs = [{ y: 22 }, { y: 86 }, { y: 150 }, { y: 214 }];
  const hubX = 354; // left edge of the owned module
  return (
    <svg className="svc-unbundle" viewBox="0 0 480 300" fill="none" aria-hidden="true">
      <defs>
        <linearGradient id="svcUnbStroke" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#20C8A2" />
          <stop offset="100%" stopColor="#1E82D2" />
        </linearGradient>
        <filter id="svcUnbGlow" x="-60%" y="-60%" width="220%" height="220%">
          <feGaussianBlur stdDeviation="2.8" result="b" />
          <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
        </filter>
      </defs>
      {/* converging links subscription -> owned module */}
      {subs.map((s, i) => (
        <path key={'l' + i} id={'unb' + i}
          d={`M120,${s.y + 26} C220,${s.y + 26} 280,150 ${hubX},150`}
          stroke="url(#svcUnbStroke)" strokeWidth="1.5" opacity="0.4" />
      ))}
      {/* subscription tiles (what you stop paying for) */}
      {subs.map((s, i) => (
        <g key={'t' + i} className="svc-unb-sub" style={{ animationDelay: (i * 0.5) + 's' }}>
          <rect x="20" y={s.y} width="100" height="52" rx="9"
            fill="rgba(255,255,255,.03)" stroke="url(#svcUnbStroke)" strokeWidth="1.5" />
          <circle cx="42" cy={s.y + 26} r="6" fill="none" stroke="url(#svcUnbStroke)" strokeWidth="1.5" />
          <line x1="58" y1={s.y + 20} x2="104" y2={s.y + 20} stroke="url(#svcUnbStroke)" strokeWidth="2" opacity=".55" />
          <line x1="58" y1={s.y + 33} x2="90" y2={s.y + 33} stroke="url(#svcUnbStroke)" strokeWidth="2" opacity=".3" />
        </g>
      ))}
      {/* traveling dots toward the custom build */}
      {subs.map((s, i) => (
        <circle key={'d' + i} r="3.5" fill="#20C8A2" filter="url(#svcUnbGlow)">
          <animateMotion dur={`${2.4 + i * 0.3}s`} begin={`${i * 0.4}s`} repeatCount="indefinite">
            <mpath href={`#unb${i}`} />
          </animateMotion>
        </circle>
      ))}
      {/* the one custom module you own */}
      <g className="svc-unb-core" filter="url(#svcUnbGlow)">
        <rect x={hubX} y="88" width="112" height="124" rx="14"
          fill="rgba(32,200,162,.08)" stroke="url(#svcUnbStroke)" strokeWidth="2.5" />
        {[0, 1, 2].map((r) =>
          [0, 1, 2].map((c) => (
            <rect key={`g${r}${c}`} x={hubX + 18 + c * 26} y={108 + r * 30} width="14" height="14" rx="3"
              fill="none" stroke="url(#svcUnbStroke)" strokeWidth="1.5" opacity=".6" />
          ))
        )}
      </g>
    </svg>
  );
}

// SEO/AEO: ranked result rows with the brand row sitting at #1, signal rings
// radiating from it (found by search + AI), and a seeking magnifier.
function ServiceSEO() {
  const rows = [0, 1, 2, 3];
  return (
    <svg className="svc-seo" viewBox="0 0 480 300" fill="none" aria-hidden="true">
      <defs>
        <linearGradient id="svcSeoStroke" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#20C8A2" />
          <stop offset="55%" stopColor="#1E82D2" />
          <stop offset="100%" stopColor="#6E50C8" />
        </linearGradient>
        <filter id="svcSeoGlow" x="-60%" y="-60%" width="220%" height="220%">
          <feGaussianBlur stdDeviation="2.6" result="b" />
          <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
        </filter>
      </defs>
      {rows.map((r) => (
        <g key={r} opacity={r === 0 ? 1 : 0.4} filter={r === 0 ? 'url(#svcSeoGlow)' : undefined}>
          <rect x="34" y={30 + r * 56} width="270" height="42" rx="8"
            fill={r === 0 ? 'rgba(32,200,162,.10)' : 'rgba(255,255,255,.03)'}
            stroke="url(#svcSeoStroke)" strokeWidth={r === 0 ? 2.5 : 1.25} />
          <circle cx="58" cy={51 + r * 56} r="8" fill="none" stroke="url(#svcSeoStroke)" strokeWidth="1.5" />
          <line x1="78" y1={45 + r * 56} x2={r === 0 ? 246 : 196} y2={45 + r * 56} stroke="url(#svcSeoStroke)" strokeWidth="3" opacity=".6" />
          <line x1="78" y1={58 + r * 56} x2={r === 0 ? 206 : 156} y2={58 + r * 56} stroke="url(#svcSeoStroke)" strokeWidth="2" opacity=".3" />
        </g>
      ))}
      {/* visibility signal over the #1 result */}
      <circle className="svc-seo-pulse" cx="290" cy="51" r="16" fill="none" stroke="url(#svcSeoStroke)" strokeWidth="2" />
      <circle className="svc-seo-pulse" cx="290" cy="51" r="16" fill="none" stroke="url(#svcSeoStroke)" strokeWidth="2" style={{ animationDelay: '1.1s' }} />
      {/* seeking magnifier */}
      <g className="svc-seo-glass" filter="url(#svcSeoGlow)">
        <circle cx="372" cy="210" r="34" fill="none" stroke="url(#svcSeoStroke)" strokeWidth="3" />
        <line x1="396" y1="234" x2="424" y2="262" stroke="url(#svcSeoStroke)" strokeWidth="4" strokeLinecap="round" />
      </g>
    </svg>
  );
}

// --- Panel data -----------------------------------------------------------
// Five services in the order the user defined them.
const SVC_PANELS = [
  {
    n: '01',
    service: 'Web Design & Development',
    href: 'services/web.html',
    title: 'A site that earns its keep',
    blurb: [
      'Web design and development built for your business without templates. Fast, mobile-ready, with copy optimized for organic and generative search engines.',
    ],
    stack: ['Custom design', 'Mobile-first build', 'On-page SEO', 'Contact form', 'Hosting + SSL'],
    result: 'A credible first step',
    visual: 'foundation',
  },
  {
    n: '02',
    service: 'AI Training & Automation',
    href: 'services/automation.html',
    title: 'Workflows that run themselves',
    blurb: [
      'We train AI on how your business actually works, then put it to work. Follow-up sequences, document generation, content drafts, internal alerts.. the repetitive tasks handled, owner hours back in your week.',
    ],
    stack: ['Custom GPTs + AI agents', 'Lead nurture sequences', 'Multi-system workflows', 'Automated reporting'],
    result: 'Your time, given back',
    visual: 'graph',
  },
  {
    n: '03',
    service: 'Software Unbundling',
    href: 'services/ecosystem.html',
    title: 'Stop renting software that almost fits',
    blurb: [
      "You're paying every month for bloated platforms and using a sliver of what they do. We map what you actually need, then build a custom tool that does exactly that. You own it, and the subscriptions stop.",
    ],
    stack: ['Software audit', 'Custom-built tools', 'Subscription savings', 'You own the code'],
    result: 'Tools you own, bills you drop',
    visual: 'unbundle',
  },
  {
    n: '04',
    service: 'Brand Design',
    href: 'services.html',
    title: 'A brand that owns the room',
    // PLACEHOLDER COPY — replace before launch (no existing brand-design source)
    blurb: [
      "Before anyone reads a word, they've already decided how they feel about your business. We make sure that feeling is right.",
    ],
    stack: ['Logo + identity', 'Color + type system', 'Brand guidelines', 'Collateral design'],
    result: 'A first impression that sticks',
    visual: 'logogrid',
  },
  {
    n: '05',
    service: 'SEO / AEO Optimization',
    href: 'services/seo.html',
    title: 'Found by search engines and AI alike',
    blurb: [
      'Search is changing. People still Google you, but more of them ask AI for a recommendation. We optimize for both, so your business surfaces whether someone types a query or asks a chatbot who to call.',
    ],
    stack: ['On-page SEO', 'Local search', 'Answer Engine Optimization', 'Schema + structured data'],
    result: 'Found wherever they look',
    visual: 'seo',
  },
];

function HomeServicePanels() {
  const I = window.PDAIcons;
  const totalLabel = String(SVC_PANELS.length).padStart(2, '0');
  const sectionRef = React.useRef(null);
  const headerRef = React.useRef(null);
  const wrapRef = React.useRef(null);
  const trackRef = React.useRef(null);

  React.useEffect(() => {
    if (
      window.__pdaIsMobile ||
      window.__pdaReduceMotion ||
      typeof gsap === 'undefined' ||
      typeof ScrollTrigger === 'undefined'
    ) {
      return;
    }
    const section = sectionRef.current;
    const wrap = wrapRef.current;
    const track = trackRef.current;
    if (!section || !wrap || !track) return;

    section.classList.add('is-horizontal');
    const panels = track.querySelectorAll('.svc-panel');

    const ctx = gsap.context(() => {
      gsap.to(track, {
        x: () => -(track.scrollWidth - window.innerWidth),
        ease: 'none',
        scrollTrigger: {
          trigger: wrap,
          start: 'top top',
          end: () => '+=' + (track.scrollWidth - window.innerWidth),
          pin: true,
          scrub: 1,
          snap: panels.length > 1 ? 1 / (panels.length - 1) : false,
          invalidateOnRefresh: true,
        },
      });

      // Header fades + slides down as the first panel takes over.
      gsap.to(headerRef.current, {
        opacity: 0,
        y: 80,
        ease: 'none',
        scrollTrigger: {
          trigger: wrap,
          start: 'top top',
          end: () => '+=' + window.innerWidth * 0.7,
          scrub: true,
        },
      });
    }, section);

    return () => {
      ctx.revert();
      section.classList.remove('is-horizontal');
    };
  }, []);

  return (
    <section className="svc-section" ref={sectionRef} aria-label="What we do">
      <div className="svc-wrap" ref={wrapRef}>
        <div className="svc-header" ref={headerRef}>
          <h2 className="section-display">What We Do</h2>
        </div>
        <div className="svc-track" ref={trackRef}>
          {SVC_PANELS.map((p) => (
            <article className={'svc-panel svc-panel-' + p.n} key={p.n}>
              <div className="svc-panel-inner container">
                <div className="svc-panel-content">
                  <span className="eyebrow svc-panel-service">{p.n} &middot; {p.service}</span>
                  <h3 className="svc-panel-title">{p.title}</h3>
                  {p.blurb.map((para, i) => (
                    <p className="svc-panel-blurb" key={i}>{para}</p>
                  ))}
                  <div className="svc-chips">
                    {p.stack.map((s, i) => (
                      <span className="svc-chip" key={i}>
                        <I.Check size={12} />{s}
                      </span>
                    ))}
                  </div>
                  <div className="svc-panel-foot">
                    <div className="svc-result">
                      <span className="svc-result-label">Outcome</span>
                      <span className="svc-result-value gradient-text">{p.result}</span>
                    </div>
                    <a className="svc-cta" href={p.href} aria-label={'Explore ' + p.service}>
                      <span className="svc-cta-label">Explore {p.service}</span>
                      <span className="svc-cta-arrow" aria-hidden="true">&rarr;</span>
                    </a>
                  </div>
                </div>
                <div className="svc-panel-visual" aria-hidden="true">
                  {p.visual === 'foundation' && <ServiceFoundation />}
                  {p.visual === 'graph' && <ServiceNodeGraph />}
                  {p.visual === 'unbundle' && <ServiceUnbundle />}
                  {p.visual === 'logogrid' && <ServiceLogoGrid />}
                  {p.visual === 'seo' && <ServiceSEO />}
                </div>
              </div>
              <span className="svc-counter">{p.n} / {totalLabel}</span>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}
window.HomeServicePanels = HomeServicePanels;
