// v5 — Method as a flywheel (5 stages: Signal to System)
// Adapted from v2's flywheel.jsx — auto-cycling, click to pause, with a detail panel.

const METHOD_STAGES = [
{
  id: "sense",
  label: "Sense",
  tagline: "Gather live signals before deciding what the answer should be.",
  body: "Audience language, market behavior, cultural tension, competitor patterns, product constraints, founder intuition, and research artifacts. The point is not to collect everything. The point is to hear the right frequency.",
  outputs: ["Signal scan", "Audience language", "Category tension", "Research brief", "Creative territory map"]
},
{
  id: "frame",
  label: "Frame",
  tagline: "Turn scattered inputs into a thesis.",
  body: "What the idea is. Who it is for. What problem of meaning it solves. What people need to understand before they can care. Framing is the work that decides whether everything downstream compounds or gets wasted.",
  outputs: ["Category thesis", "Positioning frame", "Experience principles", "Narrative architecture"]
},
{
  id: "multiply",
  label: "Multiply",
  tagline: "Use AI to generate range fast.",
  body: "AI-native workflows expand the field: concept directions, visual systems, interface patterns, product stories, motion ideas, content models, and prototype variants. The goal is not more options for their own sake. It is more range before judgment.",
  outputs: ["Concept range", "Prompt systems", "Visual studies", "Prototype directions", "Scenario set"]
},
{
  id: "reduce",
  label: "Reduce",
  tagline: "Judgment chooses the direction.",
  body: "Narrow the range through taste, strategy, feasibility, audience trust, regulatory sensitivity, and the ability to teach the idea back to the team. This is where most of the value lives.",
  outputs: ["Selected direction", "Design rationale", "Messaging system", "Prototype priorities", "Validation criteria"]
},
{
  id: "systemize",
  label: "Systemize",
  tagline: "Make the direction reusable.",
  body: "Turn the chosen direction into something the team can run: a website, brand system, product architecture, packaging system, campaign toolkit, curriculum, AI workflow, or operating playbook.",
  outputs: ["Design system", "Content system", "Product / brand guide", "Prototype", "Implementation roadmap"]
}];


const V5Flywheel = ({ size = 540 }) => {
  const [active, setActive] = useState(0);
  const [paused, setPaused] = useState(false);
  const wheelRef = useRef(null);

  useEffect(() => {
    if (paused) return;
    const id = setInterval(() => setActive((a) => (a + 1) % METHOD_STAGES.length), 4800);
    return () => clearInterval(id);
  }, [paused]);

  useEffect(() => {
    const el = wheelRef.current;if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (!e.isIntersecting) setPaused(true);
    }, { threshold: 0.05 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const pick = (i) => {setPaused(true);setActive(i);};

  const r = size / 2;
  const ringR = r - 70;
  const nodeR = 50;
  const cx = r,cy = r;

  // Position nodes evenly around — start at top (12 o'clock), go clockwise
  const positions = METHOD_STAGES.map((_, i) => {
    const angle = (-90 + i * (360 / METHOD_STAGES.length)) * Math.PI / 180;
    return { x: cx + ringR * Math.cos(angle), y: cy + ringR * Math.sin(angle), angle };
  });

  const activeStage = METHOD_STAGES[active];

  return (
    <div className="v5-flywheel-layout" ref={wheelRef}>
      {/* Wheel */}
      <div className="v5-flywheel-wheel" style={{ width: size, height: size }}>
        <div className="v5-flywheel-meta">
          <span className="mono v5-flywheel-meta-label">Stage</span>
          <span className="v5-flywheel-counter">
            {String(active + 1).padStart(2, "0")}
            <span> / {String(METHOD_STAGES.length).padStart(2, "0")}</span>
          </span>
        </div>

        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="v5-flywheel-svg">
          <defs>
            <radialGradient id="v5fw-core" cx="50%" cy="48%">
              <stop offset="0%" stopColor="var(--v4-paper)" />
              <stop offset="100%" stopColor="var(--v4-paper-2)" />
            </radialGradient>
            <radialGradient id="v5fw-glow">
              <stop offset="0%" stopColor="var(--v4-accent-hi)" stopOpacity="0.25" />
              <stop offset="100%" stopColor="var(--v4-accent)" stopOpacity="0" />
            </radialGradient>
          </defs>

          {/* Outer rings */}
          <circle cx={cx} cy={cy} r={ringR + 22} fill="none" stroke="var(--v4-line-soft)" strokeWidth="0.6" strokeDasharray="2 6" />
          <circle cx={cx} cy={cy} r={ringR} fill="none" stroke="var(--v4-line)" strokeWidth="0.8" />

          {/* Compass ticks */}
          {Array.from({ length: 60 }).map((_, i) => {
            const a = i * 360 / 60 * Math.PI / 180;
            const r1 = ringR + 6,r2 = ringR + (i % 5 === 0 ? 14 : 10);
            return (
              <line key={i}
              x1={cx + r1 * Math.cos(a)} y1={cy + r1 * Math.sin(a)}
              x2={cx + r2 * Math.cos(a)} y2={cy + r2 * Math.sin(a)}
              stroke="var(--v4-mute)" strokeWidth={i % 5 === 0 ? 0.8 : 0.4} opacity={i % 5 === 0 ? 0.65 : 0.3} />);


          })}

          {/* Active arc — copper segment glowing on the active stage */}
          {METHOD_STAGES.map((_, i) => {
            const a1 = positions[i].angle;
            const a2 = positions[(i + 1) % METHOD_STAGES.length].angle;
            const x1 = cx + ringR * Math.cos(a1);
            const y1 = cy + ringR * Math.sin(a1);
            const x2 = cx + ringR * Math.cos(a2);
            const y2 = cy + ringR * Math.sin(a2);
            const isActive = i === active;
            return (
              <path key={`arc-${i}`}
              d={`M ${x1} ${y1} A ${ringR} ${ringR} 0 0 1 ${x2} ${y2}`}
              fill="none"
              stroke={isActive ? "var(--v4-accent)" : "transparent"}
              strokeWidth="2.2"
              strokeLinecap="round"
              style={{ transition: "stroke .55s ease" }} />);


          })}

          {/* Glow behind active node */}
          <circle r="80"
          cx={positions[active].x} cy={positions[active].y}
          fill="url(#v5fw-glow)"
          style={{ transition: "cx 0.9s var(--ease-soft, ease), cy 0.9s var(--ease-soft, ease)" }} />
          

          {/* Center disc */}
          <circle cx={cx} cy={cy} r={88} fill="url(#v5fw-core)" stroke="var(--v4-ink)" strokeWidth="1" />
          <circle cx={cx} cy={cy} r={78} fill="none" stroke="var(--v4-line-soft)" strokeWidth="0.7" />
          <text x={cx} y={cy - 18} textAnchor="middle" fontFamily="var(--mono)" fontSize="9" letterSpacing="3" fill="var(--v4-mute)">JUDGMENT</text>
          <text x={cx} y={cy - 5} textAnchor="middle" fontFamily="var(--mono)" fontSize="9" letterSpacing="3" fill="var(--v4-mute)">IN THE LOOP</text>
          <text x={cx} y={cy + 18} textAnchor="middle" fontFamily="var(--serif)" fontSize="14" fontStyle="italic" fill="var(--v4-ink-2)">Signal → System</text>

          {/* Stage nodes */}
          {METHOD_STAGES.map((s, i) => {
            const p = positions[i];
            const isActive = i === active;
            return (
              <g key={s.id}
              style={{ cursor: "pointer", transition: "transform .25s ease" }}
              onClick={() => pick(i)}
              onMouseEnter={() => pick(i)}>
                
                <circle cx={p.x} cy={p.y} r={nodeR}
                fill={isActive ? "var(--v4-ink)" : "var(--v4-paper)"}
                stroke={isActive ? "var(--v4-ink)" : "var(--v4-line)"}
                strokeWidth="1"
                style={{ transition: "fill .4s ease, stroke .4s ease" }} />
                
                {!isActive && <circle cx={p.x} cy={p.y} r={nodeR - 6} fill="none" stroke="var(--v4-line-soft)" strokeWidth="0.8" />}
                <text x={p.x} y={p.y - 4} textAnchor="middle"
                fontFamily="var(--serif)" fontSize="19"
                fill={isActive ? "var(--v4-paper)" : "var(--v4-ink)"}>{s.label}</text>
                <text x={p.x} y={p.y + 14} textAnchor="middle"
                fontFamily="var(--mono)" fontSize="8.5" letterSpacing="1.6"
                fill={isActive ? "rgba(242,238,230,0.6)" : "var(--v4-mute)"}>0{i + 1}</text>
              </g>);

          })}
        </svg>

        <div className="v5-flywheel-corner-bl">
          {paused ? "paused" : "auto-cycle"}
        </div>
      </div>

      {/* Detail panel */}
      <div className="v5-flywheel-detail">
        <div className="v5-flywheel-detail-head">
          <span className="mono v5-flywheel-detail-stage">Stage {String(active + 1).padStart(2, "0")} of {String(METHOD_STAGES.length).padStart(2, "0")}</span>
          <div className="v5-flywheel-detail-ticks">
            {METHOD_STAGES.map((_, i) =>
            <button key={i} type="button" onClick={() => pick(i)}
            className={`v5-flywheel-tick ${i === active ? "is-active" : ""}`}
            aria-label={`Show stage ${i + 1}`} />

            )}
          </div>
        </div>

        <div key={activeStage.id} className="v5-flywheel-detail-body">
          <h3 className="v5-flywheel-detail-title">{activeStage.label}.</h3>
          <p className="v5-flywheel-detail-tagline"><span className="emph">{activeStage.tagline}</span></p>
          <p className="v5-flywheel-detail-body-copy">{activeStage.body}</p>

          <div className="v5-flywheel-outputs">
            <span className="v5-flywheel-outputs-label">— Outputs</span>
            <ul>
              {activeStage.outputs.map((o, i) =>
              <li key={o} className="v5-flywheel-output">
                  <span className="v5-flywheel-output-mark">+</span>
                  <span>{o}</span>
                </li>
              )}
            </ul>
          </div>
        </div>

        <div className="v5-flywheel-detail-foot">
          <span className="mono">{String(active + 1).padStart(2, "0")} / {String(METHOD_STAGES.length).padStart(2, "0")}</span>
          <button type="button" className="mono v5-flywheel-next" onClick={() => pick((active + 1) % METHOD_STAGES.length)}>
            Next stage →
          </button>
        </div>
      </div>
    </div>);

};

const DISCIPLINES = [
{ n: "01", k: "Experience Strategy", d: "Decision architecture, journeys, service design, and research-led structure.", t: "Makes the idea legible." },
{ n: "02", k: "Interface Systems", d: "Interfaces with hierarchy, restraint, confident type, and system-level usability.", t: "Makes the product usable." },
{ n: "03", k: "Brand & Narrative", d: "Positioning, identity, naming, voice, and category language built as operating logic.", t: "Makes the story repeatable." },
{ n: "04", k: "Product & Packaging", d: "From early concept to shipped surface, CPG systems, hardware, software, and launch-ready market experiences.", t: "Makes the offer tangible." },
{ n: "05", k: "Motion & Behavior", d: "Kinetic prototypes, interaction motion, demos, and build animations that show how the system behaves.", t: "Makes the work feel alive." },
{ n: "06", k: "Design Engineering", d: "Runnable prototypes, AI-assisted builds, component systems, and browser-based proof of concept work.", t: "Makes the concept testable." }];


const V5Disciplines = () => {
  const rowRef = useRef(null);
  useEffect(() => {
    const el = rowRef.current;if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        el.querySelectorAll(".v4-cap-cell").forEach((c, i) => {
          c.style.setProperty("--d", `${i * 90}ms`);
          c.classList.add("is-in");
        });
        io.disconnect();
      }
    }, { threshold: 0.2 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <div className="v5-method-disciplines">
      <div className="v5-section-open v5-section-open-sub">
        <div className="v5-section-open-eyebrow">
          <span className="v5-section-open-rule"></span>
          <span className="v5-section-open-num">02b</span>
          <span>Disciplines · the practice, in six parts</span>
        </div>
        <div className="v5-section-open-row v5-section-open-row-disciplines">
          <h3 className="v5-section-open-headline v5-disciplines-headline" data-cursor="Six disciplines · one instrument">
            <WordReveal text="Every discipline" stagger={60} />
            <br />
            <span className="emph"><WordReveal text="a new idea needs." stagger={60} startDelay={350} /></span>
          </h3>
          <div className="v5-section-open-copy v5-disciplines-copy">
            <FadeIn delay={300}>
              Six ways to move an idea from signal to system, with AI accelerating the range, rhythm, and build cycle.
            </FadeIn>
          </div>
        </div>
      </div>
      <div className="v4-cap-row v5-method-disciplines-row" ref={rowRef}>
        {DISCIPLINES.map((c) =>
        <div key={c.n} className="v4-cap-cell" data-cursor={`${c.k} · discipline ${c.n}`}>
            <span className="v4-cap-num">{c.n}</span>
            <span className="v4-cap-name">{c.k}</span>
            <span className="v4-cap-desc">{c.d}</span>
            {c.t && <span className="v4-cap-tagline">{c.t}</span>}
          </div>
        )}
      </div>
    </div>);

};

const V5Method = () => {
  return (
    <section id="method" className="v5-method" data-screen-label="Method · Signal to System">
      <div className="v4-container">
        {/* Section starter — methodology, not AI-specific */}
        <div className="v5-section-open">
          <div className="v5-section-open-eyebrow">
            <span className="v5-section-open-rule"></span>
            <span className="v5-section-open-num">02</span>
            <span>Method · how the work moves</span>
          </div>
          <div className="v5-section-open-row">
            <h2 className="v5-section-open-headline v5-method-manifesto" data-cursor="The method">
              <WordReveal text="Find the signal." stagger={60} />
              <br />
              <span className="emph"><WordReveal text="Shape the system." stagger={60} startDelay={400} /></span>
            </h2>
            <div className="v5-section-open-copy" style={{ fontSize: "19px" }}>
              <FadeIn delay={350}>
                Less a process than a working instrument. The cycle starts with live signals, turns them into a thesis, uses AI to create range, applies judgment to reduce the field, then builds a system the team can actually run. Signal becomes system. Range becomes direction. Direction becomes something usable.
              </FadeIn>
            </div>
          </div>
        </div>

        {/* Flywheel — the cycle */}
        <V5Flywheel />

        {/* Disciplines — the hands */}
        <V5Disciplines />
      </div>
    </section>);

};

Object.assign(window, { V5Method, V5Flywheel, V5Disciplines, METHOD_STAGES });