﻿// ===== The Roadmap =====
// One persistent isometric building that ACCUMULATES through the four stages and
// finally joins a network of other buildings:
//   Foundation -> excavated slab with pulsing survey grid (its own look)
//   Growth     -> walls + roof rise: it becomes a real building
//   Operation  -> wiring lights up: window glows + conduits with energy flowing
//   Automation -> the building shrinks and connects to many other buildings
// Each layer only adds, so transitions read as construction, not swaps.

// Isometric geometry (viewBox 0 0 500 500), main building centred ~ (250,300).
const RB = {
  Ftop: [250, 330], Fright: [400, 396], Fbot: [250, 462], Fleft: [100, 396],
  Utop: [250, 180], Uright: [400, 246], Ubot: [250, 312], Uleft: [100, 246],
  apex: [250, 108],
};
const _add = (o, u, su, v, sv) => [o[0] + u[0] * su + v[0] * sv, o[1] + u[1] * su + v[1] * sv];
const _pt = (p) => p[0] + ',' + p[1];

// generate a window parallelogram on a wall face defined by origin o + basis u,v
function winPath(o, u, v, su0, su1, sv0, sv1) {
  const c00 = _add(o, u, su0, v, sv0), c10 = _add(o, u, su1, v, sv0);
  const c11 = _add(o, u, su1, v, sv1), c01 = _add(o, u, su0, v, sv1);
  return `M${_pt(c00)} L${_pt(c10)} L${_pt(c11)} L${_pt(c01)} Z`;
}

// small, distinct building silhouettes for the Automation network
const SAT_SHAPES = [
  (x, y) => `M${x-22},${y+16} V${y-6} L${x},${y-20} L${x+22},${y-6} V${y+16} Z`,          // house
  (x, y) => `M${x-15},${y+16} V${y-24} H${x+15} V${y+16} Z M${x-7},${y-14} H${x+7} M${x-7},${y-2} H${x+7}`, // tower
  (x, y) => `M${x-24},${y+16} V${y-2} L${x-12},${y-15} L${x+12},${y-15} L${x+24},${y-2} V${y+16} Z`, // warehouse
  (x, y) => `M${x-22},${y+16} V${y-8} H${x+22} V${y+16} Z M${x-22},${y-8} L${x},${y-20} L${x+22},${y-8}`, // shop
  (x, y) => `M${x-14},${y+16} V${y-16} H${x+14} V${y+16} Z M${x},${y-16} V${y-28} M${x-7},${y-23} H${x+7}`, // clinic (cross)
  (x, y) => `M${x-20},${y+16} V${y-10} L${x},${y-22} L${x+20},${y-10} V${y+16} Z M${x-6},${y+16} V${y+3} H${x+6} V${y+16}`, // house+door
];

function RoadmapBuilding({ stage }) {
  const cls = (idx) => 'rb-layer' + (stage >= idx ? ' shown' : '');
  const networkOn = stage >= 3;

  // Foundation concentric diamonds (survey grid)
  const rings = [0.7, 0.46, 0.22];

  // Growth wall faces
  const leftWall = `M${_pt(RB.Fleft)} L${_pt(RB.Fbot)} L${_pt(RB.Ubot)} L${_pt(RB.Uleft)} Z`;
  const rightWall = `M${_pt(RB.Fbot)} L${_pt(RB.Fright)} L${_pt(RB.Uright)} L${_pt(RB.Ubot)} Z`;

  // Operation windows (origin + basis per wall)
  const lO = RB.Fleft, lU = [RB.Fbot[0]-RB.Fleft[0], RB.Fbot[1]-RB.Fleft[1]], lV = [0, RB.Uleft[1]-RB.Fleft[1]];
  const rO = RB.Fbot, rU = [RB.Fright[0]-RB.Fbot[0], RB.Fright[1]-RB.Fbot[1]], rV = [0, RB.Ubot[1]-RB.Fbot[1]];
  const windows = [
    winPath(lO, lU, lV, 0.18, 0.40, 0.22, 0.46),
    winPath(lO, lU, lV, 0.56, 0.78, 0.50, 0.74),
    winPath(rO, rU, rV, 0.22, 0.44, 0.50, 0.74),
    winPath(rO, rU, rV, 0.60, 0.82, 0.22, 0.46),
  ];

  // Automation satellites in a ring around the (shrunken) building
  const hub = [250, 292];
  const sats = [
    { x: 250, y: 86 }, { x: 416, y: 168 }, { x: 430, y: 372 },
    { x: 250, y: 460 }, { x: 70, y: 372 }, { x: 84, y: 168 },
  ];

  return (
    <svg className="roadmap-building-svg" viewBox="0 0 500 500" fill="none" aria-hidden="true">
      <defs>
        <linearGradient id="rbStroke" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#20C8A2" /><stop offset="100%" stopColor="#1E82D2" />
        </linearGradient>
        <filter id="rbGlow" x="-60%" y="-60%" width="220%" height="220%">
          <feGaussianBlur stdDeviation="3.2" result="b" />
          <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
        </filter>
      </defs>

      <g className={'rb-main' + (networkOn ? ' rb-main-shrunk' : '')}>
        {/* 1 — Foundation: excavation + slab + pulsing survey grid + footings */}
        <g className={cls(0)} stroke="url(#rbStroke)">
          {/* excavation outline (dashed, larger) */}
          <path d="M250,316 L416,388 L250,476 L84,388 Z" strokeWidth="1" opacity="0.3" strokeDasharray="3 7" />
          {/* slab depth + footings */}
          <path className="rb-draw" pathLength="1" d="M100,396 L100,420 L250,488 L250,462 Z" strokeWidth="2" opacity="0.55" />
          <path className="rb-draw" pathLength="1" d="M250,462 L250,488 L400,420 L400,396 Z" strokeWidth="2" opacity="0.55" />
          {[[100,420],[250,488],[400,420]].map((f,i)=>(
            <line key={'ft'+i} className="rb-draw" pathLength="1" x1={f[0]} y1={f[1]} x2={f[0]} y2={f[1]+16} strokeWidth="3" opacity="0.5" />
          ))}
          {/* top face */}
          <path className="rb-draw" pathLength="1" d={`M${_pt(RB.Ftop)} L${_pt(RB.Fright)} L${_pt(RB.Fbot)} L${_pt(RB.Fleft)} Z`} strokeWidth="2.5" />
          {/* concentric survey diamonds that pulse outward */}
          {rings.map((s, i) => (
            <path key={'rg'+i} className="rb-found-ring" style={{ animationDelay: (i*0.7)+'s' }}
              d={`M250,${396-66*s} L${250+150*s},396 L250,${396+66*s} L${250-150*s},396 Z`} strokeWidth="1" />
          ))}
          {/* pulsing survey markers at corners */}
          {[RB.Ftop, RB.Fright, RB.Fbot, RB.Fleft].map((c,i)=>(
            <circle key={'sv'+i} className="rb-survey" cx={c[0]} cy={c[1]} r="3.5" fill="#20C8A2" stroke="none" style={{ animationDelay: (i*0.4)+'s' }} />
          ))}
        </g>

        {/* 2 — Growth: walls rise + roof => a real building */}
        <g className={cls(1)} stroke="url(#rbStroke)">
          <path className="rb-draw rb-wall" pathLength="1" d={leftWall} strokeWidth="2" fill="rgba(32,200,162,.04)" />
          <path className="rb-draw rb-wall" pathLength="1" d={rightWall} strokeWidth="2" fill="rgba(30,130,210,.05)" />
          {/* corner posts */}
          {[[RB.Ftop,RB.Utop],[RB.Fright,RB.Uright],[RB.Fbot,RB.Ubot],[RB.Fleft,RB.Uleft]].map((p,i)=>(
            <line key={'po'+i} className="rb-draw" pathLength="1" x1={p[0][0]} y1={p[0][1]} x2={p[1][0]} y2={p[1][1]} strokeWidth="2" opacity="0.8" />
          ))}
          {/* roof */}
          {[RB.Utop,RB.Uright,RB.Ubot,RB.Uleft].map((u,i)=>(
            <line key={'rf'+i} className="rb-draw" pathLength="1" x1={RB.apex[0]} y1={RB.apex[1]} x2={u[0]} y2={u[1]} strokeWidth="2" />
          ))}
          <path className="rb-draw" pathLength="1" d={`M${_pt(RB.Utop)} L${_pt(RB.Uright)} L${_pt(RB.Ubot)} L${_pt(RB.Uleft)} Z`} strokeWidth="1.5" opacity="0.7" />
          {/* a light that travels up the front edge — growth */}
          <circle className="rb-grow-dot" r="3.5" fill="#20C8A2" filter="url(#rbGlow)">
            <animateMotion dur="2.6s" repeatCount="indefinite" path={`M${_pt(RB.Fbot)} L${_pt(RB.Ubot)}`} />
          </circle>
        </g>

        {/* 3 — Operation: wiring comes alive — window glows + conduits */}
        <g className={cls(2)} stroke="url(#rbStroke)">
          {windows.map((d, i) => (
            <path key={'wi'+i} className="rb-window" d={d} fill="rgba(32,200,162,.18)" strokeWidth="1.4"
              filter="url(#rbGlow)" style={{ animationDelay: (i*0.5)+'s' }} />
          ))}
          {/* conduits up the posts + center, with energy flowing */}
          <path id="rbcL" d={`M${_pt(RB.Fleft)} L${_pt(RB.Uleft)}`} strokeWidth="1.2" opacity="0.4" strokeDasharray="2 5" />
          <path id="rbcR" d={`M${_pt(RB.Fright)} L${_pt(RB.Uright)}`} strokeWidth="1.2" opacity="0.4" strokeDasharray="2 5" />
          <path id="rbcC" d={`M${_pt(RB.Fbot)} L${_pt(RB.Ubot)} L${_pt(RB.apex)}`} strokeWidth="1.2" opacity="0.4" strokeDasharray="2 5" />
          {['rbcL','rbcR','rbcC'].map((id,i)=>(
            <circle key={'cd'+i} r="3" fill={i===1?'#1E82D2':'#20C8A2'} filter="url(#rbGlow)">
              <animateMotion dur={`${2.4+i*0.5}s`} begin={`${i*0.6}s`} repeatCount="indefinite"><mpath href={`#${id}`} /></animateMotion>
            </circle>
          ))}
        </g>
      </g>

      {/* 4 — Automation: connect to a network of other buildings */}
      <g className={'rb-network' + (networkOn ? ' shown' : '')} stroke="url(#rbStroke)">
        {sats.map((s, i) => (
          <line key={'ln'+i} x1={hub[0]} y1={hub[1]} x2={s.x} y2={s.y} strokeWidth="1" opacity="0.25" strokeDasharray="2 6" />
        ))}
        {sats.map((s, i) => (
          <circle key={'nd'+i} r="3" fill={i % 2 ? '#1E82D2' : '#20C8A2'} filter="url(#rbGlow)">
            <animateMotion dur={`${2.6 + (i % 3) * 0.5}s`} begin={`${i * 0.35}s`} repeatCount="indefinite"
              path={`M${hub[0]},${hub[1]} L${s.x},${s.y}`} />
          </circle>
        ))}
        {sats.map((s, i) => (
          <path key={'sat'+i} className="rb-sat" d={SAT_SHAPES[i % SAT_SHAPES.length](s.x, s.y)}
            strokeWidth="2" strokeLinejoin="round" style={{ animationDelay: (i * 0.12) + 's' }} />
        ))}
      </g>
    </svg>
  );
}

// --- Stage data -----------------------------------------------------------
const ROADMAP_STAGES = [
  {
    n: '01', name: 'Foundation', outcome: 'A credible first step',
    desc: 'Start with a clean one-page site, built without templates: fast, mobile-ready, and optimized for organic and generative search.',
    chips: ['Custom design', 'Mobile-first build', 'On-page SEO', 'Hosting + SSL'],
    testimonial: {
      quote: "Eric showed me a working version of my new website before I'd given him a dollar. I'd never had a vendor do that. Best decision I've made for my business.",
      who: 'Kris Addison, Owner · Addison Excavations',
    },
  },
  {
    n: '02', name: 'Growth', outcome: 'A steady source of qualified leads',
    desc: 'Expand the site with service pages, local + AI search, and a blog that compounds quietly, so the right people find you instead of your competition.',
    chips: ['Service pages', 'Local + GEO & SEO', 'Monthly blog cadence', 'Analytics + Search Console'],
    mantra: 'Start small, scale selectively. Build a foundation that works, then add new systems as you grow.',
  },
  {
    n: '03', name: 'Operation', outcome: 'Build systems that scale',
    desc: 'Wire the website into the rest of the business: CRM, email, dashboards. A lead arrives, routes to a person, and is tracked end to end.',
    chips: ['CRM setup', 'Website ↔ CRM', 'Reporting dashboard', 'Pipeline + attribution'],
    testimonial: {
      quote: "PDA built us the dashboard we'd been describing in meetings for two years and that no other vendor could ever quite deliver. Took six weeks.",
      who: 'Priya Nair, GM · MyLTC Insurance',
    },
    skLink: true,
  },
  {
    n: '04', name: 'Automation', outcome: 'Your time, given back',
    desc: "Automate the things that shouldn't need a human: follow-up sequences, document generation, content drafts, internal alerts. Owner hours back in your week.",
    chips: ['Lead nurture sequences', 'Custom GPTs + AI agents', 'Multi-system workflows', 'Automated reporting'],
    mantra: 'Sustainable systems over quick wins. A good tech stack should outlast any single trend — we build for durability, not novelty.',
  },
];

function HomeSchematics() {
  const I = window.PDAIcons;
  const sectionRef = React.useRef(null);
  const headerRef = React.useRef(null);
  const wrapRef = React.useRef(null);
  const [active, setActive] = React.useState(0);
  const [pinned, setPinned] = React.useState(false);
  const activeRef = React.useRef(0);

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

    section.classList.add('is-pinned');
    setPinned(true);

    const ctx = gsap.context(() => {
      ScrollTrigger.create({
        trigger: wrap,
        start: 'top top',
        end: () => '+=' + window.innerHeight * 4,
        pin: true,
        scrub: true,
        invalidateOnRefresh: true,
        onUpdate: (self) => {
          const idx = Math.min(ROADMAP_STAGES.length - 1, Math.floor(self.progress * ROADMAP_STAGES.length));
          if (idx !== activeRef.current) {
            activeRef.current = idx;
            setActive(idx);
          }
        },
      });

      gsap.to(headerRef.current, {
        opacity: 0, y: 80, ease: 'none',
        scrollTrigger: {
          trigger: wrap, start: 'top top',
          end: () => '+=' + window.innerHeight * 0.8, scrub: true,
        },
      });
    }, section);

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

  const buildingStage = pinned ? active : ROADMAP_STAGES.length - 1;

  return (
    <section className="schem-section" ref={sectionRef} aria-label="The Roadmap — our method">
      <div className="schem-wrap" ref={wrapRef}>
        <div className="schem-header" ref={headerRef}>
          <h2 className="section-display">The Roadmap</h2>
        </div>

        <div className="schem-body">
          <div className="schem-stages">
            {ROADMAP_STAGES.map((s, i) => (
              <div className={'schem-stage schem-stage-' + s.n + (i === active ? ' is-active' : '')} key={s.n}>
                <div className="schem-stage-content">
                  <span className="schem-stage-eyebrow">{s.name}</span>
                  <div className="schem-stage-head">
                    <span className="schem-stage-num gradient-text">{s.n}</span>
                    <h3 className="schem-stage-name gradient-text">{s.outcome}</h3>
                  </div>
                  <p className="schem-stage-desc">{s.desc}</p>
                  <div className="svc-chips">
                    {s.chips.map((c, k) => (
                      <span className="svc-chip" key={k}><I.Check size={12} />{c}</span>
                    ))}
                  </div>

                  {s.testimonial && (
                    <blockquote className="schem-testimonial">
                      <span className="schem-quote-mark"><I.Quote size={22} /></span>
                      <p>{s.testimonial.quote}</p>
                      <cite>{s.testimonial.who}</cite>
                    </blockquote>
                  )}
                  {s.mantra && (
                    <div className="schem-mantra">
                      <p>{s.mantra}</p>
                    </div>
                  )}
                  {s.skLink && (
                    <a className="schem-sk-link" href="skeleton-key.html">
                      <I.Link size={14} />
                      <span>Learn about The Skeleton Key</span>
                      <I.Arrow size={12} />
                    </a>
                  )}
                </div>
              </div>
            ))}
          </div>

          <div className="schem-building" aria-hidden="true">
            <RoadmapBuilding stage={buildingStage} />
          </div>
        </div>

        <div className="schem-progress" aria-hidden="true">
          {ROADMAP_STAGES.map((s, i) => (
            <span className={'schem-dot' + (i <= active ? ' is-on' : '')} key={s.n} />
          ))}
        </div>
      </div>
    </section>
  );
}
window.HomeSchematics = HomeSchematics;
