/* global React */

function Trilemma() {
  return (
    <figure className="re-trilemma" aria-label="Cost, Speed, Quality triangle">
      <div className="re-trilemma-stage">
        <svg
          className="re-trilemma-svg"
          viewBox="0 0 100 80"
          preserveAspectRatio="xMidYMid meet"
          aria-hidden="true"
        >
          {/* Triangle is sized so its centroid (50, 40) sits at the
              centre of the viewBox: apex at top edge, base 75% down. */}
          <polygon className="re-trilemma-edge" points="50,0 15.35,60 84.65,60" />
          <text
            className="re-trilemma-mark"
            x="49.2" y="40"
            textAnchor="middle"
            dominantBaseline="central"
          >RE</text>
        </svg>
        <span className="re-trilemma-label re-trilemma-label-quality">Quality</span>
        <span className="re-trilemma-label re-trilemma-label-cost">Cost</span>
        <span className="re-trilemma-label re-trilemma-label-speed">Speed</span>
      </div>
    </figure>
  );
}

const { useState: useSvcState, useRef: useSvcRef, useLayoutEffect: useSvcLayoutEffect } = React;

const pad2 = (i) => String(i + 1).padStart(2, "0");

const STEPS_M = [
  { stage: "Napkin sketch", no: "M.01", title: "3D CAD design",
    desc: "Parametric models in SolidWorks, Onshape, Fusion 360, or Inventor, whichever your team already uses. Built so your engineers can keep editing them after handoff." },
  { stage: "CAD model", no: "M.02", title: "CAM programming",
    desc: "Toolpaths and setup sheets for 3-axis, 4-axis, and lathe work on the machines you have." },
  { stage: "Ready for parts", no: "M.03", title: "Manufacturing & assembly",
    desc: "Short-run parts made in-house or through job shops we trust, shipped with a first-article inspection report." },
  { stage: "Working prototype", no: "M.04", title: "DFM & design review",
    desc: "If a part quotes too high or yields too low, we find out why. It's usually a radius, a draft angle, or a tolerance tighter than it needs to be." },
];

const STEPS_E = [
  { stage: "Feature list", no: "E.01", title: "Circuit design",
    desc: "Schematics from your block diagram or breadboard, using parts you can actually buy, with second sources where it matters." },
  { stage: "Arduino or Pi build", no: "E.02", title: "Embedded upgrades",
    desc: "Move off an Arduino or Raspberry Pi onto a custom board with the same I/O, a smaller footprint, and a lower BOM cost." },
  { stage: "Finished schematic", no: "E.03", title: "PCB layout",
    desc: "Layout in KiCad or Altium. We assemble the first boards and bring up the power rails before firmware starts." },
];

const STEPS_S = [
  { stage: "Bare hardware", no: "S.01", title: "Embedded firmware",
    desc: "C++ on PlatformIO using the vendor HAL (STM32, ESP-IDF, Pico SDK, Zephyr). Code goes into your Git repo with tests and a README." },
  { stage: "Working device", no: "S.02", title: "Internal tooling",
    desc: "Python tools for your lab or shop floor, like calibration jigs, instrument control, and data collection." },
  { stage: "Proof of concept", no: "S.03", title: "End-user software",
    desc: "Customer-facing apps and dashboards built to your brand, on web, desktop, or mobile, and written so your team can maintain them." },
];

const DISCIPLINES = [
  {
    n: "01", name: "Mechanical",
    question: "Have back-of-the-napkin sketches needing proof-of-concept validation?",
    steps: STEPS_M,
  },
  {
    n: "02", name: "Electrical",
    question: "Have a breadboard mess that needs to become a board?",
    steps: STEPS_E,
  },
  {
    n: "03", name: "Software",
    question: "Have a vibe-coded proof-of-concept that needs to be the real deal?",
    steps: STEPS_S,
  },
];

// Header, timeline, and step panels. Rendered live inside each pinned
// section, and as a static copy (onJump omitted) inside the previous
// section's preview.
function DiscBody({ n, name, question, steps, active, onJump }) {
  const count = steps.length;
  const Stop = onJump ? "button" : "span";
  return (
    <>
      <header className="re-disc-head">
        <span className="re-disc-bignum">{n}</span>
        <span className="re-eyebrow re-disc-eyebrow">{name.toUpperCase()}</span>
        <h3 className="re-disc-q">{question}</h3>
      </header>

      <div className="re-steps" style={{ "--steps": count }}>
        <div className="re-steps-track" aria-hidden="true">
          <span className="re-steps-fill" style={{ width: `${(active / (count - 1)) * 100}%` }} />
        </div>
        <ol className="re-steps-list">
          {steps.map((s, i) => (
            <li key={s.no}>
              <Stop
                {...(onJump ? { type: "button", onClick: () => onJump(i), "aria-current": i === active ? "step" : undefined } : {})}
                className={"re-step" + (i === active ? " is-active" : i < active ? " is-past" : "")}
              >
                <span className="re-step-n">{pad2(i)}</span>
                <span className="re-step-dot" aria-hidden="true" />
                <span className="re-step-name">{s.stage}</span>
              </Stop>
            </li>
          ))}
        </ol>
      </div>

      <div className="re-step-panels">
        {steps.map((s, i) => (
          <article
            key={s.no}
            className={"re-step-panel" + (i === active ? " is-active" : "")}
            aria-hidden={i !== active}
          >
            <span className="re-svc-item-no">{s.no}</span>
            <h4 className="re-step-title">{s.title}</h4>
            <p className="re-step-desc">{s.desc}</p>
          </article>
        ))}
      </div>
    </>
  );
}

function HowBody() {
  return (
    <>
      <header className="re-how-head">
        <span className="re-eyebrow">HOW WE WORK</span>
        <h2>We work in your tools, and you own everything we make.</h2>
      </header>
      <div className="re-how-grid">
        <div>
          <div className="re-eyebrow">YOUR TOOLS</div>
          <p>We use the CAD package your team already runs and commit code to your Git repo and CI. You don't have to switch to our setup.</p>
        </div>
        <div>
          <div className="re-eyebrow">YOU OWN THE WORK</div>
          <p>You get every source file, schematic, layout, and line of firmware with no license strings attached. If we part ways, your team picks it up from there.</p>
        </div>
        <div>
          <div className="re-eyebrow">SCOPE</div>
          <p>Anything from a single part to a full product. Sprints are fixed length and fixed price, with hourly work available for ongoing help. No retainers or minimums.</p>
        </div>
      </div>
    </>
  );
}

// Section layout: [pinned content][preview][spacer]. The spacer is the scroll
// distance spent stepping through the timeline; scroll speed is never
// altered. The preview is a static copy of the next section, pinned right
// under the content and filling the rest of the viewport, so the gap between
// sections stays tight while the steps advance. When the section ends, the
// real next section arrives exactly where the copy sits and the copy hides.
// Earlier sections stack above later ones (`layer`) so the real next section
// slides in behind the copy instead of over it.
function Discipline({ data, next, layer }) {
  const { steps } = data;
  const secRef = useSvcRef(null);
  const stickyRef = useSvcRef(null);
  const peekRef = useSvcRef(null);
  const [active, setActive] = useSvcState(0);
  const [handedOff, setHandedOff] = useSvcState(false);
  const count = steps.length;

  useSvcLayoutEffect(() => {
    let frame = 0;
    const update = () => {
      frame = 0;
      const sec = secRef.current, sticky = stickyRef.current;
      if (!sec || !sticky) return;
      const contentH = sticky.offsetHeight;
      sec.style.setProperty("--content-h", contentH + "px");
      const r = sec.getBoundingClientRect();
      const travel = r.height - contentH;
      const p = travel > 0 ? Math.min(Math.max(-r.top / travel, 0), 0.9999) : 0;
      setActive(Math.floor(p * count));
      const off = r.bottom <= contentH + 1;
      // Toggle the DOM directly too, so the copy never lingers a render late.
      if (peekRef.current) peekRef.current.classList.toggle("is-hidden", off);
      setHandedOff(off);
    };
    const onScroll = () => { if (!frame) frame = requestAnimationFrame(update); };
    update();
    const ro = new ResizeObserver(onScroll);
    ro.observe(stickyRef.current);
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      ro.disconnect();
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      if (frame) cancelAnimationFrame(frame);
    };
  }, [count]);

  const jump = (i) => {
    const sec = secRef.current;
    const travel = sec.offsetHeight - stickyRef.current.offsetHeight;
    const top = sec.getBoundingClientRect().top + window.scrollY + travel * (i + 0.5) / count;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    window.scrollTo({ top, behavior: reduce ? "auto" : "smooth" });
  };

  return (
    <section className="re-disc" ref={secRef} style={{ "--steps": count, zIndex: layer }}>
      <div className="re-disc-sticky re-disc-pad" ref={stickyRef}>
        <DiscBody {...data} active={active} onJump={jump} />
      </div>

      <div className={"re-peek" + (handedOff ? " is-hidden" : "")} ref={peekRef} aria-hidden="true">
        <div className="re-peek-inner">
          {next
            ? <div className="re-peek-disc"><div className="re-disc-pad"><DiscBody {...next} active={0} /></div></div>
            : <div className="re-how"><HowBody /></div>}
        </div>
      </div>

      <div className="re-disc-spacer" aria-hidden="true" />
    </section>
  );
}

function Services() {
  return (
    <>
      <section className="re-svc-hero" id="why">
        <span className="re-eyebrow">WHY ONE SHOP</span>
        <h2 className="re-svc-h1">
          Cost. Speed. Quality.
          <br/><em>Pick three.</em>
        </h2>
        <div className="re-svc-thesis">
          <p>
            Most hardware projects lose time and money in the handoffs between mechanical,
            electrical, and software teams. We do all three, so your budget goes into the design
            instead of the meetings about it.
          </p>
          <Trilemma />
        </div>
      </section>

      <section className="re-svc-list" id="services">
        <header className="re-svc-list-head">
          <span className="re-eyebrow">SERVICES</span>
          <h2>Engagements that meet you where you are.</h2>
          <p>Bring us a napkin sketch, a breadboard, or a prototype that only works on your bench.</p>
        </header>
        {DISCIPLINES.map((d, i) => (
          <Discipline key={d.n} data={d} next={DISCIPLINES[i + 1]} layer={DISCIPLINES.length - i} />
        ))}
      </section>

      <section className="re-how" id="how-we-work">
        <HowBody />
      </section>
    </>
  );
}

window.Services = Services;
