// Motion pages — Principles, Easing/Timing, Live demos
const TM = window.RS_TOKENS;

function MotionPrinciplesPage() {
  return (
    <div className="page-anim">
      <SectionHeader eyebrow="Motion · Principles" title="Motion principles"
        lede="Motion is how RegScale communicates change. Six rules govern every animation in our marketing surfaces."
        provenance={{ level: "recommended", note: "RegScale source materials contain no documented motion guidelines. These six principles are proposed standards — synthesized from product positioning and industry conventions. Needs brand-team sign-off before adoption." }} />

      <div className="grid grid-2">
        {[
          { n: "01", t: "Functional first", d: "Motion answers ‘what changed?’. If a viewer can't name the function, cut it." },
          { n: "02", t: "Quick to enter, quicker to leave", d: "Entrances 240–400ms. Exits 160–240ms. Never make a user wait for an exit." },
          { n: "03", t: "One focal point", d: "Per screen, one element earns ‘emphasis’ easing. Everything else uses standard." },
          { n: "04", t: "Stagger to suggest sequence", d: "Lists, KPI tiles, and reveals stagger at 80ms. Tight enough to feel grouped, loose enough to read order." },
          { n: "05", t: "Respect reduced motion", d: "Honor prefers-reduced-motion. Replace movement with opacity. Never disable feedback entirely." },
          { n: "06", t: "Brand-coded easing", d: "Emphasis curve (a soft overshoot) is the brand's signature. Use it sparingly — heroes, success states, the moment a number lands." },
        ].map(p => (
          <div key={p.n} className="principle">
            <div className="num">{p.n}</div>
            <h3>{p.t}</h3>
            <p>{p.d}</p>
          </div>
        ))}
      </div>

      <H2 sub="The hierarchy of attention through motion.">When to use what</H2>
      <div className="card">
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
          <thead><tr style={{ textAlign: "left", borderBottom: "1px solid var(--rs-border)" }}>
            <th style={{ padding: "10px 0" }}>Surface</th><th>Easing</th><th>Duration</th><th>Notes</th>
          </tr></thead>
          <tbody>
            {[
              ["Hero entrance","ease-emphasis","700ms","Stagger eyebrow → headline → CTA at 80ms each"],
              ["Section reveal on scroll","ease-entrance","400ms","Translate-Y 16px, fade in. Trigger at 30% viewport."],
              ["Card hover lift","ease-standard","240ms","translateY(-4px), shadow grows. No scale."],
              ["Button press","ease-standard","80ms","Scale 0.98 on active. Releases instantly."],
              ["Modal enter","ease-emphasis","320ms","Scale 0.95→1, fade scrim simultaneously."],
              ["Modal exit","ease-exit","200ms","No bounce on exit. Out of the way."],
              ["Number ticker","ease-emphasis","900ms","Cinematic — only for hero metrics."],
              ["Loader","linear","continuous","Marquee or spinner — predictable rhythm."],
            ].map((r,i)=>(
              <tr key={i} style={{ borderBottom: "1px solid var(--rs-border)" }}>
                {r.map((c,j) => <td key={j} style={{ padding: "10px 0", fontFamily: j===1||j===2 ? "JetBrains Mono, monospace" : "inherit", fontSize: j===1||j===2 ? 11.5 : 13 }}>{c}</td>)}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function MotionTimingPage() {
  const [runKey, setRunKey] = useState(0);
  const easings = TM.motion.easing;
  return (
    <div className="page-anim">
      <SectionHeader eyebrow="Motion · Timing & Easing" title="Timing & easing tokens"
        lede="Six easings, six durations. Don't invent new ones."
        provenance={{ level: "recommended", note: "Curves and durations follow Material Motion / Apple HIG conventions. No motion tokens exist in source — these are proposed canonical values." }} />

      <H2 sub="Click ‘play’ on any curve to preview.">Easing tokens</H2>
      <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 12 }}>
        <button className="dl-btn" onClick={()=>setRunKey(k=>k+1)}>▶ Play all</button>
      </div>
      <div className="grid grid-2">
        {Object.entries(easings).map(([name, e]) => {
          const m = e.cubic.match(/cubic-bezier\(([-\d.]+),\s*([-\d.]+),\s*([-\d.]+),\s*([-\d.]+)\)/);
          const pts = m ? [m[1],m[2],m[3],m[4]].map(parseFloat) : [0,0,1,1];
          return (
            <div key={name} className="demo-card">
              <div className="demo-card-head">
                <h4>{name}</h4>
                <button className="replay" onClick={()=>setRunKey(k=>k+1)}>Replay</button>
              </div>
              <p className="desc">{e.use}</p>
              <EasingCurve p1x={pts[0]} p1y={pts[1]} p2x={pts[2]} p2y={pts[3]} runKey={runKey} />
              <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: "var(--rs-text-muted)", marginTop: 10 }}>
                {e.cubic}
              </div>
            </div>
          );
        })}
      </div>

      <H2>Duration scale</H2>
      <div className="card" style={{ padding: 24 }}>
        <div style={{ display: "grid", gridTemplateColumns: "120px 1fr 100px", rowGap: 14, columnGap: 16, alignItems: "center" }}>
          {Object.entries(TM.motion.duration).map(([name, val]) => {
            const ms = parseInt(val);
            const pct = Math.min(100, (ms / 900) * 100);
            return (
              <React.Fragment key={name}>
                <div style={{ fontFamily: "JetBrains Mono", fontSize: 12, fontWeight: 600 }}>{name}</div>
                <div style={{ height: 8, background: "var(--rs-bg)", borderRadius: 4, overflow: "hidden" }}>
                  <div style={{ height: "100%", width: pct + "%", background: "var(--rs-grad-hero)" }} />
                </div>
                <div style={{ fontFamily: "JetBrains Mono", fontSize: 12, color: "var(--rs-text-muted)", textAlign: "right" }}>{val}</div>
              </React.Fragment>
            );
          })}
        </div>
      </div>

      <H2>CSS tokens</H2>
      <CodeBlock>
{`/* Easing */
--ease-standard: cubic-bezier(0.4, 0.0, 0.2, 1);
--ease-entrance: cubic-bezier(0.0, 0.0, 0.2, 1);
--ease-exit:     cubic-bezier(0.4, 0.0, 1, 1);
--ease-emphasis: cubic-bezier(0.2, 0.9, 0.1, 1);
--ease-spring:   cubic-bezier(0.34, 1.56, 0.64, 1);

/* Duration */
--dur-fast:     160ms;
--dur-base:     240ms;
--dur-slow:     400ms;
--dur-deliberate: 600ms;
--dur-cinematic:  900ms;

/* Stagger */
--stagger-tight: 40ms;
--stagger:       80ms;
--stagger-loose: 140ms;`}
      </CodeBlock>
    </div>
  );
}

function MotionDemosPage() {
  const [keys, setKeys] = useState({});
  const replay = (k) => setKeys(s => ({ ...s, [k]: (s[k]||0)+1 }));

  return (
    <div className="page-anim">
      <SectionHeader eyebrow="Motion · Live demos" title="Motion library"
        lede="Battle-tested patterns for landing pages, webinar promotion, and HTML5 ads. Each demo ships with copy-paste code."
        provenance={{ level: "recommended", note: "Static targets (CTA, key pill, hero composition) are verified from source. The motion treatments applied to them are proposed." }} />

      <H2>Hero entrance — staggered reveal</H2>
      <div className="grid grid-2">
        <div>
          <div className={"hero-mini " + (keys.hero ? "run" : "")} key={keys.hero || 0}>
            <div className="hero-cont">
              <div className="hero-eyebrow">Webinar · Live April 30</div>
              <div className="hero-h">Continuous controls, in real time.</div>
              <div className="hero-cta">Register Now →</div>
            </div>
          </div>
          <button className="dl-btn" style={{ marginTop: 12 }} onClick={()=>replay("hero")}>▶ Replay</button>
        </div>
        <CodeBlock>
{`/* Stagger eyebrow → headline → CTA */
.hero > * { opacity: 0; }
.hero.run > * {
  animation: heroIn 700ms var(--ease-emphasis) both;
}
.hero.run .eyebrow { animation-delay: 60ms; }
.hero.run .headline { animation-delay: 200ms; }
.hero.run .cta { animation-delay: 380ms; }

@keyframes heroIn {
  from { opacity: 0; transform: translateY(16px); }
  to   { opacity: 1; transform: translateY(0); }
}`}
        </CodeBlock>
      </div>

      <H2>CTA button — shimmer on hover</H2>
      <div className="grid grid-2">
        <div className="demo-stage">
          <button className="cta-pill">Register for the Webinar →</button>
        </div>
        <CodeBlock>
{`.cta { position: relative; overflow: hidden; }
.cta::before {
  content: ""; position: absolute; inset: 0;
  background: linear-gradient(120deg,
    transparent 30%,
    rgba(255,255,255,0.4) 50%,
    transparent 70%);
  transform: translateX(-120%);
  transition: transform 700ms var(--ease-standard);
}
.cta:hover::before { transform: translateX(120%); }
.cta:hover { transform: translateY(-2px); }`}
        </CodeBlock>
      </div>

      <H2>Card hover lift</H2>
      <div className="grid grid-2">
        <div className="demo-stage">
          <div className="lift-card">
            <div className="img" />
            <div className="body">
              <h5>State of CCM 2026</h5>
              <p>Deep-dive · 45 min · Live April 30</p>
            </div>
          </div>
        </div>
        <CodeBlock>
{`.card {
  transition:
    transform 320ms var(--ease-standard),
    box-shadow 320ms var(--ease-standard);
}
.card:hover {
  transform: translateY(-6px);
  box-shadow: 0 18px 40px rgba(46,48,145,0.18);
}`}
        </CodeBlock>
      </div>

      <H2>Modal enter / exit</H2>
      <div className="grid grid-2">
        <div className="demo-stage">
          <div className={"modal-stage " + (keys.modal ? "open" : "")} key={keys.modal || 0}>
            <div className="scrim" />
            <div className="modal">
              <h5>Saved to your calendar</h5>
              <p>We'll email you a Zoom link 24 hours before the session.</p>
            </div>
            <button className="dl-btn" style={{ position: "absolute", bottom: 14, left: 14 }} onClick={()=>replay("modal")}>▶ Open</button>
          </div>
        </div>
        <CodeBlock>
{`.modal {
  transform: translate(-50%, -45%) scale(0.95);
  opacity: 0;
  transition:
    transform 320ms var(--ease-emphasis),
    opacity 240ms var(--ease-standard);
}
.open .modal {
  transform: translate(-50%, -50%) scale(1);
  opacity: 1;
}
/* Exit: swap to var(--ease-exit), 200ms */`}
        </CodeBlock>
      </div>

      <H2>List stagger reveal</H2>
      <div className="grid grid-2">
        <div className="demo-stage">
          <div className={"stagger-row " + (keys.stagger ? "run" : "")} key={keys.stagger || 0}>
            {[0,1,2,3,4,5,6,7].map(i => (
              <div className="dot" key={i} style={{ animationDelay: (i*80)+"ms" }} />
            ))}
          </div>
          <button className="dl-btn" style={{ marginTop: 14 }} onClick={()=>replay("stagger")}>▶ Replay</button>
        </div>
        <CodeBlock>
{`.row .item {
  opacity: 0;
  transform: translateY(12px);
}
.row.run .item {
  animation: itemIn 480ms var(--ease-emphasis) forwards;
}
/* JS or :nth-child to delay each by 80ms */
.row.run .item:nth-child(2) { animation-delay: 80ms; }
.row.run .item:nth-child(3) { animation-delay: 160ms; }`}
        </CodeBlock>
      </div>

      <H2>Number ticker — KPI / hero metric</H2>
      <div className="grid grid-2">
        <div className="demo-stage" style={{ flexDirection: "column", display: "flex", justifyContent: "center", alignItems: "center" }}>
          <Ticker key={keys.ticker || 0} target={847} suffix="x" />
          <div className="ticker-sub">Faster ATO with RegScale</div>
          <button className="dl-btn" style={{ marginTop: 14 }} onClick={()=>replay("ticker")}>▶ Replay</button>
        </div>
        <CodeBlock>
{`// Animate from 0 → target with ease-emphasis
const animate = (target, dur=900) => {
  const start = performance.now();
  const ease = (t) => 1 - Math.pow(1-t, 3); // approx emphasis
  const step = (now) => {
    const t = Math.min(1, (now - start)/dur);
    setValue(Math.round(target * ease(t)));
    if (t < 1) requestAnimationFrame(step);
  };
  requestAnimationFrame(step);
};`}
        </CodeBlock>
      </div>

      <H2>Logo entrance — reserved for brand moments</H2>
      <div className="grid grid-2">
        <div className="demo-stage">
          <div className={"logo-entrance " + (keys.logo ? "run" : "")} key={keys.logo || 0}>
            <div className="ls-mark" />
            <div className="ls-text">
              {"RegScale".split("").map((ch,i) => (
                <span key={i} style={{ animationDelay: (180 + i*40)+"ms", color: i>=3 ? "var(--rs-indigo)" : "var(--rs-ink)" }}>{ch}</span>
              ))}
            </div>
          </div>
          <button className="dl-btn" style={{ marginTop: 14 }} onClick={()=>replay("logo")}>▶ Replay</button>
        </div>
        <CodeBlock>
{`/* Symbol pops in with rotation, wordmark types up */
.mark { animation: markIn 700ms var(--ease-emphasis) both; }
@keyframes markIn {
  0%   { opacity: 0; transform: scale(0.4) rotate(-12deg); }
  60%  { opacity: 1; transform: scale(1.08) rotate(2deg); }
  100% { transform: scale(1) rotate(0); }
}
.text span { transform: translateY(110%); display: inline-block; }
.run .text span { animation: charIn 600ms var(--ease-emphasis) both; }
@keyframes charIn { to { transform: translateY(0); } }`}
        </CodeBlock>
      </div>

      <H2>Continuous loader — partner marquee</H2>
      <div className="grid grid-2">
        <div className="demo-stage" style={{ alignItems: "stretch", padding: 20 }}>
          <div className="marquee" style={{ flex: 1, alignSelf: "center" }}>
            <div className="track">
              {["FedRAMP","NIST 800-53","CMMC","SOC 2","ISO 27001","HITRUST","PCI DSS","FISMA","FedRAMP","NIST 800-53","CMMC","SOC 2"].map((x,i)=>(
                <div className="item" key={i}>{x}</div>
              ))}
            </div>
          </div>
        </div>
        <CodeBlock>
{`.track {
  display: flex; gap: 56px;
  animation: marquee 22s linear infinite;
}
@keyframes marquee {
  to { transform: translateX(-50%); }
}
/* Duplicate items so the loop is seamless */`}
        </CodeBlock>
      </div>

      <H2>Reduced motion fallback</H2>
      <CodeBlock>
{`@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
  }
  /* Replace translate/scale with opacity-only */
  .hero > * { animation: fadeOnly 200ms ease both; }
  @keyframes fadeOnly { from { opacity: 0; } to { opacity: 1; } }
}`}
      </CodeBlock>
    </div>
  );
}

function Ticker({ target = 100, suffix = "" }) {
  const [v, setV] = useState(0);
  useEffect(() => {
    const start = performance.now();
    const dur = 900;
    const ease = (t) => 1 - Math.pow(1-t, 3);
    let raf;
    const step = (now) => {
      const t = Math.min(1, (now - start)/dur);
      setV(Math.round(target * ease(t)));
      if (t < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [target]);
  return <div className="ticker">{v}{suffix}</div>;
}

Object.assign(window, { MotionPrinciplesPage, MotionTimingPage, MotionDemosPage });
