# SlideCast: AI Slide & Simulation Generation Guide

> **Purpose**: This guide provides the complete specification and prompt instructions for creating interactive, production-ready slide decks and decoupled standalone simulations that run inside the **SlideCast Sandbox Platform**.
> 
> Pass this document to any AI model (Claude, ChatGPT, Gemini) to generate slide decks and physics simulations that work on the first try.

---

## 0. START HERE — The Slide Maker's Feature Catalog (Plain-English Menu)

> **For new slide makers.** This section answers three questions in plain language:
> 1. What can a slide **do** inside SlideCast?
> 2. What is **not possible yet**?
> 3. How do I **instruct an AI** to build slides using these features?

![The Work & Potential trial deck running inside the SlideCast slider](guide_assets/01_deck_in_slider.png)
*Example: `Work_and_Potential/lecture_deck.html` presented inside `index.html`.*

### 0.1 The One-Minute Model

- **The Slider** (`index.html`) = the venue. It owns screen fitting, arrow-key navigation, pen / highlighter / laser, navigator drawer (<kbd>G</kbd>), frosted whiteboard sheet (<kbd>O</kbd>), and media sound management. It never changes for a lecture.
- **The Slide deck** (`Work_and_Potential/lecture_deck.html`) = your content. You have 100% freedom over looks and behavior.
- **The handshake**: the slider reacts to a fixed vocabulary of classes and `data-*` markers. Write a marker → get its behavior. Anything outside the vocabulary is simply ignored by the slider (which is perfectly fine for pure design and animation).

### 0.2 The Full Menu — Available Today

**A. Freedom zone (no markers needed — the slider stays out of your way):**
HTML/CSS layouts, Tailwind styling, custom fonts, hover effects, CSS keyframes, SVG, Canvas, **animation libraries (GSAP, Motion, Anime.js)**, Three.js 3D, KaTeX/MathJax formulas, **Mermaid diagrams, Chart.js graphs**, and your own buttons running their own `<script>` functions. All of these are approved and load fine via CDN `<script>` tags.

**B. Slider-orchestrated features (use these exact markers):**

| # | Feature | Marker to write | What the slider does | Details |
|---|---|---|---|---|
| 1 | **Pages** | `<section class="slide" data-title="...">` | <kbd>←</kbd>/<kbd>→</kbd> moves between slides; the title shows in the dock and navigator | §3 |
| 2 | **Screen shape** | `data-aspect="16:9"` / `"4:3"` / `"9:16"` on slide 1 | Sets the stage shape at load | §3 |
| 3 | **Entrance animations** | `anim-fade-up`, `anim-fade-down`, `anim-slide-left`, `anim-slide-right`, `anim-pop-in`, `anim-card-in` + `delay-50 … delay-700` | Elements animate in when the slide appears | §3.3 |
| 4 | **Click reveals (steps)** | `class="step"` (or `class="fragment"`, or just `data-step`) | <kbd>→</kbd> reveals one per press before leaving the slide; <kbd>←</kbd> reverses | §5 |
| 5 | **Grouped reveals** | `data-step="2"` | All elements with the same number reveal together | §5 |
| 6 | **Reveal styles** | `class="step fade"` / `zoom` / `slide-left` / `slide-right` / `highlight` | Different entrance feel per step | §5 |
| 7 | **Run code on reveal** | `data-step-action="fn()"` + optional `data-step-reverse="undo()"` | Runs your JS function when the step shows / hides | §5 |
| 8 | **Deep-dive sub-slides** | `<div class="subslide" id="sub-x" data-title="...">` + `openSubslide('sub-x')` / `closeSubslide()` | Opens an inner page with its own steps and its own ink layer | §7 |
| 9 | **Auto-play media** | `data-autoplay` on `<video>` / `<audio>` | Plays when revealed or entered; auto pause + mute when hidden | §5.D |
| 10 | **Images anywhere** | `src="images/x.png"` (or bare filename, or `assets/…`) | Auto-resolved from the deck's own folder | §3.4 |
| 11 | **Your own buttons & scripts** | `<script> function fn(){} </script>` + `onclick="fn()"` | Slider hoists `fn` so the button works (reserved names protected) | §3.5 |
| 12 | **Speaker notes** | `<aside class="notes">…</aside>` | Hidden on stage; broadcast to the synced second window | §0.4 |
| 13 | **Jump to any slide** | `onclick="goToSlide(4)"` | Direct jump from any button or table-of-contents | §8 |
| 14 | **Simulation modal** | `openSimulation('modalId')` + `<iframe data-src="simulations/x.html">` | Lazy-loads the simulation; resets fresh on close | §4 |
| 15 | **Standalone simulations** | `simulations/<name>.html` | Double-clickable web apps, reusable in homework and labs | §9 |
| 16 | **Inline quiz cards** | Solve & Reveal / ConcepTest patterns | Question with pen working space, or clickable instant feedback | §6 |
| 17 | **Standalone quizzes** | `quizzes/<name>.html` opened via modal | Multi-question assessments with scoring | §6, §9 |
| 18 | **Complex Canvas & Audio** | `(function(){ ... })()` + `MutationObserver` | Scoped loops, click-to-play audio, auto-pause on slide change | §3.9 |

### 0.3 What Is NOT Available Yet (Don't Ask a Slide to Do These)

| Not available (yet) | Why / what to do instead |
|---|---|
| Recording voice, webcam, or drawing telemetry | Roadmap Phase 1 — see `INTERACTIVE_CLASSROOM_PLAN.md` |
| Presenter console window | Notes are broadcast already, but no console UI file exists yet |
| 3D avatar teacher | Roadmap Phase 3 |
| One-click video export / PDF handouts | Roadmap Phase 5 |
| Built-in quiz scoring engine | Write your own scoring inside a standalone `quizzes/*.html` file |
| New keyboard shortcuts for your slide | Hotkeys belong to the slider — this is a **Type B** change |
| Changing the slider's buttons or chrome from a slide | Same reason — **Type B** |

> If you truly need something from this list: it is a **Type B (slider-orchestrated) feature**. The slider must be updated first and documented — see `AGENTS.md` §1 for the exact process.

### 0.4 How to Use This Guide to Instruct an AI

1. **Collect assets**: put your images into `Work_and_Potential/images/` (any filenames).
2. **Pick features** from the §0.2 menu (e.g. "3 steps + one subslide + autoplay video").
3. **Prompt the AI**: give it the §11 master prompt, then your request, naming the features and images.
4. **Paste the result** as a new `<section class="slide">` inside `Work_and_Potential/lecture_deck.html`. One slide = one section.
5. **Verify**: run the §12 checklist, then open `index.html` and test: <kbd>→</kbd> steps, <kbd>←</kbd> reverse, <kbd>G</kbd> navigator, <kbd>O</kbd> whiteboard.

**Animation policy:** if you share only an image (or just a topic) with no animation instructions, the AI chooses the most suitable, good-looking animations automatically — built-in `anim-*` entrances first (§3.3), then GSAP/Motion/Anime.js for special choreography (§3.6). No need to specify animations unless you want something particular.

Example request to paste after the §11 master prompt:

```text
Add ONE new slide to Work_and_Potential/lecture_deck.html.
Topic: The Work-Energy Theorem.
Design: match the existing Montserrat + #F5B718 house style, 1333x750 virtual size.
Features: 3 .step reveals, one data-step-action animation, one .subslide deep dive (id="sub-wet").
Images: images/wet_diagram.png placed on the right side.
Follow AI_SLIDE_AND_SIMULATION_GUIDE.md sections 3, 5, 7 and the section 12 checklist.
```

Speaker-notes contract (hidden on stage, sent to the synced window):

```html
<aside class="notes">
  Ask the class: "If the boulder does not move, was any work done?"
</aside>
```

### 0.5 The In-Slider Docs Panel (Press <kbd>D</kbd>)

The slider itself carries this menu: click **Docs** in the top bar (or press <kbd>D</kbd>) to open a plain-English panel listing every available slide feature, the free platform tools (<kbd>P</kbd> pen, <kbd>G</kbd> navigator, <kbd>O</kbd> whiteboard…), what is not available yet, and how to use this guide with an AI. It is the fastest way for a new slide maker to see the full menu without opening any file.

> [!IMPORTANT]
> **Keep the panel in sync.** Whenever a platform feature is added or changed, update the Docs panel content inside `index.html` (`#docsModal`) at the same time as this guide and `README.md` — see `AGENTS.md` §1, item 5.

---

## 1. The SlideCast Paradigm: An Open Runtime & Authoring Contract

SlideCast is an **Open Presentation Runtime & Educational Framework** (analogous to what iOS or Android is for mobile apps, or what React is for user interfaces).

Instead of forcing creators into rigid binary files (`.pptx`, `.key`) or restrictive markdown templates, SlideCast divides presentations into two distinct layers:

### The Division of Responsibilities

```mermaid
flowchart TD
    subgraph Content["Authoring Layer (100% Creative Freedom)"]
        A1["Any Web Layout: Tailwind CSS, Flexbox, Grids"]
        A2["Rich Graphics: HTML5 Canvas, SVG, 3D WebGL / Three.js"]
        A3["Mathematical Typesetting: KaTeX & MathJax"]
        A4["Decoupled Interactive Simulations & Demos"]
    end

    subgraph Contract["The Semantic Framework Contract"]
        C1["&lt;section class='slide'&gt;"]
        C2[".step / [data-step] (Incremental Builds)"]
        C3[".subslide (Branching Deep Dives)"]
        C4["data-autoplay (Sound-Safe Media)"]
        C5["750px Virtual Coordinate Height"]
    end

    subgraph Runtime["SlideCast Sandbox Platform (The Infrastructure)"]
        R1["Dynamic 4K Vector Scaler (Zero Distortion)"]
        R2["Hardware-Accelerated Vector Inking & Laser Trails"]
        R3["Slide Navigator with Live Miniature Visual Previews"]
        R4["Slate Blackboard & Frosted Whiteboard Overlay Sheet (O / Tab)"]
        R5["Sound Leak Silencer & Cross-Window Broadcaster"]
    end

    Content --> Contract
    Contract --> Runtime
```

1. **The Sandbox Runtime (`index.html`)**:
   Provides the entire presentation infrastructure for free:
   - Dynamic letterboxing and uncapped 4K vector scaling across any monitor, projector, iPad, or mobile screen.
   - Smooth vector pen, procedural chalk (<kbd>C</kbd>), uniform highlighter (<kbd>H</kbd>), touch eraser (<kbd>E</kbd>), clear ink (<kbd>X</kbd>), and transient vanishing laser pointer (<kbd>L</kbd>).
   - Slate Blackboard & Frosted Whiteboard explanation overlay sheet (<kbd>O</kbd> / <kbd>Tab</kbd>) for spontaneous chalkboard math and derivations.
   - Slide Navigator drawer (<kbd>G</kbd>) rendering live, scaled miniature DOM previews of each slide.
   - Audio/video lifecycle management (auto-pausing media on slide leave to eliminate rogue audio leaks).
   - Branching sub-slide deep dives with independent, non-bleeding ink layers.

2. **The Authoring Layer (100% Creative Freedom)**:
   Content authors and AI models have complete creative liberty. You can code using any modern web technology:
   - Custom fonts, glassmorphism cards, CSS micro-animations, or dark/light themes.
   - Interactive buttons, live calculators, and SVG diagrams.
   - 2D Canvas physics engines or full 3D Three.js WebGL scenes.

3. **The Semantic Contract (The Rules)**:
   To enable the sandbox to orchestrate your slides without getting in your way, you follow a lightweight semantic standard:
   - Wrap slides in `<section class="slide">`.
   - Design for a 750px virtual height (`1333×750` for 16:9, `1000×750` for 4:3, `422×750` for 9:16).
   - Use `class="step"` for sequential reveals.
   - Use `class="subslide"` for non-linear drilldowns.
   - Keep heavy simulations decoupled as standalone assets.

### Why SlideCast Beats Traditional Presentation Tools

| Capability | PowerPoint / Keynote | Reveal.js / Marp | SlideCast Platform |
| :--- | :--- | :--- | :--- |
| **Format** | Proprietary binary files (`.pptx`, `.key`) | Markdown / HTML | **Pure Web Standard** (HTML5, CSS3, JS) |
| **AI Compatibility** | Poor (cannot generate rich interactive simulations) | Basic text & static images | **Native AI Authoring** (Decoupled simulations & code) |
| **Stylus & Inking** | Clunky, fixed colors, no glass whiteboard | None (external annotation plugins required) | **PowerPoint-Grade Vector Inking, Laser & Glass Overlay** |
| **Navigation** | Strict linear sequence | Rigid 2D grid | **Linear + Branching Drilldowns + Live Previews (<kbd>G</kbd>)** |
| **Responsive Scaling** | Fixed aspect ratio with letterbox bars | Reflows text, breaking alignment | **Uncapped Vector Scaling (1:1 coordinate fidelity)** |
| **Sound Management** | Manual audio triggers | No automatic audio cleanup | **Automatic Audio Silencer** (No ghost audio leaks) |

---

## 1.1 The 3 AI Slide Authoring Methods & Benchmark (Speed vs. Tokens vs. Pixel-Perfection)

When creating presentation slides with AI (whether converting a reference image, textbook scan, or generating from a text outline), there is a fundamental engineering trade-off between **generation speed**, **token cost**, and **visual fidelity**.

Through extensive empirical testing across real physics decks, we benchmarked the **three distinct AI generation pipelines**:

```
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                   THE 3 AI SLIDE GENERATION PIPELINES                                  │
│                                                                                                        │
│  METHOD 1: DECLARATIVE SCHEMA           METHOD 2: ONE-SHOT DIRECT CODE     METHOD 3: AGENTIC CLOSED-LOOP│
│  (slide.json ➔ Compiler)                (Prompt ➔ Complete HTML)           (Render ➔ Inspect ➔ Fix QA) │
│                                                                                                        │
│  ┌──────────────────────────────┐       ┌──────────────────────────────┐   ┌──────────────────────────┐│
│  │ 📄 Vision AI / Prompt        │       │ ⚡ Single AI Prompt          │   │ 👁️ Vision AI Measurement ││
│  │        │                     │       │        │                     │   │        │                 ││
│  │        ▼                     │       │        ▼                     │   │        ▼                 ││
│  │ 📦 structured slide.json     │       │ 🌐 Semantic lecture_deck.html│   │ 🛠️ Code Generation       ││
│  │        │                     │       │        │                     │   │        │                 ││
│  │        ▼                     │       │        ▼                     │   │        ▼                 ││
│  │ ⚙️ Deterministic Compiler    │       │ 🚀 Instant WebSlider Play    │   │ 📸 Live Screenshot Render││
│  │        │                     │       │   (Blind: no self-correction)│   │        │                 ││
│  │        ▼                     │       └──────────────────────────────┘   │        ▼                 ││
│  │ 🌐 lecture_deck.html         │                                          │ 🔍 Vision QA Loop (Fixes)││
│  └──────────────────────────────┘                                          │        │                 ││
│                                                                            │        ▼                 ││
│                                                                            │ 💎 100% Pixel-Perfect    ││
│                                                                            │   (~10m, heavy tokens)   ││
│                                                                            └──────────────────────────┘│
└────────────────────────────────────────────────────────────────────────────────────────────────────────┘
```

---

### Empirical Benchmark: Real-World Test Results

| Benchmark Metric | Method 1: Declarative Schema (`slide.json`) | Method 2: One-Shot Direct Code | Method 3: Agentic Closed-Loop QA |
| :--- | :---: | :---: | :---: |
| **Real Test Deck** | *Non-Contact Forces (4 Cards)* | *WebSlide Prototype* | *Work & Energy (Sisyphus)* |
| **Generation Time** | **~45 seconds ⚡** (14× faster than QA) | **~15–20 seconds 🚀** (Fastest) | **10 minutes 50 seconds ⏳** (Longest) |
| **Token Cost** | **~15,000 tokens** (97% savings) | **~8,000 tokens** (Lowest cost) | **~500,000 tokens** (Heavy token cost) |
| **Tool Invocations** | **3 tool executions** | **1 single prompt** | **65 tool executions** (42 terminal, 20 vision) |
| **Visual Accuracy** | **80% initially** ➔ **98%** (with alpha cutouts) | **80–85%** (Blind estimation) | **100% Pixel-Perfect Match** |
| **Self-Correction** | ❌ None (Deterministic compiler) | ❌ None (Single-pass blind) | ✅ **Full Vision QA** (Auto-fixes overlaps) |
| **Best Use Case** | Whole curriculums, batch decks, non-coders | Fast lecture outlines, creative layouts | Keynotes, investor decks, textbook cloning |

---

### In-Depth Breakdown of the 3 Methods

#### Method 1: Declarative Schema Pipeline (`slide.json` ➔ Compiler)
* **How It Works**:
  1. The LLM or Vision AI outputs a structured JSON schema (`slide.json` or `deck.json`) describing cards, colors, coordinates, formulas, and text blocks.
  2. A deterministic compiler script reads the JSON and renders standard SlideCast `<section class="slide">` HTML.
* **Why It’s Powerful**:
  - **Decoupled Design**: Teachers and non-programmers can fix a typo, alter a formula, or swap a color in `slide.json` in 5 seconds without touching HTML or CSS.
  - **Massive Batch Scale**: An AI can generate a 25-slide lecture module in a single JSON array with minimal token overhead (~15k tokens).
* **Trade-Off**: Without visual feedback, single-pass estimations may have minor text-wrapping imperfections unless corrected in JSON.

---

#### Method 2: One-Shot Direct Code Generation (Fastest Delivery)
* **How It Works**:
  - The AI directly authors the complete semantic HTML file (`lecture_deck.html`) in a single response using Tailwind CSS, KaTeX delimiters, and `.step` classes.
* **Why It’s Powerful**:
  - **Zero Build Step**: No compiler scripts, no JSON schemas — save the `.html` file and drag it into WebSlider.
  - **Creative Freedom**: Allows custom glassmorphism gradients, bespoke SVG layouts, and creative card designs.
  - **Ultra-Fast**: Generates in **~15 seconds** with ~8k tokens.
* **Trade-Off**: "Blind execution" — the AI cannot see its own rendered output, so subtle text overflows or badge misalignments require human inspection or quick prompt adjustment.

---

#### Method 3: Agentic Closed-Loop Visual QA Loop (Pixel-Perfect Cloning)
* **How It Works**:
  1. **Pixel Measurement**: Vision AI measures exact reference bounds, aspect ratios, and color palettes.
  2. **Asset Engineering**: Scripts crop artwork, digitally remove text artifacts, and produce transparent antialiased masks.
  3. **Compile & Snap**: Slide is rendered in the browser/QuickLook, and a high-resolution screenshot is captured (`screencapture`).
  4. **Vision QA Loop**: Vision AI inspects the screenshot, catches collisions (e.g. subtitle touching a card border), refactors the HTML/CSS, and re-renders until a **flawless 100% match** is verified.
* **Why It’s Powerful**:
  - Delivers **100% pixel-perfect clones** of complex textbook figures, Keynote layouts, or hand-drawn sketches.
* **Trade-Off**: Demands **~10 minutes** of automated verification and **~500,000 tokens** across dozens of tool calls.

---

### Two Critical Empirical Discoveries

#### 1. The "80% vs. 98% Asset Sheet Rule"
During our experiments on the *Non-Contact Forces* slide, Method 1 initially produced only an **~80% visual match**:
* **The Culprit**: Raw rectangular crops taken directly from screenshot bounding boxes had solid background colors that clashed with rounded pastel cards, leaving ugly square seams.
* **The Breakthrough**: By switching to a **transparent PNG asset sheet (sprites with alpha channels)**, the exact same declarative pipeline jumped from **80% to 98% accuracy** in 40 seconds!

> [!TIP]
> **Always use transparent PNG cutouts (`rgba`)** for card icons and hero illustrations. This single decision eliminates 90% of visual clipping and makes slides look professionally authored.

#### 2. Why We Moved from PowerPoint to WebSlider (Pathway 3)
In our early experiments, we attempted to generate `.pptx` PowerPoint files. We discovered:
* PowerPoint files require complex XML hacks (`p:morph`) for smooth transitions.
* `python-pptx` has zero native support for smooth KaTeX math equations or 60fps physics animations.
* PowerPoint locks presenters into modal pen tools that block slide navigation.

By executing **Method 2 and Method 1 in WebSlider**, you get the best of both worlds: **instant ~15-second generation** combined with **live vector inking, vanishing laser pointer, KaTeX math, and pausable physics simulations** that PowerPoint can never deliver.

---

## 2. Core Architectural Philosophy: Decoupled Simulation Assets

Simulations must **never be hardcoded directly inside the slide's HTML**. 

Instead, simulations are treated as **standalone external assets** (just like images or videos):

```
my-physics-lecture/
├── lecture_deck.html            <-- Main presentation slide deck
├── images/                      <-- Image assets (diagrams, hero photos)
│   ├── gravity_diagram.png
│   └── energy_hero.png
├── simulations/                 <-- Standalone interactive simulations
│   ├── inclined_plane_sim.html  <-- 100% standalone simulation
│   └── pendulum_energy_sim.html <-- 100% standalone simulation
└── quizzes/                     <-- Standalone interactive quizzes & assessments
    ├── kinetic_concepTest.html  <-- Interactive multiple-choice / polling module
    └── momentum_problem_set.html
```

### Why Standalone Simulations?
1. **Reusability**: You can use the exact same simulation separately in online homework, web labs, quizzes, or student self-study without touching the presentation.
2. **Zero Code Clutter**: The slide deck remains clean, readable, and lightweight without 500 lines of physics/canvas math cluttering the presentation markup.
3. **No Namespace Collisions**: The simulation runs safely inside its own sandboxed context (`iframe` / modular container), preventing variable or styling conflicts with the presentation platform.

---

## 3. Slide Deck Specification & Golden Rules

When generating `lecture_deck.html`, adhere strictly to these golden platform rules:

### 1. Slide Container Structure: Use `<section class="slide">`

Each individual slide must be wrapped in a `<section class="slide">` (or `<div class="slide">`):

```html
<!-- Slide 1 -->
<section class="slide active" data-title="Work & Kinetic Energy" data-aspect="16:9">
  <!-- Slide 1 Content Here -->
</section>

<!-- Slide 2 -->
<section class="slide" data-title="Non-Contact Forces">
  <!-- Slide 2 Content Here -->
</section>
```

- **`class="slide"`**: Identifies each slide to the navigation and inking engine.
- **`class="active"`**: Put on the first slide to display it initially.
- **`data-title="..."`**: Sets the title shown on the bottom dock indicator.
- **`data-aspect="16:9"`** *(optional, on slide 1)*: Tells SlideCast whether to start in `16:9`, `4:3`, or `9:16`.

---

### 2. Base Virtual Size: 750px Height

SlideCast uses a standard vector resolution with a **750px height**:
- **16:9 (Widescreen)**: `1333px × 750px`
- **4:3 (Standard)**: `1000px × 750px`
- **9:16 (Vertical)**: `422px × 750px`

> [!IMPORTANT]
> **Do NOT add outer wrappers like `#stage`, `.deck-viewport`, or your own `resizeStage()` function!**  
> The platform automatically provides the stage, the letterboxing, and the dynamic uncapped 4K scaler. In your slide code, just write the `<section class="slide">` containers!

---

### 3. Built-In Micro-Animations (Triggered on Slide Change)

SlideCast has built-in CSS entrance animations that fire automatically when you switch to that slide:

| Animation Class | What It Does |
| :--- | :--- |
| **`anim-fade-up`** | Fades in while floating upward smoothly |
| **`anim-fade-down`** | Fades in while sliding downward |
| **`anim-slide-left`** | Glides in from the left |
| **`anim-slide-right`** | Glides in from the right |
| **`anim-pop-in`** | Bouncy, energetic entrance (great for badges & formulas) |
| **`anim-card-in`** | Smooth card lift with scale |

**Staggered Delays:** Add `.delay-100`, `.delay-200`, `.delay-300`, etc., to make elements appear one after another:
```html
<h1 class="text-4xl font-black anim-fade-down">Newton's Second Law</h1>
<p class="anim-fade-up delay-100">Force equals mass times acceleration</p>
<div class="formula-card anim-pop-in delay-200">F = m · a</div>
```

---

### 4. Image Paths: Flexible & Auto-Resolved

You can reference images simply by filename or relative path:
- `src="clean_gravity.png"`
- `src="./images/hero.png"`
- `src="assets/diagram.png"`

SlideCast's **Universal Asset Resolver** automatically checks the active deck's own folder, the common subfolders (`images/`, `assets/`), and in-memory dropped files. Example: the reference chapter in `Work_and_Potential/` stores its artwork in `Work_and_Potential/images/`.

---

### 5. Interactive Buttons & Scripts (Simulations / Demos)

You can include normal `<script>` tags for interactive physics, buttons, or canvas simulations:
```html
<button onclick="runSimulation()" class="bg-[#F5B718] px-4 py-2 rounded-xl">
  Push Object
</button>

<script>
  function runSimulation() {
    // SlideCast automatically hoists this function to window
    // so onclick="runSimulation()" works instantly!
  }
</script>
```

> [!CAUTION]
> **Reserved Names to Avoid**: Do not name your custom functions `resizeStage`, `setAspectRatio`, `setStageAlignment`, `goToSlide`, or `setTool`, as these are the platform's internal controls.

---

### 6. Recommended Animation Tools & Easing Curves

For professional, presentation-grade motion, use these recommended tools and curves.

> **AI authors**: unless the user requests something specific, automatically select the best-fitting tool(s) from this section for every slide. Every slide should have tasteful motion — never leave a slide static, and never overdo it.

#### A. GSAP (GreenSock) for Keynote-Style Smooth Diagram & Line Draws
To animate vector arrows, force lines, trajectory paths, and multi-step derivations:
- **CDN**: `<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>`
- **Why**: Replaces robotic pop-ins with smooth Apple Keynote-style **Line Draw** animations.
- **Code Pattern**:
  ```html
  <svg class="w-64 h-32" viewBox="0 0 200 100">
    <path id="trajectoryArc" d="M 10 90 Q 100 10 190 90" fill="none" stroke="#F5B718" stroke-width="4" stroke-linecap="round" />
  </svg>

  <script>
    // Smooth line drawing on slide load
    function animateDiagram() {
      const path = document.querySelector('#trajectoryArc');
      if (!path) return;
      const length = path.getTotalLength();
      path.style.strokeDasharray = length;
      path.style.strokeDashoffset = length;
      gsap.to(path, { strokeDashoffset: 0, duration: 1.4, ease: "power2.out" });
    }
  </script>
  ```

#### B. Motion (motion.dev) for Spring Physics, Stagger & Gestures

For natural, modern motion (springs, hover/press/drag gestures, staggered cascades):
- **CDN**: `<script src="https://cdn.jsdelivr.net/npm/motion@latest/dist/motion.js"></script>`
- **Why**: Free (MIT), tiny core, real spring physics, and native gesture support. Ideal for lively formula cards, staggered lists, and draggable diagrams.
- **When to use which**: GSAP for complex timelines and SVG line-draws; Motion for springs, stagger, and interactive gestures.
- **Code Pattern**:
  ```html
  <div class="step" data-step-action="springIn('#formulaCard')">
    <div id="formulaCard" class="p-6 rounded-2xl bg-white shadow-lg">E = mc²</div>
  </div>

  <script>
    function springIn(selector) {
      Motion.animate(selector, { scale: [0.6, 1], opacity: [0, 1] }, { type: 'spring', stiffness: 220, damping: 18 });
    }
    function staggerList() {
      Motion.animate('.list-item', { y: [24, 0], opacity: [0, 1] }, { delay: Motion.stagger(0.08) });
    }
  </script>
  ```
- **Animating on slide entry**: trigger via `data-step-action`, `onclick`, or watch for the `.slide.active` class with a `MutationObserver` in your slide script. Do **not** use `Motion.inView()` for slide-entry — hidden slides are still technically "in view".

#### C. Anime.js for SVG Morphing, Motion Paths & Line Draws

For an all-in-one engine with the strongest SVG toolset (shape morphing, motion paths, line drawing) alongside timeline and stagger:
- **CDN**: `<script src="https://cdn.jsdelivr.net/npm/animejs@4/lib/anime.iife.min.js"></script>` (global `anime`, free, MIT)
- **Why**: Morph one diagram into another, draw force arrows/vectors on cue, or animate an object along an orbit path — ideal for physics figures.
- **Code Pattern**:
  ```html
  <div class="step" data-step-action="drawForceArrow()">
    <svg viewBox="0 0 200 100" class="w-64 h-32">
      <path id="forceArrow" d="M 10 90 Q 100 10 190 90" fill="none" stroke="#F5B718" stroke-width="4" stroke-linecap="round"/>
    </svg>
  </div>

  <script>
    function drawForceArrow() {
      anime.animate(anime.createDrawable('#forceArrow'), { draw: '0 1', duration: 1200, ease: 'inOutQuad' });
    }
    function staggerCards() {
      anime.animate('.card', { y: [24, 0], opacity: [0, 1], delay: anime.stagger(80), ease: 'outExpo' });
    }
    function morphDiagram() {
      anime.animate('#shapeA', { d: anime.morphTo('#shapeB'), duration: 800, ease: 'inOutQuad' });
    }
  </script>
  ```
- **Pick the right tool**: GSAP = complex timelines & precise control; Motion = springs, gestures, drag; **Anime.js = SVG morphing, motion paths, quick all-in-one choreography**.

#### D. Apple's Signature Smooth Easing Curve: `cubic-bezier(0.16, 1, 0.3, 1)`
For all custom UI cards, modals, sliders, and transitions, avoid generic `ease` or `linear`. Use Apple's signature easing curve:
```css
.custom-card {
  transition: all 0.45s cubic-bezier(0.16, 1, 0.3, 1);
}
```
- **Feel**: Fast, energetic initial burst with an ultra-smooth deceleration curve that glides naturally into place.

#### E. `perfect-freehand` for Natural Stylus & Whiteboard Inking
SlideCast uses `perfect-freehand` internally to turn raw stylus coordinates into smooth, variable-width, pressure-sensitive strokes that taper naturally. When authoring custom whiteboard or drawing mini-apps, use `perfect-freehand` rather than basic canvas line-to.

---

### Minimal Slide Deck Template (Copy & Paste Ready)

Whenever you create a new slide deck, this minimal structure is all you need:

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    /* Custom slide styling here */
  </style>
</head>
<body>

  <!-- Slide 1 -->
  <section class="slide active" data-title="Slide 1 Title" data-aspect="16:9">
    <div class="h-full flex flex-col justify-between">
      <h1 class="text-4xl font-extrabold anim-fade-down">Slide 1 Title</h1>
      <div class="anim-fade-up delay-150">Slide 1 Content</div>
    </div>
  </section>

  <!-- Slide 2 -->
  <section class="slide" data-title="Slide 2 Title">
    <div class="h-full flex flex-col justify-between">
      <h1 class="text-4xl font-extrabold anim-fade-down">Slide 2 Title</h1>
      <div class="anim-fade-up delay-150">Slide 2 Content</div>
    </div>
  </section>

</body>
</html>
```


### 7. Layout Golden Rule A: The Top-Right Brand Logo Safe Zone

The SlideCast platform displays a persistent brand logo watermark in the **top-right corner** of the stage (approx **82px wide × 55px high** at `top: 14px; right: 20px` on a 1333×750 stage).

To prevent visual collisions, slide authors and AI models must leave a clean clearance buffer in the top-right corner:

- **Buffer Size**: Reserve at least **120px wide × 80px high** in the top-right corner as completely blank whitespace.
- **No Text or Controls**: Never place headers, category badges, "LEARN/PRACTICE" motto columns, formulas, or interactive buttons in this area.
- **Header Insets**: Main headers and slide category bars should start from the left or leave generous right padding (`pr-32` or similar) so they never touch or collide with the logo.
- **Settings Configurable**: Users can upload their custom SVG/PNG logo, toggle placement (Top-Right default, or Top-Left), or hide the logo entirely via **Settings (<kbd>S</kbd>)**.

---

### 8. Layout Golden Rule B: The Bottom-Right Presenter Webcam Safe Zone

When recording video lectures or streaming live, the instructor's webcam video feed (typically a square or 4:3 picture-in-picture box, approx **280px × 240px** on a 1333×750 stage) is positioned in the **bottom-right corner** of the slide.

To ensure that neither the platform brand logo nor the instructor's camera ever obscures instructional material, adhere strictly to this stage layout map:

```
┌───────────────────────────────────────────────────┬────────────────────┐
│ 16:9 Widescreen Virtual Stage (1333 × 750 px)     │ 🏷️ BRAND LOGO ZONE │
│                                                   │  (approx 120×80 px)│
│                                                   │  • KEEP 100% BLANK │
│   PRIMARY CONTENT & INSTRUCTIONAL ZONE            └────────────────────┘
│   • Topic title, category badges, learning objectives                  │
│   • Core cards, KaTeX derivations, definitions, and diagrams           │
│   • Multi-step reveals (.step), buttons, and interactive widgets       │
│   • Inking workspace for teacher writing (Hotkey: P)                   │
│                                                                        │
│                                           ┌────────────────────────────┐
│                                           │ 📹 PRESENTER WEBCAM        │
│                                           │    SAFE ZONE               │
│                                           │ (approx 280 × 240 px)      │
│                                           │                            │
│                                           │ • KEEP BLANK / CLEAN       │
│                                           │ • OR NON-ESSENTIAL ART     │
│                                           │ • NO FORMULAS / TEXT       │
│                                           └────────────────────────────┘
└────────────────────────────────────────────────────────────────────────┘
```

#### Guidelines for the Bottom-Right Zone:
1. **Keep It Clean or Blank**: Leave generous whitespace or a subtle background tint in the bottom-right corner.
2. **Non-Essential Decorative Art Only**: If this corner is not completely blank, it may only contain ambient, non-essential background design (such as a subtle gradient, abstract curve, or low-contrast watermark).
3. **Zero Critical Subject Matter**: **Never** place primary formulas ($E = mc^2$), bullet points, key vocabulary, practice question text, or interactive launcher buttons in the bottom-right quadrant.
4. **The "Cover-Up Test"**: If you place a solid square over the bottom-right corner of the slide, the entire lesson, all text, and all interactive controls must remain **100% visible and understandable**.

---

### 9. Complex Canvas Animations & Web Audio Synthesizers (The 4 Golden Rules)

When authoring slides with custom `<canvas>` animation loops (such as particle engines, custom physics choreographies, or wave visualizers) or Web Audio API synthesizers (ambient music, harmonic tones, SFX):

#### Rule 1: Scope Isolation (Always Wrap in an IIFE)
In SlideCast, all slides in a deck live in a single unified HTML document. If you declare top-level variables (e.g. `const cv = document.getElementById(...)`, `let ctx = ...`, `let isPlaying = false`), another slide declaring similar variables will trigger an immediate, fatal compile-time collision:
```text
Uncaught SyntaxError: Identifier 'cv' has already been declared
```
This error prevents the slide's JavaScript from executing entirely.

- **The Golden Pattern**: Always encapsulate your slide script inside an Immediately Invoked Function Expression (IIFE):
```html
<script>
(function() {
  const cv = document.getElementById('myCanvas');
  if (!cv) return;
  const ctx = cv.getContext('2d');
  let isPlaying = false;

  function togglePlay() {
    isPlaying = !isPlaying;
    // ...
  }

  // Bind listeners cleanly inside the local scope
  const btn = document.getElementById('myPlayBtn');
  if (btn) btn.addEventListener('click', togglePlay);

  // Expose to window ONLY if called via inline onclick="..."
  window.myUniquePlay = togglePlay;
})();
</script>
```

#### Rule 2: Web Audio Autoplay Policy & Explicit "Click-to-Play" Gesture
Modern web browsers (Chrome, Safari, Edge, Firefox) enforce strict autoplay restrictions that suspend `AudioContext` until initiated by a direct user interaction (such as a click or tap).
- Attempting to start audio automatically on slide load will cause the browser to block sound and log an `Autoplay blocked` warning.
- **The Golden Pattern**: Always design audio-enabled slides with an explicit **Click-to-Play** control — such as an overlay badge `[▶ Click to Play]` or a prominent Play button. When clicked, call `audioCtx.resume()` inside the click handler to cleanly unlock sound before initiating synthesizers or audio oscillators.

#### Rule 3: Slide Lifecycle & Auto-Pause via `MutationObserver`
When a presenter advances to the next slide (<kbd>→</kbd>) or steps backward (<kbd>←</kbd>), running canvas loops (`requestAnimationFrame`) and Web Audio nodes must not continue running in the background. Running invisibly wastes CPU/GPU cycles, drains battery, and results in confusing audio bleed across slides.
- **The Golden Pattern**: Attach a `MutationObserver` to the slide element to detect when it loses the `.active` class:
```javascript
const slideEl = cv.closest('.slide');
if (slideEl) {
  const observer = new MutationObserver(() => {
    if (!slideEl.classList.contains('active')) {
      if (isPlaying) {
        pauseAnimation(); // cancelAnimationFrame
        stopAudio();      // disconnect/suspend audio nodes
      }
    }
  });
  observer.observe(slideEl, { attributes: true, attributeFilter: ['class'] });
}
```

#### Rule 4: Lightweight Assets & Storage Quotas (<50KB Slides)
Avoid inlining huge base64-encoded SVG or PNG files (e.g. 1.5MB+ data URLs) inside `<script>` or HTML tags.
- Huge base64 data URLs inflate file size from ~30KB to several megabytes, degrading DOM parsing performance.
- When slide decks are uploaded into SlideCast or cached in browser `localStorage`, multi-megabyte payloads quickly exceed browser storage quotas (typically 5MB–10MB per origin), causing `QuotaExceededError`.
- **The Golden Pattern**: Keep slides lightweight (target <50KB). Store images or complex SVG graphics in the deck's `images/` or `assets/` subfolder and reference them by path (`src="images/logo.svg"`). SlideCast's Universal Asset Resolver automatically locates and caches them.

#### Rule 5: Zero Global CSS Leakage (Never Style Bare `.slide` or `body`)
Never place global layout rules like `.slide { background: ...; display: flex; align-items: center; justify-content: center; }`, `body { ... }`, or `html { ... }` in a slide's `<style>` block.
- **Why**: All slides in a deck share a single DOM document. If an intro or animated slide injects a generic `.slide` selector with `display: flex` or a background color, it infects **every subsequent slide in the presentation**—wiping out their padding, centering their content into a tight column, and overriding their theme colors.
- **The Golden Pattern**: Apply dark backgrounds or flex alignments **strictly as inline styles** on that slide's specific `<section>` tag or a unique ID:
```html
<section class="slide active" id="mySpecialSlide" data-title="Promo" style="background:#050505; padding:0; display:flex; align-items:center; justify-content:center;">
  <canvas id="c" width="1280" height="720" style="width:100%; height:100%; object-fit:contain;"></canvas>
</section>
```

---

## 4. How Slides Launch Simulations: The Modal Overlay Pattern

Inside the slide, provide a clean launcher card or button that opens the external simulation in an overlay modal when clicked:

### Reference Slide Implementation Pattern

```html
<section class="slide" data-title="Inclined Plane Experiment">
  <div class="h-full flex flex-col justify-between">
    
    <!-- Header -->
    <div>
      <span class="text-xs font-bold text-[#F5B718] tracking-widest uppercase anim-fade-down">Interactive Physics Lab</span>
      <h1 class="text-4xl font-black text-[#181F26] mt-1 anim-fade-down delay-100">Work Done on an Incline</h1>
      <p class="text-sm text-[#5B6672] mt-2 max-w-xl anim-fade-up delay-150">
        Analyze how changing the slope angle and friction coefficient affects the net work required to elevate a mass.
      </p>
    </div>

    <!-- Simulation Launch Card -->
    <div class="bg-gradient-to-br from-white to-[#F9F9F8] p-6 rounded-2xl border border-black/10 shadow-lg flex items-center justify-between anim-card-in delay-200">
      <div class="flex items-center space-x-4">
        <div class="w-14 h-14 rounded-xl bg-[#F5B718]/15 border border-[#F5B718]/30 flex items-center justify-center text-[#F5B718]">
          <svg class="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        </div>
        <div>
          <h3 class="text-lg font-bold text-[#181F26]">Interactive Incline Sandbox</h3>
          <p class="text-xs text-[#5B6672]">Live physics simulation · Mass, Angle, and Friction controls</p>
        </div>
      </div>

      <!-- Button that triggers the simulation modal -->
      <button onclick="openSimulation('simInclineModal')" class="px-6 py-3 rounded-xl bg-[#F5B718] hover:bg-[#deb412] text-[#12161A] font-bold text-sm transition shadow-md hover:scale-105 flex items-center space-x-2">
        <span>Launch Simulation</span>
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"/></svg>
      </button>
    </div>

    <!-- Key Takeaway Notes -->
    <div class="grid grid-cols-2 gap-4 anim-fade-up delay-300">
      <div class="p-4 rounded-xl bg-white border border-black/5 shadow-sm">
        <div class="text-xs font-bold text-black/50 uppercase">Key Equation</div>
        <div class="text-base font-black text-[#181F26] font-mono mt-1">W = F · d · cos(θ)</div>
      </div>
      <div class="p-4 rounded-xl bg-white border border-black/5 shadow-sm">
        <div class="text-xs font-bold text-black/50 uppercase">Normal Force</div>
        <div class="text-base font-black text-[#181F26] font-mono mt-1">N = m · g · cos(θ)</div>
      </div>
    </div>

    <!-- ================= SIMULATION MODAL (Hidden by default) ================= -->
    <div id="simInclineModal" class="absolute inset-0 z-50 bg-black/75 backdrop-blur-md rounded-2xl hidden flex-col p-4 transition-all">
      <!-- Modal Header -->
      <div class="flex items-center justify-between pb-3 border-b border-white/10 mb-3 text-white">
        <div class="flex items-center space-x-2">
          <span class="w-2.5 h-2.5 rounded-full bg-[#F5B718]"></span>
          <span class="font-bold text-sm">Interactive Simulation: Inclined Plane</span>
        </div>
        <!-- Close Button -->
        <button onclick="closeSimulation('simInclineModal')" class="px-3 py-1.5 rounded-lg bg-white/10 hover:bg-red-500/80 text-white text-xs font-bold transition flex items-center space-x-1">
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
          <span>Close & Return to Slide</span>
        </button>
      </div>

      <!-- Sandboxed External Simulation Frame -->
      <div class="flex-1 w-full h-full rounded-xl overflow-hidden bg-white shadow-2xl">
        <iframe 
          id="simInclineIframe"
          data-src="simulations/inclined_plane_sim.html" 
          class="w-full h-full border-0"
          allow="accelerometer; autoplay; encrypted-media; gyroscope">
        </iframe>
      </div>
    </div>

  </div>
</section>

<script>
  function openSimulation(modalId) {
    const modal = document.getElementById(modalId);
    if (!modal) return;
    const iframe = modal.querySelector('iframe');
    // Lazy-load iframe source on open so simulation resets fresh
    if (iframe && iframe.getAttribute('data-src')) {
      iframe.src = iframe.getAttribute('data-src');
    }
    modal.classList.remove('hidden');
    modal.classList.add('flex');
  }

  function closeSimulation(modalId) {
    const modal = document.getElementById(modalId);
    if (!modal) return;
    const iframe = modal.querySelector('iframe');
    // Stop any running simulation audio or loops on close
    if (iframe) {
      iframe.src = 'about:blank';
    }
    modal.classList.remove('flex');
    modal.classList.add('hidden');
  }
</script>
```

---

## 5. Multi-Step Click Animations (Fragments & Inner Slide Builds)

SlideCast includes a native **Click-to-Build / Fragment Engine**. This lets you reveal bullet points, diagrams, formulas, and trigger custom JavaScript animations sequentially across multiple clicks on the **same slide** before moving to the next slide.

### How It Works
1. **On Slide 1**: Pressing <kbd>→</kbd>, <kbd>Space</kbd>, or clicking the Next button moves to Slide 2.
2. **On Slide 2**: If Slide 2 contains inner `.step` elements, clicking Next **does not** jump to Slide 3. Instead, each click triggers the next step or animation inside Slide 2.
3. **Advancing to Slide 3**: Only after all inner steps on Slide 2 are completed will the next click transition to Slide 3.
4. **Smooth Reverse**: Clicking Previous (<kbd>←</kbd>) undoes the inner steps in reverse order before navigating back to the previous slide. Navigating backwards to a slide automatically shows all its steps in completed state.

---

### Step HTML Syntax & Styling

#### A. Basic Sequential Reveal
Simply add `class="step"` (or `class="fragment"`). Elements will appear one-by-one in DOM order:
```html
<section class="slide" data-title="Newton's Second Law">
  <h1 class="text-4xl font-black anim-fade-down">Force & Acceleration</h1>

  <div class="space-y-4 mt-8">
    <div class="step p-4 rounded-xl bg-white border border-black/10 shadow-sm">
      <span class="font-bold text-[#F5B718]">Step 1:</span> Unbalanced force causes acceleration.
    </div>
    <div class="step p-4 rounded-xl bg-white border border-black/10 shadow-sm">
      <span class="font-bold text-[#F5B718]">Step 2:</span> Acceleration is proportional to net force: $a \propto F_{net}$.
    </div>
    <div class="step p-4 rounded-xl bg-white border border-black/10 shadow-sm">
      <span class="font-bold text-[#F5B718]">Step 3:</span> Final formula: $F = m \cdot a$.
    </div>
  </div>
</section>
```

#### B. Grouped Reveals & Custom Order (`data-step="N"`)
Use `data-step="N"` to control the exact click number. Elements that share the same step number will appear **simultaneously** on that click:
```html
<!-- Click 1: Diagram and its caption appear together -->
<img class="step" data-step="1" src="free_body_diagram.png" alt="FBD">
<p class="step text-xs text-black/60" data-step="1">Figure 1: Free body diagram with normal force and gravity.</p>

<!-- Click 2: Equation appears -->
<div class="step" data-step="2">
  $$\Sigma F_y = N - mg = 0$$
</div>
```

#### C. Built-in Animation Modifiers
Combine `.step` with built-in transition modifier classes:
| Class | Visual Effect |
| :--- | :--- |
| `class="step"` | Smooth upward glide + fade with Apple easing (`cubic-bezier(0.16, 1, 0.3, 1)`) |
| `class="step fade"` | Pure opacity fade with no translation |
| `class="step zoom"` | Scale pop-in from 0.88 to 1.0 |
| `class="step slide-left"` | Enters from right to left |
| `class="step slide-right"` | Enters from left to right |
| `class="step highlight"` | Starts dimmed (32% opacity) and lights up to 100% when clicked |

---

### Triggering Custom JavaScript Animations (`data-step-action`)

You can run arbitrary JavaScript code, GSAP line-draws, or Canvas physics animations on specific clicks by adding `data-step-action`:

```html
<section class="slide" data-title="Work-Energy Theorem">
  <h1 class="text-3xl font-extrabold">Kinetic Energy Derivation</h1>

  <!-- Step 1: Initial formula -->
  <p class="step">We start with the kinematic formula: $v^2 = u^2 + 2as$</p>

  <!-- Step 2: Trigger custom JS / GSAP animation on this click -->
  <div class="step" data-step-action="animateWorkVector()" data-step-reverse="resetWorkVector()">
    <canvas id="vectorCanvas" width="600" height="180"></canvas>
  </div>

  <!-- Step 3: Final conclusion -->
  <div class="step p-4 rounded-xl bg-[#F5B718]/15 border border-[#F5B718]/30 font-bold">
    $W_{net} = \Delta KE = \frac{1}{2}m v_f^2 - \frac{1}{2}m v_i^2$
  </div>
</section>

<script>
  function animateWorkVector(stepEl) {
    // Run GSAP or custom canvas draw when Step 2 activates
    gsap.to('#vectorCanvas', { scale: 1.05, duration: 0.4, yoyo: true, repeat: 1 });
    // Or trigger a canvas physics step
  }

  function resetWorkVector(stepEl) {
    // Optional: Reverse animation if user presses Previous arrow
    gsap.set('#vectorCanvas', { scale: 1 });
  }
</script>
```

> [!TIP]
> You can either provide a function name (e.g. `data-step-action="animateWorkVector"`) or inline code (e.g. `data-step-action="gsap.to('#box', {x: 200})"`).

---

### D. Multi-Media Step Sequencing (Text $\to$ Video $\to$ Simulation in Steps)

You can mix different media types freely in sequential click steps on the same slide:

```
[Slide Loads] ──> Step 1: Text & Concept Question appear
                     │
              (Click Next)
                     ▼
                  Step 2: Video appears
                          • data-autoplay: Starts playback immediately on reveal
                          • OR Click-to-Play: Shows controls, teacher talks first
                     │
              (Click Next)
                     ▼
                  Step 3: Interactive Simulation canvas appears & starts running
                     │
              (Click Next)
                     ▼
                  Step 4: Takeaway Formula & Conclusion appear
```

#### Code Implementation Example:
```html
<section class="slide" data-title="Galileo's Free Fall">
  <h1 class="text-3xl font-black anim-fade-down">Gravitational Acceleration</h1>

  <!-- Step 1: Introductory Question / Theory -->
  <div class="step mt-6 p-4 rounded-xl bg-white border border-black/10 shadow-sm">
    <p class="font-bold text-[#181F26]">Hypothesis: Do heavier objects fall faster than lighter ones in a vacuum?</p>
  </div>

  <!-- Step 2: Video Demo (Auto-plays as soon as Step 2 reveals!) -->
  <div class="step mt-4 rounded-xl overflow-hidden shadow-lg border border-black/10">
    <video src="feather_and_hammer_vacuum.mp4" 
           data-autoplay 
           muted 
           loop 
           playsinline 
           controls 
           class="w-full max-h-60 object-cover bg-black">
    </video>
    <p class="text-xs text-black/50 p-2 bg-gray-50">Apollo 15 experiment: Hammer and feather dropped simultaneously on the Moon.</p>
  </div>

  <!-- Step 3: Simulation Widget appears and starts calculating -->
  <div class="step mt-4" data-step-action="startVacuumSim()" data-step-reverse="resetVacuumSim()">
    <canvas id="vacuumCanvas" width="650" height="180" class="rounded-xl border border-black/10 bg-slate-900"></canvas>
  </div>

  <!-- Step 4: Final Conclusion -->
  <div class="step mt-4 p-4 rounded-xl bg-[#F5B718]/15 border border-[#F5B718]/30 font-bold text-[#181F26]">
    $$g = 9.8\, \text{m/s}^2 \quad \text{(Independent of mass!)}$$
  </div>
</section>
```

#### Media Lifecycle Rules Handled Automatically by SlideCast:
1. **Autoplay on Step**: Videos with `data-autoplay` remain paused while hidden. They start playing the instant their `.step` becomes active.
2. **Click-to-Play on Step**: Videos without `data-autoplay` reveal in a paused state with controls, so the presenter can introduce the topic before clicking play.
3. **Step Reversal**: Pressing <kbd>←</kbd> (Previous) to undo a step automatically pauses the video and resets its playback time to zero.
4. **Slide Navigation Silence**: Navigating to another slide automatically pauses and silences all videos across previous slides, preventing audio leakage.

---

## 6. Question & Quiz Slide Patterns: Solve & Reveal vs. Interactive Assessment

In technical and scientific lecturing, slides must never be purely passive lecture notes. They are active intellectual checkpoints where instructors gauge comprehension and students engage in deliberate practice.

SlideCast natively supports **two complementary question paradigms**, plus a decoupled architecture for extensive question banks:

```
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                               QUESTION & QUIZ ARCHITECTURE                             │
│                                                                                        │
│  PATTERN 1: "SOLVE & REVEAL"               PATTERN 2: INTERACTIVE QUIZ                 │
│  (Live Pen Working Space)                  (Clickable Concept Check)                   │
│                                                                                        │
│  ┌──────────────────────────────┐          ┌──────────────────────────────┐            │
│  │ ❓ Problem Statement & Data  │          │ 💡 Concept Question          │            │
│  ├──────────────────────────────┤          ├──────────────────────────────┤            │
│  │ ✍️ Blank Whiteboard Canvas    │          │ [A] Option 1 (Red on click)  │            │
│  │   (Teacher inks with [P])    │          │ [B] Option 2 (Green correct) │            │
│  ├──────────────────────────────┤          ├──────────────────────────────┤            │
│  │ ✅ Step Reveal Model Answer   │          │ 💬 Instant Explanation      │            │
│  │   (Next click [→] reveals)   │          │   (Reveals on answer/click)  │            │
│  └──────────────────────────────┘          └──────────────────────────────┘            │
│                                                                                        │
│  PATTERN 3: DECOUPLED QUIZ APPS (quizzes/*.html)                                       │
│  Multi-question assessments, randomized banks, and gamified timers launched via modal. │
└────────────────────────────────────────────────────────────────────────────────────────┘
```

---

### Pattern A: "Solve & Reveal" Question Card (Live Pen Working Space)

**Best for:** Numerical problems, physics derivations, free-body diagrams, and organic chemistry mechanisms where the instructor or student needs to work out the solution in real time.

#### How It Works:
1. **Problem Card**: Presents the problem statement, given values, and target variables at the top or left.
2. **Dedicated Inking Canvas**: A generous blank space styled with a clean white/slate background or subtle dotted grid. The presenter presses <kbd>P</kbd> (Vector Pen) or <kbd>H</kbd> (Highlighter) and writes directly onto the slide to solve the problem live in class.
3. **Model Answer Reveal**: The official step-by-step solution is marked with `class="step"`. When the presenter finishes solving or wants to show the verified answer, pressing <kbd>→</kbd> or <kbd>Space</kbd> reveals the model solution card smoothly.

#### Minimal Working Example:
```html
<section class="slide p-8 flex flex-col justify-between" data-title="Example: Projectile Motion">
  <!-- Top: Problem Statement -->
  <div class="bg-white/80 dark:bg-slate-800/80 backdrop-blur rounded-2xl p-5 border border-slate-200 dark:border-slate-700 shadow-sm">
    <div class="flex items-center gap-3 mb-2">
      <span class="px-2.5 py-0.5 rounded-full text-xs font-bold bg-amber-500/10 text-amber-600 dark:text-amber-400 border border-amber-500/20">
        PRACTICE PROBLEM
      </span>
      <h3 class="text-xl font-bold text-slate-900 dark:text-white">Maximum Height of a Projectile</h3>
    </div>
    <p class="text-sm text-slate-600 dark:text-slate-300">
      A ball is launched with initial velocity $v_0 = 20\, \text{m/s}$ at an angle $\theta = 30^\circ$. 
      Find the maximum height reached ($g = 10\, \text{m/s}^2$).
    </p>
  </div>

  <!-- Middle: Blank Whiteboard Workspace for Pen (Hotkey: P) -->
  <div class="my-4 flex-1 min-h-[220px] rounded-2xl border-2 border-dashed border-slate-300 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-900/30 flex flex-col items-center justify-center relative overflow-hidden">
    <!-- Subtle watermark guide for inking -->
    <div class="text-center select-none pointer-events-none opacity-40">
      <span class="text-2xl">✍️</span>
      <p class="text-xs font-medium text-slate-500 dark:text-slate-400 mt-1">
        Instructor / Student Working Area (Press <kbd class="px-1 py-0.5 rounded bg-slate-200 dark:bg-slate-700 text-xs">P</kbd> to write)
      </p>
    </div>
  </div>

  <!-- Bottom: Official Step-by-Step Model Answer (Revealed on Next Click) -->
  <div class="step bg-emerald-500/10 border border-emerald-500/30 rounded-2xl p-4 text-slate-800 dark:text-slate-100 anim-fade-up">
    <div class="flex items-center justify-between mb-2">
      <span class="text-xs font-bold text-emerald-600 dark:text-emerald-400 uppercase tracking-wider">
        ✓ Official Model Solution
      </span>
      <span class="text-xs text-slate-400">Press → to reveal</span>
    </div>
    <div class="grid grid-cols-3 gap-4 text-xs font-mono">
      <div>$v_y = v_0 \sin\theta = 20 \times 0.5 = 10\, \text{m/s}$</div>
      <div>$H = \frac{v_y^2}{2g} = \frac{100}{20} = 5.0\, \text{m}$</div>
      <div class="font-bold text-emerald-600 dark:text-emerald-400">Final: $H_{\max} = 5.0\, \text{m}$</div>
    </div>
  </div>
</section>
```

---

### Pattern B: Interactive Quiz / ConcepTest Card (Clickable Options with Instant Feedback)

**Best for:** Conceptual checkpoints, Peer Instruction (Mazur method), and rapid multiple-choice sanity checks during a lecture.

#### How It Works:
1. **Interactive State in Cursor Mode (<kbd>V</kbd>)**: When the presenter or student is in standard Cursor mode (<kbd>V</kbd> or <kbd>Esc</kbd>), option buttons respond to clicks.
2. **Instant Visual Validation**:
   - Tapping an option immediately reveals whether it is correct (turns emerald green) or incorrect (turns rose red).
   - Tapping also reveals an informative explanation card explaining **why** the correct answer is right and clarifying common student misconceptions.
3. **Optional Step Sequencing**:
   - The question can appear first, with options revealing one-by-one via `class="step"`.
   - Or the whole question and options are visible immediately, and the explanation card is gated behind a `.step`.

#### Minimal Working Example:
```html
<section class="slide p-8 flex flex-col justify-center" data-title="Concept Check: Newton's 3rd Law">
  <div class="max-w-3xl mx-auto w-full bg-white dark:bg-slate-800 rounded-3xl p-8 shadow-xl border border-slate-200 dark:border-slate-700">
    <!-- Question Badge & Title -->
    <div class="flex items-center gap-2 mb-3">
      <span class="px-3 py-1 rounded-full text-xs font-bold bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 border border-indigo-500/20">
        CONCEPT CHECK (CONCEPTEST)
      </span>
    </div>
    <h2 class="text-2xl font-bold text-slate-900 dark:text-white mb-6">
      A heavy truck collides head-on with a small compact car. During the collision, which vehicle experiences a greater magnitude of impact force?
    </h2>

    <!-- Option Cards (Clickable in Cursor Mode [V]) -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-3" id="quiz-options-1">
      <button onclick="handleQuizAnswer(this, false, 'quiz-feedback-1')" 
              class="quiz-btn text-left p-4 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-indigo-400 transition-all text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-indigo-50/50 dark:hover:bg-indigo-950/30">
        <span class="font-bold mr-2 text-indigo-500">A.</span> The small compact car
      </button>
      <button onclick="handleQuizAnswer(this, false, 'quiz-feedback-1')" 
              class="quiz-btn text-left p-4 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-indigo-400 transition-all text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-indigo-50/50 dark:hover:bg-indigo-950/30">
        <span class="font-bold mr-2 text-indigo-500">B.</span> The heavy truck
      </button>
      <button onclick="handleQuizAnswer(this, true, 'quiz-feedback-1')" 
              class="quiz-btn text-left p-4 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-indigo-400 transition-all text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-indigo-50/50 dark:hover:bg-indigo-950/30">
        <span class="font-bold mr-2 text-indigo-500">C.</span> Both experience the exact same force magnitude
      </button>
      <button onclick="handleQuizAnswer(this, false, 'quiz-feedback-1')" 
              class="quiz-btn text-left p-4 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-indigo-400 transition-all text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-indigo-50/50 dark:hover:bg-indigo-950/30">
        <span class="font-bold mr-2 text-indigo-500">D.</span> Depends on which vehicle was traveling faster
      </button>
    </div>

    <!-- Explanation Box (Hidden until option is clicked, or revealed by pressing Next Step) -->
    <div id="quiz-feedback-1" class="hidden mt-6 p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-900 dark:text-emerald-200 text-sm anim-fade-up">
      <div class="font-bold text-emerald-600 dark:text-emerald-400 mb-1">✓ Correct Answer: C (Newton's Third Law)</div>
      <p class="text-xs leading-relaxed text-slate-600 dark:text-slate-300">
        By Newton's 3rd Law, the force exerted by the truck on the car is exactly equal and opposite to the force exerted by the car on the truck ($|F_{TC}| = |F_{CT}|$). The car sustains far more visible damage solely because of its smaller mass ($a = F/m$ causes much higher acceleration/deceleration).
      </p>
    </div>
  </div>
</section>

<!-- Lightweight Inline Script for Option Feedback -->
<script>
function handleQuizAnswer(btn, isCorrect, feedbackId) {
  const container = btn.closest(".slide");
  container.querySelectorAll(".quiz-btn").forEach(b => {
    b.disabled = true;
    b.classList.remove("hover:border-indigo-400", "hover:bg-indigo-50/50");
  });
  if (isCorrect) {
    btn.classList.add("bg-emerald-500/20", "border-emerald-500", "text-emerald-600", "dark:text-emerald-300");
  } else {
    btn.classList.add("bg-rose-500/20", "border-rose-500", "text-rose-600", "dark:text-rose-300");
  }
  const fb = document.getElementById(feedbackId);
  if (fb) fb.classList.remove("hidden");
}
</script>
```

---

### Decoupled Quiz Applications (`quizzes/` Folder)

Just as heavy Canvas simulations are kept out of slides and placed in `simulations/`, **multi-question assessments, randomized tests, or gamified quizzes** belong in a decoupled `quizzes/` folder:

```
my-lecture/
├── lecture_deck.html         # Main SlideCast slides
├── simulations/              # Decoupled interactive simulations
│   ├── orbit_sim.html
│   └── friction_sim.html
├── quizzes/                  # Decoupled interactive quiz apps
│   ├── motion_quiz.html      # Multi-question interactive quiz
│   └── forces_exam.html      # Timed practice assessment
└── assets/
    └── images/
```

#### When to Decouple into `quizzes/`:
- **Single checkpoint question** $ightarrow$ Keep inline on the slide using Pattern A (Solve & Reveal) or Pattern B (ConcepTest).
- **Multi-question bank or timed quiz (3+ questions, score tracker, randomized order)** $ightarrow$ Place in `quizzes/<quiz_name>.html` and open via the standard Modal Launcher:

```html
<!-- Slide with Quiz Launcher Card -->
<div class="p-6 rounded-2xl bg-indigo-500/10 border border-indigo-500/30 flex items-center justify-between">
  <div>
    <h3 class="text-lg font-bold text-indigo-900 dark:text-indigo-200">Module Knowledge Check</h3>
    <p class="text-xs text-indigo-700 dark:text-indigo-300">5 interactive concept questions with immediate scoring.</p>
  </div>
  <button onclick="openSimulation('quizModal1')" 
          class="px-5 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-sm shadow-md transition-transform hover:scale-105">
    Launch Quiz Modal →
  </button>
</div>

<!-- Modal Container hosting quizzes/motion_quiz.html -->
<div id="quizModal1" class="sim-modal hidden fixed inset-0 z-50 bg-black/80 backdrop-blur-md flex items-center justify-center p-6">
  <div class="relative w-full max-w-4xl h-[650px] bg-slate-900 rounded-2xl overflow-hidden border border-slate-700 shadow-2xl flex flex-col">
    <div class="flex justify-between items-center px-4 py-3 bg-slate-800 border-b border-slate-700">
      <span class="text-sm font-bold text-white">Motion Knowledge Check</span>
      <button onclick="closeSimulation('quizModal1')" class="text-slate-400 hover:text-white font-bold text-lg">✕</button>
    </div>
    <iframe src="quizzes/motion_quiz.html" class="w-full flex-1 border-0" loading="lazy"></iframe>
  </div>
</div>
```

#### Platform Rule for New Sandbox Features:
Whenever a new interactive quiz widget, scoring engine, or inking workspace is added to the SlideCast sandbox runtime, developers and AI agents must update this section to explain both:
1. How the feature renders and behaves inside the sandbox.
2. The exact slide HTML code required to utilize the feature.


---

## 7. Branching Sub-Slides & Drilldowns ("Inner Slides")

When an overview slide presents multiple sub-topics (e.g. **4 Fundamental Forces**, **3 Laws of Motion**, or **5 Case Studies**), you should use **Sub-Slides**.

A Sub-Slide is a dedicated deep-dive view that opens smoothly over the current slide **without altering the main presentation slide numbers (`1, 2, 3...`)**.

```
   ┌────────────────────────────────────────────────────────┐
   │                    MAIN SLIDE 2                        │
   │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
   │  │ 1. Gravity   │  │ 2. Electro   │  │ 3. Nuclear   │  │
   │  │ (Click Me!)  │  │              │  │              │  │
   │  └──────┬───────┘  └──────────────┘  └──────────────┘  │
   └─────────┼──────────────────────────────────────────────┘
             │ onclick="openSubslide('sub-gravity')"
             ▼
   ┌────────────────────────────────────────────────────────┐
   │  [← Back to Overview]          Slide 2 • Deep Dive     │
   │         ↑ Only exit point                              │
   │  SUB-SLIDE: Universal Gravitation                      │
   │  • Full Derivation                                     │
   │  • Interactive Orbit Video / Simulation                │
   │  • Dedicated Whiteboard Ink Layer                      │
   │  [→ / Space advances steps INSIDE sub-slide only]      │
   └────────────────────────────────────────────────────────┘
```

### Sub-Slide HTML Structure

Place `<div class="subslide" id="..." data-title="...">` directly inside the parent slide:

```html
<section class="slide" data-title="Fundamental Forces">
  <h1 class="text-4xl font-black">Fundamental Forces of Nature</h1>
  
  <!-- 4 Force Cards on Main Slide -->
  <div class="grid grid-cols-4 gap-6 mt-8">
    <!-- Card 1: Clicking opens Sub-Slide 'sub-gravity' -->
    <div onclick="openSubslide('sub-gravity')" class="cursor-pointer p-5 rounded-2xl bg-sky-50 border border-sky-200 hover:scale-105 transition shadow-sm">
      <h3 class="font-bold text-sky-900">1. Gravitational Force</h3>
      <p class="text-xs text-sky-700 mt-2">Always attractive · Infinite range</p>
      <span class="text-[10px] font-bold text-sky-600 underline mt-4 block">Click for Deep Dive →</span>
    </div>

    <!-- Card 2: Electrostatic Force -->
    <div onclick="openSubslide('sub-electro')" class="cursor-pointer p-5 rounded-2xl bg-rose-50 border border-rose-200 hover:scale-105 transition shadow-sm">
      <h3 class="font-bold text-rose-900">2. Electrostatic Force</h3>
      <p class="text-xs text-rose-700 mt-2">Attractive or repulsive · Infinite range</p>
      <span class="text-[10px] font-bold text-rose-600 underline mt-4 block">Click for Deep Dive →</span>
    </div>
  </div>

  <!-- ================= SUB-SLIDE 1: GRAVITY DEEP DIVE ================= -->
  <div class="subslide" id="sub-gravity" data-title="Gravitational Force Deep-Dive">
    <!-- Top Return Bar — Back button is the ONLY way to exit a sub-slide -->
    <div class="flex items-center justify-between pb-3 border-b border-black/10 mb-6">
      <button onclick="closeSubslide()" class="flex items-center space-x-2 text-xs font-bold text-[#181F26] px-3.5 py-1.5 rounded-lg bg-black/5 hover:bg-black/10 transition">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M15 19l-7-7 7-7"/></svg>
        <span>Back to Overview</span>
      </button>
      <span class="text-xs font-bold uppercase tracking-wider text-black/40">Slide 2 • Deep Dive</span>
    </div>

    <!-- Sub-Slide Content (Can include text, inner steps, videos, simulations) -->
    <h2 class="text-3xl font-black text-sky-950">Newton's Law of Universal Gravitation</h2>
    
    <div class="grid grid-cols-2 gap-8 mt-6">
      <div>
        <p class="step text-sm text-gray-700 leading-relaxed">
          Every point mass attracts every other point mass by a force acting along the line intersecting both points.
        </p>
        <div class="step mt-4 p-4 rounded-xl bg-sky-100 border border-sky-300 font-mono text-lg font-bold text-sky-900">
          $$F = G \frac{m_1 m_2}{r^2}$$
        </div>
      </div>
      
      <!-- Embedded Video in Sub-Slide -->
      <div class="step rounded-xl overflow-hidden shadow-md">
        <video src="orbit_motion.mp4" data-autoplay muted loop playsinline controls class="w-full h-48 object-cover bg-black"></video>
      </div>
    </div>
  </div>

  <!-- ================= SUB-SLIDE 2: ELECTROSTATIC DEEP DIVE ================= -->
  <div class="subslide" id="sub-electro" data-title="Electrostatic Force Deep-Dive">
    <div class="flex items-center justify-between pb-3 border-b border-black/10 mb-6">
      <button onclick="closeSubslide()" class="flex items-center space-x-2 text-xs font-bold text-[#181F26] px-3.5 py-1.5 rounded-lg bg-black/5 hover:bg-black/10 transition">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M15 19l-7-7 7-7"/></svg>
        <span>Back to Overview</span>
      </button>
      <span class="text-xs font-bold uppercase tracking-wider text-black/40">Slide 2 • Deep Dive</span>
    </div>
    <h2 class="text-3xl font-black text-rose-950">Coulomb's Law</h2>
    <div class="step mt-4 p-4 rounded-xl bg-rose-100 border border-rose-300 font-mono text-lg font-bold text-rose-900">
      $$F = \frac{1}{4\pi\varepsilon_0} \frac{|q_1 q_2|}{r^2}$$
    </div>
  </div>
</section>
```

#### Key Platform Behaviors for Sub-Slides:
- **Clean Numbering**: The bottom dock indicator displays `2 [Branch]`, preserving the global deck slide count (`Slide 2 / 5`).
- **One-Key Return**: Pressing <kbd>Escape</kbd> or clicking `← Back to Overview` smoothly returns you to the main overview.
- **Independent Inking**: Whiteboard ink drawn on a sub-slide stays on that sub-slide and does not bleed into the main slide.
- **Inner Step Support**: Pressing Next (<kbd>→</kbd>) while inside a sub-slide steps through the sub-slide's inner `.step` fragments before returning.

---

## 8. Direct Navigation: Slide Navigator with Live Miniature Previews

Presenters often need to jump directly across a presentation (e.g. from Slide 7 back to Slide 1 to review a formula, or from Slide 2 to Slide 5 for a quiz).

SlideCast provides a **Keynote / PowerPoint-style Slide Navigator**:

1. **Slide Navigator Left Rail (HotKey: <kbd>G</kbd>)**:
   - Pressing <kbd>G</kbd> opens a sleek slide drawer on the left side of the screen.
   - **Main Presentation Dimming**: The main presentation stage gently dims (`opacity: 0.45; filter: blur(1px)`) in the background, keeping context visible while highlighting the navigator.
   - **Live Scaled Miniature Previews**: Instead of just text, each card features a **complete, pixel-perfect visual thumbnail** of the slide rendered at 0.195× scale. It displays the slide's actual layout, typography, background gradients, hero artwork, and cards!
   - **Step Completion Preview**: In the thumbnail, all step fragments are revealed so the presenter can immediately identify the slide by its full contents.
   - **Live Whiteboard Ink Previews**: Any annotations drawn with the pen or highlighter on a slide are dynamically rendered onto that slide's thumbnail canvas.
   - **Sandboxed Safety**: Cloned thumbnails have all `<script>` tags removed, media paused and muted, and iframes substituted with lightweight badges to ensure zero background CPU load or rogue sound leaks.
   - **Active Slide Highlight**: The currently active slide features a prominent glowing gold border, gold number badge, and `ACTIVE` pill, and automatically scrolls into view when the drawer opens.
   - **Instant Jump**: Clicking any thumbnail immediately jumps to that slide in 0 ms and closes the drawer, restoring the stage to full brightness.

2. **Clicking the Dock Counter (`1 / N =`)**:
   - Clicking the slide counter on the bottom dock also opens the Slide Navigator.

3. **JavaScript API**:
   - Slides can also trigger jumps via buttons or table-of-contents links:
     ```html
     <!-- Table of Contents link directly to Slide 4 -->
     <button onclick="goToSlide(4)" class="px-4 py-2 rounded-xl bg-amber-400 font-bold">
       Jump to Quiz (Slide 4) →
     </button>
     ```

---

## 9. Standalone Simulation & Quiz File Standards (`simulations/*.html`, `quizzes/*.html`)

Files located in the `simulations/` and `quizzes/` folders must be **independent, fully functional, standalone web applications**.

### Standalone Requirements (Simulations & Quizzes):
1. **Self-Contained**: Single HTML file containing its own HTML, styles, and JavaScript (Canvas, SVG, or Three.js).
2. **Double-Clickable**: Double-clicking the file in Finder/Explorer opens and runs it standalone in Chrome/Safari without needing a web server.
3. **Responsive Size**: Uses `width: 100%; height: 100%;` so it looks sharp whether loaded in the slide's modal or full-screen on a mobile device.
4. **Interactive Controls**:
   - Sliders (e.g. Mass, Angle, Friction, Velocity).
   - Action Buttons: `Start / Run`, `Pause`, `Reset`.
   - Dynamic Telemetry / Readouts: Numbers update in real-time as the simulation runs.
5. **Theme & Visual Harmony Matching**:
   - Whether created from scratch or adapted from user/third-party snippets, the simulation **MUST be remade to match the visual theme, colors, fonts, and styling of the host slide deck**.
   - Match palette accents (e.g. Amber `#F5B718`, Dark Slate `#181F26`, Emerald `#10B981`, Rose `#EF4444`), typography, and sleek bento card containers.
   - Use compact 2-column or dashboard layouts to ensure zero vertical scrolling within presentation frames.


---

---

## 10. Long-Term Vision, 6-Month Incubation Plan & Strategic Roadmap

SlideCast is evolving from an interactive presentation sandbox into a complete **ecosystem for interactive technical and scientific lecturing**:

### Phase 1: AI Prompting & Authoring Ecosystem (Current)
- **Standardized Contract**: Proven semantic specification for LLMs (Claude, GPT, Gemini) to author full interactive decks on the first attempt.
- **Multi-Media Step Engine**: Coordinated reveals of text, equations, audio, video, and canvas simulations on a single slide.
- **Non-Linear Navigation**: Direct jump rail with live DOM-scaled miniature thumbnails (<kbd>G</kbd>).
- **Sub-Slide Branching**: Topic drilldowns with isolated whiteboard drawing canvases.

### Phase 2: Dual-Screen Presenter Console & Broadcast Engine
- **Dedicated Presenter Window (`presenter.html`)**: Connected in real time via the existing `BroadcastChannel('deck_channel')`.
- **Dual Display Layout**:
  - Current slide on stage + upcoming slide / step preview.
  - Speaker notes extracted live from `<aside class="notes">`.
  - Elapsed presentation timer, local clock, and slide progress bar.
- **Wireless / Second-Screen Remote Control**: Advance slides, toggle laser pointer, or switch tools from an iPad, phone, or laptop while projecting fullscreen on the lecture hall display.
- **Auto-Animate / Morph Choreography**: Elements tagged with a matching `data-morph="name"` on two different slides glide smoothly from their old position/size to the new one when the slide changes (PowerPoint-Morph style), with reverse support on <kbd>←</kbd>.

### Phase 3: Export & Student Handout Suite
- **Vector PDF Print Engine**: Generates pixel-perfect PDF lecture handouts capturing each completed slide state with high-resolution vector text.
- **Annotated Lecture Export**: Bundles teacher handwriting annotations into student-accessible review PDFs or PNG snapshots after class.
- **Standalone Offline Bundler**: Single-file exporter that packages images, simulations, KaTeX fonts, and slides into a single self-contained `.html` presentation for offline delivery.

### Phase 4: Reusable Educational UI Components (Drop-in Widgets)
- **KaTeX / MathJax Equation Cards**: Declarative `<div class="math-card">` with auto-typesetting and step-by-step algebraic derivation highlights.
- **Interactive Function Grapher**: 2D plotting widget for physics formulas ($y = f(x)$) with dynamic interactive parameter sliders.
- **Live Classroom Polling & Quiz Cards**: Interactive multiple-choice check-for-understanding cards with instant animated solution reveals.

---

### The 6-Month Open-Source Incubation Strategy

The most impactful developer tools (such as **Vue, Vite, Tailwind CSS, Excalidraw**, and **Reveal.js**) succeeded by incubating privately, battle-testing on real production workloads, and launching publicly with a rich showcase library.

SlideCast follows this **6-month incubation-to-open-source playbook**:

```mermaid
timeline
    title SlideCast 6-Month Incubation Roadmap
    Month 1 - 2 : Core Runtime & Inking Polish : Complete Presenter Console (dual-screen) : Live visual navigator & vanishing laser
    Month 3 - 4 : Battle-Testing & Content : Create 10-15 interactive lecture decks : Drop-in educational widgets (graphers, KaTeX cards)
    Month 5 : Zero-Friction Tooling : 1-click starter generator : Export suite (Vector PDF handouts) : GitHub repo cleanup & MIT License
    Month 6 : The Open Source Launch : Interactive demo on GitHub Pages : Launch on Hacker News & Product Hunt : Educator community outreach
```

#### Why This Strategy Ensures Maximum Impact:
1. **Battle-Tested in Real Lecture Halls**:
   - Using SlideCast continuously for real STEM lectures over 6 months eliminates subtle edge cases, stylus latency quirks, and projector resolution issues before the wider public touches it.
2. **Launch with an Irresistible Showcase Library**:
   - Frameworks go viral because of their **demos**. SlideCast will launch with 10–15 complete, breathtaking interactive decks (Forces, Thermodynamics, Electromagnetism, Quantum concepts) with live simulations that immediately inspire educators.
3. **The "AI-First" Hook (The Viral Growth Vector)**:
   - SlideCast is the **first presentation runtime engineered specifically for the Generative AI era**.
   - Educators and developers will simply paste this guide into Claude or ChatGPT to generate complete, interactive, simulation-backed slide decks on any topic in seconds.
4. **Zero-Install / Zero-Dependency Freedom**:
   - No `npm install`, no heavy build step, and no backend requirement. Anyone can run it locally by double-clicking `index.html` or deploying it instantly to free GitHub Pages under an open MIT License.

---

## 11. Complete Copy-Paste Prompt for Other AI Assistants

*Copy the prompt below and give it to any AI when requesting slides and simulations:*

```markdown
You are an expert interactive educational slide designer and web developer.
I need an interactive slide deck for the SlideCast presentation platform.
SlideCast is an open web presentation runtime and framework: the sandbox automatically manages uncapped 4K stage scaling, PowerPoint-style vector inking, vanishing laser pointer, glass explanation sheets, live miniature visual thumbnails, and sound-safe video lifecycles. A built-in Docs panel (top bar **Docs** or press D) lists every slide feature in plain language.

Your role is to author the slide content adhering to SlideCast's lightweight semantic framework contract (<section class="slide">, .step, .subslide, and decoupled standalone simulations) with 100% creative styling freedom.

### PROJECT REQUIREMENTS:
1. Topic: [INSERT TOPIC, e.g. Fundamental Forces of Nature]
2. Total Slides: [e.g. 4 Slides]
3. Required Simulations: [e.g. Gravitational Orbit and Incline Friction]

### ARCHITECTURAL RULES:
1. DECOUPLED ARCHITECTURE:
   - Provide the main slide deck as `lecture_deck.html`.
   - Provide heavy simulations as separate files in `simulations/<sim_name>.html`.
   - On the slide, provide a launcher card with a button calling `openSimulation('simModalId')`.

2. SLIDE DECK SPECIFICATION:
   - Wrap each slide in `<section class="slide" data-title="..." data-aspect="16:9">`.
   - Target a 750px virtual height (1333x750 for 16:9).
   - Use modern Tailwind CSS styling (rounded-2xl cards, crisp typography, clean contrast).
   - Entrance animations: `anim-fade-up`, `anim-fade-down`, `anim-pop-in`, and stagger delays `delay-100`, `delay-200`.
   - Optional CDN libraries (load only when needed): GSAP, Motion, or Anime.js for animation, Three.js for 3D, KaTeX/MathJax for math, Mermaid for diagrams, Chart.js for graphs.

3. MULTI-MEDIA STEP SEQUENCING:
   - For multi-step explanations, derivations, or problem solutions, use `class="step"` (or `class="fragment"`).
   - You can mix text, video, and simulation canvas inside steps:
     * Text: `<div class="step">...</div>`
     * Video: `<video class="step" data-autoplay muted loop playsinline controls src="..."></video>` (starts playing automatically when revealed)
     * Click-to-Play Video: `<video class="step" controls src="..."></video>` (fades in paused for teacher to talk first)
     * Simulation: `<div class="step" data-step-action="runSim()">...</div>`
   - Use `data-step="N"` to group multiple elements on the same click.

4. QUESTION & QUIZ PATTERNS:
   - When introducing practice problems, use Pattern A: "Solve & Reveal"
     * Problem statement at top.
     * Generous blank workspace (min-h-[220px]) with dashed border for teacher/student live inking with Pen [P].
     * Step-by-step model solution wrapped in class="step" (revealed on next click [→]).
   - For multiple choice concept checks, use Pattern B: "Interactive ConcepTest"
     * Clickable option buttons (handled in Cursor mode [V]).
     * Instant visual feedback (emerald for correct, rose for incorrect) + explanation box.
   - For multi-question assessments (3+ questions), decouple into `quizzes/<quiz_name>.html` and launch via modal launcher button.

5. BRANCHING SUB-SLIDES (INNER SLIDES):
   - When an overview slide introduces multiple sub-topics (e.g. 4 forces or 3 laws), wrap each sub-topic deep-dive in:
     `<div class="subslide" id="sub-<topic>" data-title="<Topic> Deep-Dive">`
   - Inside the subslide, include a **Back button** calling `closeSubslide()` — this is the ONLY exit point. Esc and arrow keys do NOT close sub-slides.
   - On the parent overview card, add `onclick="openSubslide('sub-<topic>')"` to launch it.

6. DIRECT NAVIGATION:
   - Presenters can jump directly to any slide by pressing 'G' or calling `goToSlide(slideIndex)`.

7. PRESENTER WEBCAM SAFE ZONE (BOTTOM-RIGHT):
   - In every slide, reserve the bottom-right area (approx 280px × 240px) as a safe zone.
   - Keep this corner blank (whitespace) or place only non-essential ambient background art.
   - The instructor's square/4:3 webcam video overlays this corner during video recording.
   - NEVER place core lesson text, formulas, definitions, interactive buttons, or quiz questions in the bottom-right quadrant.

8. BRAND LOGO SAFE ZONE (TOP-RIGHT):
   - In every slide, reserve the top-right corner (approx 120px × 80px) as a blank safe zone.
   - The platform overlays a persistent brand logo watermark in the top-right corner.
   - NEVER place slide titles, subtitles, motto text, formulas, badges, or buttons in the top-right corner.

9. DO NOT INCLUDE:
   - Do NOT include `#stage`, `.deck-viewport`, or `resizeStage()` code.

10. ANIMATION POLICY (ALWAYS APPLY):
   - Never deliver a static slide. Proactively choose suitable, polished, good-looking animations for every slide using the approved toolkit:
     * Default: built-in entrance classes (`anim-fade-up`, `anim-fade-down`, `anim-slide-left`, `anim-slide-right`, `anim-pop-in`, `anim-card-in`) with staggered `delay-100 … delay-700`.
     * Special choreography: GSAP (SVG line-draws, timelines), Motion (springs, stagger, gestures), or Anime.js (SVG morphing, motion paths) via CDN.
   - Trigger JS animations with `data-step-action="fn()"` and provide `data-step-reverse` for the undo.
   - Motion must feel purposeful, smooth, and professional — never distracting or excessive.
   - If the user provides only an image (or a topic) with no animation instructions, select the best-fitting animations yourself — do not ask.

11. CANVAS ANIMATIONS & AUDIO SYNTHESIZERS (THE 4 GOLDEN RULES):
   - Scope isolation: wrap custom slide scripts in an IIFE `(function() { ... })();` to prevent global variable collisions (`SyntaxError: Identifier already declared`).
   - Web Audio policy: use an explicit Click-to-Play user interaction (`AudioContext.resume()`) before initiating sound generation.
   - Slide lifecycle: attach a `MutationObserver` to `.slide` watching the `class` attribute to pause animation loops (`cancelAnimationFrame`) and stop audio loops when navigating away (`!slideEl.classList.contains('active')`).
   - Storage & performance: keep slides lightweight (<50KB); avoid embedding multi-megabyte base64 image strings.

Now, generate the complete code for `lecture_deck.html` and each standalone simulation file in `simulations/`.
```

---

## 12. Checklist Before Delivering Files

- [ ] Each slide has `<section class="slide" data-title="...">`
- [ ] No `resizeStage()`, `#stage`, or `.deck-viewport` in `lecture_deck.html`
- [ ] Multi-step items use `<div class="step">` or `data-step="N"`
- [ ] Autoplay videos in steps have `data-autoplay muted loop playsinline controls`
- [ ] Practice questions provide blank workspace for Pen [P] with model answer in `class="step"`
- [ ] Multi-question tests are stored in `quizzes/` and launched via modal
- [ ] Sub-slides use `<div class="subslide" id="..." data-title="...">` with `closeSubslide()` back button
- [ ] Simulations live in the `simulations/` subfolder and run independently when double-clicked
- [ ] Simulations and inner slides match the parent deck theme, color palette, typography, and card design (no raw, unstyled embeds)
- [ ] Sliders and reset buttons work with real physical calculations
- [ ] Every slide has suitable, polished animations (built-in `anim-*` entrances and/or GSAP/Motion/Anime.js) — no static slides
- [ ] Top-right corner (approx 120px × 80px) kept clean for persistent platform brand logo watermark
- [ ] Bottom-right corner kept clean (or non-essential art only) for presenter webcam / PiP video overlay
- [ ] Canvas scripts and audio synths are wrapped in an isolated IIFE `(function() { ... })();`
- [ ] Web Audio synthesizers use an explicit Click-to-Play user gesture (`AudioContext.resume()`)
- [ ] Slide lifecycle `MutationObserver` automatically pauses canvas animation loops and mutes audio when leaving the slide
- [ ] Slides avoid massive inline base64 assets to ensure fast DOM parsing and protect `localStorage` quotas (<50KB per slide)


