// ===== New Hero =====
// Eyebrow: "We love small business."
// Headline: "your partner in tech." — KOTA staircase, animated "o" medallion.
// Lead: "Work with people who enjoy growing your operation as much as you do."
// Service pills: 5 services cycling every 4s, each driving a unique SVG scene
// in the "o" and a blurred atmospheric right-side backdrop panel.

// ─── Service Scene Data ───────────────────────────────────────────────────

const SERVICE_SCENES = [
  { label: 'Brand Design',     cls: 'brand'   },
  { label: 'Web Design & Development', cls: 'web'     },
  { label: 'SEO / AEO',       cls: 'seo'     },
  { label: 'Systems',         cls: 'systems' },
  { label: 'AI Automation',   cls: 'ai'      },
];
const NUM_SCENES = SERVICE_SCENES.length;
const SERVICE_CYCLE_MS = 4000;

// Sequential transition keys — these get choreographed GSAP exit animations.
const SEQ_KEYS = new Set(['0-1', '1-2', '2-3', '3-4', '4-0']);

// ─── SVG Scene Components ─────────────────────────────────────────────────

// Scene 0: Brand Design — a lettermark "D" drawn with ink strokes
function SceneBrand() {
  return (
    <svg viewBox="0 0 100 100" focusable="false">
      <line className="o-draw" x1="18" y1="22" x2="36" y2="22" pathLength="1" />
      <line className="o-draw" x1="18" y1="78" x2="36" y2="78" pathLength="1" />
      <line className="o-draw" x1="28" y1="22" x2="28" y2="78" pathLength="1" />
      <path className="o-draw" d="M28 24 Q80 24 80 50 Q80 76 28 76" pathLength="1" />
    </svg>
  );
}

// Scene 1: Web Design & Development — browser wireframe building out block by block
function SceneWeb() {
  return (
    <svg viewBox="0 0 100 100" focusable="false">
      <rect className="o-wire" x="10" y="14" width="80" height="13" rx="3" />
      <circle className="o-wire o-wire-dot" cx="19" cy="20" r="2.5" />
      <circle className="o-wire o-wire-dot" cx="27" cy="20" r="2.5" />
      <circle className="o-wire o-wire-dot" cx="35" cy="20" r="2.5" />
      <rect className="o-wire" x="10" y="33" width="80" height="20" rx="2" />
      <rect className="o-wire" x="10" y="59" width="37" height="27" rx="2" />
      <rect className="o-wire" x="53" y="59" width="37" height="27" rx="2" />
    </svg>
  );
}

// Scene 2: SEO / AEO — broadcast signal radiating upward from a source
function SceneSeo() {
  return (
    <svg viewBox="0 0 100 100" focusable="false">
      <circle className="o-draw" cx="50" cy="76" r="4" pathLength="1" />
      <path className="o-draw" d="M32 76 A26 26 0 0 1 68 76" pathLength="1" />
      <path className="o-draw" d="M16 76 A42 42 0 0 1 84 76" pathLength="1" />
      <path className="o-draw" d="M2 76 A58 58 0 0 1 98 76" pathLength="1" />
    </svg>
  );
}

// Scene 3: Systems — hub-and-spoke diagram snapping into place
function SceneSystems() {
  const pts = [[50,22],[74,36],[74,64],[50,78],[26,64],[26,36]];
  return (
    <svg viewBox="0 0 100 100" focusable="false">
      <circle className="o-hub" cx="50" cy="50" r="9" pathLength="1" />
      {pts.map(([x,y],i) => (
        <line key={i} className="o-spoke" x1="50" y1="50" x2={x} y2={y} pathLength="1" />
      ))}
      {pts.map(([x,y],i) => (
        <circle key={i} className="o-node" cx={x} cy={y} r="5" pathLength="1" />
      ))}
    </svg>
  );
}

// Scene 4: AI Automation — neural network nodes pulsing and connecting
function SceneAI() {
  const nodes = [[22,28],[75,22],[16,70],[50,50],[82,68],[60,82]];
  const edges = [[0,3],[1,3],[2,3],[4,3],[5,3],[0,1],[2,5],[4,5]];
  return (
    <svg viewBox="0 0 100 100" focusable="false">
      {edges.map(([a,b],i) => (
        <line key={i} className="o-draw"
          x1={nodes[a][0]} y1={nodes[a][1]}
          x2={nodes[b][0]} y2={nodes[b][1]}
          pathLength="1" />
      ))}
      {nodes.map(([x,y],i) => (
        <circle key={i} className="o-node" cx={x} cy={y} r={i===3?7:5} pathLength="1" />
      ))}
    </svg>
  );
}

const SCENE_CMPS = [SceneBrand, SceneWeb, SceneSeo, SceneSystems, SceneAI];

// ─── Scene Renderers ──────────────────────────────────────────────────────

// Renders all 5 scenes stacked inside the "o" medallion.
// CSS opacity + transition handles visibility; GSAP handles exit choreography.
function HeroServiceScenes({ serviceIdx }) {
  return (
    <span className="video-o" aria-hidden="true">
      {SERVICE_SCENES.map(({ cls }, i) => {
        const Scene = SCENE_CMPS[i];
        return (
          <span key={cls} className={'o-scene o-scene-' + cls + (serviceIdx === i ? ' is-active' : '')}>
            <Scene />
          </span>
        );
      })}
    </span>
  );
}

// ─── HomeNewHero ──────────────────────────────────────────────────────────

function HomeNewHero() {
  const blobsRef       = React.useRef(null);
  const rootRef        = React.useRef(null);
  const backdropRef    = React.useRef(null);
  const manualAdvRef   = React.useRef(0);
  const prevIdxRef     = React.useRef(0);
  const [serviceIdx, setServiceIdx] = React.useState(0);

  // ── Auto-cycle ───────────────────────────────────────────────────────────
  React.useEffect(() => {
    if (window.__pdaReduceMotion) return;
    const id = setInterval(() => {
      if (performance.now() - manualAdvRef.current < 2800) return;
      setServiceIdx(i => (i + 1) % NUM_SCENES);
    }, SERVICE_CYCLE_MS);
    return () => clearInterval(id);
  }, []);

  // ── Transition animations ─────────────────────────────────────────────────
  // On each serviceIdx change: pulse backdrop blur deeper then resolve,
  // and run a choreographed GSAP exit on the outgoing scene (sequential only).
  React.useEffect(() => {
    const prev = prevIdxRef.current;
    prevIdxRef.current = serviceIdx;
    if (prev === serviceIdx || typeof gsap === 'undefined' || window.__pdaReduceMotion) return;

    // Backdrop blur pulse: deepen → resolve (150ms after the "o" settles)
    const bd = backdropRef.current;
    if (bd) {
      gsap.killTweensOf(bd, 'filter');
      gsap.fromTo(bd,
        { filter: 'blur(28px)' },
        { filter: 'blur(48px)', duration: 0.22, ease: 'power2.in',
          onComplete() {
            gsap.to(bd, { filter: 'blur(28px)', duration: 0.5, delay: 0.15, ease: 'power2.out' });
          },
        }
      );
    }

    const oEl = rootRef.current?.querySelector('.video-o');
    if (!oEl) return;
    const sceneEl = i => oEl.querySelector('.o-scene-' + SERVICE_SCENES[i].cls);

    // The incoming scene must start from a clean slate: a prior exit tween left
    // inline opacity/transform on it, which would otherwise pin it invisible
    // (inline styles beat the .is-active CSS rule). Clearing lets CSS fade it in
    // and its draw/pop keyframes replay.
    const nextScene = sceneEl(serviceIdx);
    if (nextScene) gsap.set(nextScene, { clearProps: 'all' });

    const prevScene = sceneEl(prev);
    if (!prevScene) return;

    // Each transition moves the exiting scene in a direction that "hands off"
    // to the entering one — strokes spread, grid radiates, signals converge, etc.
    const exits = {
      '0-1': { scaleX: 1.7, opacity: 0, transformOrigin: '50% 50%', duration: 0.35, ease: 'power2.in' },
      '1-2': { x: -14, y: -14, opacity: 0, duration: 0.32, ease: 'power2.in' },
      '2-3': { scale: 0.15, opacity: 0, transformOrigin: '50% 76%', duration: 0.35, ease: 'power2.in' },
      '3-4': { scale: 1.4, opacity: 0, transformOrigin: '50% 50%', duration: 0.38, ease: 'power2.in' },
      '4-0': { scale: 0, opacity: 0, transformOrigin: '50% 50%', duration: 0.35, ease: 'power2.in' },
    };

    // Sequential steps get the choreographed exit; any jump (pill/hover) just
    // crossfades via CSS. Either way we wipe the outgoing scene's inline props
    // afterward so it can light up cleanly next time it comes around.
    const key = `${prev}-${serviceIdx}`;
    if (SEQ_KEYS.has(key)) {
      gsap.to(prevScene, { ...exits[key], onComplete() { gsap.set(prevScene, { clearProps: 'all' }); } });
    } else {
      gsap.set(prevScene, { clearProps: 'all' });
    }
  }, [serviceIdx]);

  // ── Entrance animation ────────────────────────────────────────────────────
  React.useEffect(() => {
    if (window.__pdaReduceMotion || typeof gsap === 'undefined') {
      // The pills start at CSS opacity:0 purely so the entrance can fade them
      // in. If we're skipping the entrance (reduced motion or GSAP unavailable),
      // reveal them so the service list never stays invisible.
      const pills = rootRef.current?.querySelector('.hero-pills');
      if (pills) pills.style.opacity = '1';
      return;
    }
    const root = rootRef.current;
    if (!root) return;
    const q = gsap.utils.selector(root);
    const tl = gsap.timeline({ defaults: { ease: 'power3.out' } });
    tl.fromTo(q('.hero-blobs'),
        { opacity: 0, scale: 1.06 },
        { opacity: 1, scale: 1, duration: 1.4, ease: 'power2.out' })
      .fromTo(q('.hero-eyebrow-line'),
        { opacity: 0, y: 16 },
        { opacity: 1, y: 0, duration: 0.6 }, 0.15)
      .fromTo(q('.hl-line-inner'),
        { yPercent: 115 },
        { yPercent: 0, duration: 1.05, stagger: 0.13, ease: 'power4.out' }, 0.3)
      .fromTo(q('.video-o'),
        { scale: 0 },
        { scale: 1, duration: 0.7, ease: 'back.out(1.6)' }, '-=0.45')
      .fromTo(q('.hero-new-lead'),
        { opacity: 0, y: 24 },
        { opacity: 1, y: 0, duration: 0.7 }, '-=0.3')
      .fromTo(q('.hero-pills'),
        { opacity: 0, y: 16 },
        { opacity: 1, y: 0, duration: 0.6 }, '-=0.3')
      .fromTo(q('.hero-new-ctas'),
        { opacity: 0, y: 18 },
        { opacity: 1, y: 0, duration: 0.6 }, '-=0.35')
      .fromTo(q('.hero-strip'),
        { opacity: 0, y: 14 },
        { opacity: 1, y: 0, duration: 0.6 }, '-=0.3');
    return () => tl.kill();
  }, []);

  // ── Scroll dissolve ───────────────────────────────────────────────────────
  React.useEffect(() => {
    if (
      window.__pdaIsMobile || window.__pdaReduceMotion ||
      typeof gsap === 'undefined' || typeof ScrollTrigger === 'undefined'
    ) return;
    const el = blobsRef.current;
    if (!el) return;
    const heroEl = rootRef.current;
    const ctx = gsap.context(() => {
      gsap.to(el, {
        scale: 0.3, opacity: 0, ease: 'none',
        scrollTrigger: { trigger: heroEl, start: 'top top', end: 'bottom top', scrub: true },
      });
      [['.hl-1', -7], ['.hl-2', 6], ['.hl-3', -4]].forEach(([sel, drift]) => {
        gsap.to(sel, {
          xPercent: drift, opacity: 0.25, ease: 'none',
          scrollTrigger: { trigger: heroEl, start: 'top top', end: 'bottom 25%', scrub: 1 },
        });
      });
    }, rootRef);
    return () => ctx.revert();
  }, []);

  // ── Hover interactions ────────────────────────────────────────────────────
  React.useEffect(() => {
    if (
      window.__pdaReduceMotion || typeof gsap === 'undefined' ||
      !window.matchMedia('(hover: hover)').matches
    ) return;
    const root = rootRef.current;
    if (!root) return;
    const cleanups = [];

    const btn = root.querySelector('.hero-new-ctas .btn');
    if (btn) {
      const bx = gsap.quickTo(btn, 'x', { duration: 0.4, ease: 'power3.out' });
      const by = gsap.quickTo(btn, 'y', { duration: 0.4, ease: 'power3.out' });
      const onMove = e => {
        const r = btn.getBoundingClientRect();
        bx((e.clientX - (r.left + r.width  / 2)) * 0.28);
        by((e.clientY - (r.top  + r.height / 2)) * 0.28);
      };
      const onLeave = () => { bx(0); by(0); };
      btn.addEventListener('pointermove',  onMove,  { passive: true });
      btn.addEventListener('pointerleave', onLeave);
      cleanups.push(() => {
        btn.removeEventListener('pointermove',  onMove);
        btn.removeEventListener('pointerleave', onLeave);
      });
    }

    const oEl = root.querySelector('.video-o');
    if (oEl) {
      const onEnter = () => {
        gsap.to(oEl, { scale: 1.07, duration: 0.35, ease: 'power2.out' });
        manualAdvRef.current = performance.now();
        setServiceIdx(i => (i + 1) % NUM_SCENES);
      };
      const onLeave = () => gsap.to(oEl, { scale: 1, duration: 0.4, ease: 'power2.inOut' });
      oEl.addEventListener('pointerenter', onEnter);
      oEl.addEventListener('pointerleave', onLeave);
      cleanups.push(() => {
        oEl.removeEventListener('pointerenter', onEnter);
        oEl.removeEventListener('pointerleave', onLeave);
      });
    }
    return () => cleanups.forEach(fn => fn());
  }, []);

  // ── Blob pointer effect ───────────────────────────────────────────────────
  React.useEffect(() => {
    if (
      window.__pdaIsMobile || window.__pdaReduceMotion ||
      typeof gsap === 'undefined' || !window.matchMedia('(hover: hover)').matches
    ) return;
    const hero = rootRef.current;
    if (!hero) return;
    const wraps = hero.querySelectorAll('.hero-blob-wrap');
    if (!wraps.length) return;
    const FACTORS = [{ x: 70, y: 50 }, { x: -90, y: -60 }, { x: 45, y: -80 }];
    const setters = [...wraps].map(w => ({
      x: gsap.quickTo(w, 'x', { duration: 1.1, ease: 'power3.out' }),
      y: gsap.quickTo(w, 'y', { duration: 1.1, ease: 'power3.out' }),
    }));
    const onMove = e => {
      const nx = e.clientX / window.innerWidth  - 0.5;
      const ny = e.clientY / window.innerHeight - 0.5;
      setters.forEach((s, i) => {
        s.x(nx * 2 * FACTORS[i].x);
        s.y(ny * 2 * FACTORS[i].y);
      });
    };
    hero.addEventListener('pointermove', onMove, { passive: true });
    return () => hero.removeEventListener('pointermove', onMove);
  }, []);

  const handlePillClick = i => {
    manualAdvRef.current = performance.now();
    setServiceIdx(i);
  };

  const activeCls = SERVICE_SCENES[serviceIdx].cls;

  return (
    <section className="home-new-hero" ref={rootRef}>

      {/* Blurred atmospheric backdrop — right panel, behind blobs */}
      <div className="hero-scene-backdrop" ref={backdropRef} aria-hidden="true">
        <div key={serviceIdx} className={'hero-bd-inner hero-bd-' + activeCls}>
          {React.createElement(SCENE_CMPS[serviceIdx])}
        </div>
      </div>

      <div className="hero-blobs" ref={blobsRef} aria-hidden="true">
        <span className="hero-blob-wrap"><span className="hero-blob hero-blob-teal" /></span>
        <span className="hero-blob-wrap"><span className="hero-blob hero-blob-blue" /></span>
        <span className="hero-blob-wrap"><span className="hero-blob hero-blob-purple" /></span>
      </div>

      {window.HomeRobot ? <window.HomeRobot /> : null}

      <div className="container hero-new-inner">
        <span className="hero-eyebrow-line">
          We <em>love</em> small business.
        </span>

        {/* KOTA-style staircase: three stacked lowercase lines.
            The animated "o" medallion sits inside line 1. */}
        <h1 className="hero-headline" aria-label="Your partner in tech.">
          <span aria-hidden="true" className="hl-stack">
            <span className="hl-line hl-1">
              <span className="hl-line-inner">
                y<HeroServiceScenes serviceIdx={serviceIdx} />ur
              </span>
            </span>
            <span className="hl-line hl-2">
              <span className="hl-line-inner">partner</span>
            </span>
            <span className="hl-line hl-3">
              <span className="hl-line-inner">
                in tech<span className="hl-dot">.</span>
              </span>
            </span>
          </span>
        </h1>

        <div className="hero-new-sub">
          <p className="hero-new-lead">
            Work with people who enjoy growing your operation{' '}
            <strong>as much as you do.</strong>
          </p>

          <div className="hero-pills" role="list" aria-label="Our services">
            {SERVICE_SCENES.map(({ label, cls }, i) => (
              <button
                key={cls}
                className={'hero-pill' + (serviceIdx === i ? ' is-active' : '')}
                onClick={() => handlePillClick(i)}
                role="listitem"
                aria-pressed={serviceIdx === i}
              >
                {label}
              </button>
            ))}
          </div>

          <div className="hero-new-ctas">
            <button
              className="btn btn-primary"
              onClick={() => window.PDAOpenBuilder && window.PDAOpenBuilder()}
            >
              <span className="btn-label">Hire us</span>
            </button>
          </div>
        </div>
      </div>

      <div className="hero-strip" aria-hidden="true">
        <span>Since 2020</span>
        <span>5.0 on Google</span>
        <span>42 five-star reviews</span>
        <span>Dahlonega, GA</span>
        <span className="hero-strip-scroll">Scroll<i className="hero-strip-arrow" /></span>
      </div>
    </section>
  );
}
window.HomeNewHero = HomeNewHero;
