/* AI-Native PM OS - main React app */
const { useState, useEffect, useRef, useMemo } = React;

const STORAGE = {
  done: 'pmos.lessonsDone',
  capstone: 'pmos.capstone',
  commit: 'pmos.commit',
  streak: 'pmos.streak',
  heatmap: 'pmos.heatmap',
};

const load = (k, fallback) => {
  try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : fallback; } catch { return fallback; }
};
const save = (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch {} };

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#F6891F",
  "displayFont": "Instrument Serif",
  "compactCurriculum": false,
  "showDashboard": true,
  "heroVariant": "terminal"
}/*EDITMODE-END*/;

/* ============== HERO ============== */
function Hero() {
  const cmds = [
    'claude /init pm-os',
    'claude /load PRDs/meridian-q3.md',
    'claude --use-mcp jira "decompose into tickets"',
    'claude /research synthesize interviews/*.md',
  ];
  const [cmdIdx, setCmdIdx] = useState(0);
  const [typed, setTyped] = useState('');

  useEffect(() => {
    let i = 0;
    const cmd = cmds[cmdIdx];
    setTyped('');
    const id = setInterval(() => {
      i++;
      setTyped(cmd.slice(0, i));
      if (i >= cmd.length) {
        clearInterval(id);
        setTimeout(() => setCmdIdx((cmdIdx + 1) % cmds.length), 2400);
      }
    }, 55);
    return () => clearInterval(id);
  }, [cmdIdx]);

  return (
    <section className="hero">
      <div className="wrap">
        <div className="hero-grid">
          <div className="hero-left">
            <div className="stamps">
              <span className="stamp tilt"><span className="dot"></span>v2.0 · live</span>
              <span className="stamp">63 lessons</span>
              <span className="stamp tilt-r">11 modules</span>
              <span className="stamp">free on github</span>
            </div>
            <h1 className="headline">
              Build the PM <em>operating&nbsp;system</em> your team wishes <span className="underline-stroke">it already had.</span>
            </h1>
            <p className="lede">
              A 63-lesson hands-on build program. You ship real PRD pipelines, research synthesizers,
              analytics copilots, and connector workflows - inside an AI coding agent - across a
              fictional B2B SaaS world called Meridian.
            </p>
            <div className="cta-row">
              <a href="#curriculum" className="btn btn-primary">
                Start the course <span className="arrow">→</span>
              </a>
              <a href="https://github.com/vishalmdi/ai-native-pm-os" target="_blank" rel="noopener noreferrer" className="btn btn-ghost">
                Download OS Files
              </a>
            </div>
            <div className="access-line">
              <span className="free-pill">Free now</span>
              <span>Paid edition with cohorts coming later. The build is yours forever.</span>
            </div>
          </div>

          <div className="hero-right">
            <div className="float-card fc-1">
              <div className="label">Module 03 / Lesson 3</div>
              <strong>PRD → Ticket Pipeline</strong>
              <div style={{fontSize:'12px', marginTop:'4px', opacity:.75}}>40 min · interactive</div>
            </div>
            <div className="terminal" aria-hidden="true">
              <div className="term-bar">
                <span className="dot r"></span>
                <span className="dot y"></span>
                <span className="dot g"></span>
                <span className="title">pm-os</span>
              </div>
              <div className="term-body">
                <div className="term-line">
                  <span className="term-prompt">$</span>
                  <span className="term-cmd">{typed}<span className="term-cursor"></span></span>
                </div>
                <div className="term-out info" style={{marginTop:'14px'}}>Loading CLAUDE.md (3 layers)</div>
                <div className="term-out ok">Context vault: 47 docs synced</div>
                <div className="term-out ok">MCP connectors: jira · slack · amplitude</div>
                <div className="term-out ok">Memory: 12 pinned decisions</div>
                <div className="term-out warn">› spawning sub-agent: prd-reviewer</div>
                <div className="term-out ok">Sub-agent ready (eng + design + skeptic)</div>
                <div className="term-final">▸ AI-Native PM OS is online.</div>
              </div>
            </div>
            <div className="float-card fc-2">
              <div className="label">XP earned · today</div>
              <strong>+240 XP · 2 lessons</strong>
              <div style={{fontSize:'12px', marginTop:'4px', opacity:.75}}>🔥 7-day streak alive</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============== TICKER ============== */
function Ticker() {
  const items = [
    'PRD pipeline', 'Research synthesizer', 'Analytics copilot',
    'Connector workflows', 'Meridian capstone', '11 modules',
    'Free on GitHub', '40 - 50 hours', 'Built by Vishal Jaiswal'
  ];
  const repeated = [...items, ...items];
  return (
    <div className="ticker" aria-hidden="true">
      <div className="ticker-track">
        <span>
          {repeated.map((t, i) => (
            <React.Fragment key={i}>
              <span>{t}</span>
              <span className="star">✦</span>
            </React.Fragment>
          ))}
        </span>
      </div>
    </div>
  );
}

/* ============== WHAT YOU'LL BUILD ============== */
function Build() {
  const cards = [
    { num:'01', title:'PRD pipeline', desc:'Draft, review with eng/design/skeptic agents, decompose into tickets - auto-versioned.', span:6, accent:'orange',
      glyph:<div className="gx-flow"><div className="gx-node sq"></div><div className="gx-arrow"></div><div className="gx-node fill"></div><div className="gx-arrow"></div><div className="gx-node"></div></div>
    },
    { num:'02', title:'Research synthesizer', desc:'Interviews, support tickets, competitive intel - citations included.', span:6, accent:false,
      glyph:<div className="gx-doc"></div>
    },
    { num:'03', title:'Analytics copilot', desc:'Connect data, frame experiments, narrate metrics.', span:4,
      glyph:<div className="gx"><div className="gx-bar a"></div><div className="gx-bar b"></div><div className="gx-bar c"></div><div className="gx-bar d"></div><div className="gx-bar e"></div><div className="gx-bar f"></div></div>
    },
    { num:'04', title:'Connector workflows', desc:'Jira, Slack, Amplitude, Notion, Workspace - wired into reasoning.', span:4, accent:true,
      glyph:<div className="gx-net">
        <svg viewBox="0 0 140 80" aria-hidden="true">
          <circle cx="70" cy="40" r="9" fill="#F6891F" stroke="#1d1d1d" strokeWidth="2"/>
          <circle cx="20" cy="20" r="7" fill="none" stroke="#1d1d1d" strokeWidth="2"/>
          <circle cx="120" cy="20" r="7" fill="none" stroke="#1d1d1d" strokeWidth="2"/>
          <circle cx="20" cy="60" r="7" fill="none" stroke="#1d1d1d" strokeWidth="2"/>
          <circle cx="120" cy="60" r="7" fill="none" stroke="#1d1d1d" strokeWidth="2"/>
          <line x1="61" y1="40" x2="27" y2="22" stroke="#1d1d1d" strokeWidth="1.5"/>
          <line x1="79" y1="40" x2="113" y2="22" stroke="#1d1d1d" strokeWidth="1.5"/>
          <line x1="61" y1="40" x2="27" y2="58" stroke="#1d1d1d" strokeWidth="1.5"/>
          <line x1="79" y1="40" x2="113" y2="58" stroke="#1d1d1d" strokeWidth="1.5"/>
        </svg>
      </div>
    },
    { num:'05', title:'Meridian capstone', desc:'A full PM OS demo on a realistic B2B SaaS world.', span:4,
      glyph:<div style={{display:'flex', gap:'4px', alignItems:'flex-end'}}>
        <div style={{width:'14px', height:'30px', background:'#1d1d1d'}}></div>
        <div style={{width:'14px', height:'52px', background:'#1d1d1d'}}></div>
        <div style={{width:'14px', height:'72px', background:'#F6891F', border:'1.5px solid #1d1d1d'}}></div>
        <div style={{width:'14px', height:'40px', background:'#1d1d1d'}}></div>
      </div>
    },
  ];

  return (
    <section className="build" data-reveal id="build">
      <div className="wrap">
        <div className="kicker">What you'll build</div>
        <h2>Five real surfaces. <em>Not slides.</em></h2>
        <p className="sub">Every module ends with an artifact you can show your team. By the end, you're running a system, not a chat.</p>
        <div className="build-grid">
          {cards.map(c => (
            <div key={c.num} className={`build-card span${c.span} ${c.accent === 'orange' ? 'accent-orange' : c.accent ? 'accent' : ''}`}>
              <span className="num">{c.num} · output</span>
              <h3>{c.title}</h3>
              <p>{c.desc}</p>
              <div className="glyph">{c.glyph}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============== WHO IT'S FOR ============== */
function Who() {
  const cards = [
    { num:'A', title:'The prompt-tired PM', desc:'You\'ve outgrown copy-paste prompts. You want repeatable workflows that compound.', tag:'most common', flag:'flag-orange' },
    { num:'B', title:'The system-first PM', desc:'You think in operating systems, not features. You want a real one - for yourself.', tag:'power user', flag:'' },
    { num:'C', title:'The technical PM builder', desc:'Analysts, growth, platform PMs who want connector-native workflows with real data.', tag:'fastest ROI', flag:'flag-blue' },
  ];
  return (
    <section className="who" data-reveal>
      <div className="wrap">
        <div className="who-head">
          <div>
            <div className="kicker">Who this is for</div>
            <h2>Three kinds of <em>PM</em><br/>get the most out of it.</h2>
          </div>
          <p className="who-aside">If your team has ever asked you to "operationalize AI" without giving you a playbook - this is the playbook.</p>
        </div>
        <div className="who-grid">
          {cards.map(c => (
            <div key={c.num} className={`who-card ${c.flag}`}>
              <span className="num"> - Profile {c.num}</span>
              <h3>{c.title}</h3>
              <p>{c.desc}</p>
              <span className="tag">{c.tag}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============== CURRICULUM ============== */
function Curriculum({ done, toggleDone, openLesson, compact }) {
  const modules = window.COURSE_DATA.modules;
  const [active, setActive] = useState(0);
  const totalLessons = modules.reduce((s, m) => s + m.lessons.length, 0);

  const moduleProgress = (m) => {
    const total = m.lessons.length;
    const completed = m.lessons.filter(l => done[l.id]).length;
    return { total, completed, pct: total ? completed / total : 0 };
  };

  const mod = modules[active];

  return (
    <section className="curriculum" id="curriculum" data-reveal>
      <div className="wrap">
        <div className="curr-head">
          <div>
            <div className="kicker">Curriculum</div>
            <h2>A 63-lesson <em>build</em> program.</h2>
          </div>
          <div className="meta">
            {Object.keys(done).filter(k => done[k]).length} / {totalLessons} lessons · 11 modules · 40 - 50 hrs
          </div>
        </div>

        <div className="module-tabs" role="tablist">
          {modules.map((m, i) => {
            const { pct } = moduleProgress(m);
            return (
              <button
                key={m.id}
                role="tab"
                aria-selected={i === active}
                onClick={() => setActive(i)}
                className="module-tab"
              >
                <span className="mt-num">M{String(m.id).padStart(2, '0')}</span>
                <span>{m.title}</span>
                <span className="mt-progress"><i style={{width: `${pct * 100}%`}}></i></span>
              </button>
            );
          })}
        </div>

        <div className="module-panel">
          <div className="module-panel-head">
            <div>
              <div className="kicker">Module {String(mod.id).padStart(2, '0')}</div>
              <h3>{mod.title}</h3>
              <p className="mp-sub">{mod.subtitle}</p>
            </div>
            <div className="mp-stat">
              <strong>{mod.lessons.filter(l => done[l.id]).length}/{mod.lessons.length}</strong>
              <span>lessons · {mod.hours}</span>
            </div>
          </div>

          <div className="lesson-list">
            {mod.lessons.map((l, i) => (
              <div
                key={l.id}
                className={`lesson ${done[l.id] ? 'done' : ''}`}
                onClick={() => openLesson(l.id)}
              >
                <div
                  className="lesson-check"
                  onClick={(e) => { e.stopPropagation(); toggleDone(l.id); }}
                  title="Mark complete without opening"
                  role="button"
                >
                  <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <polyline points="3,8 7,12 13,4"/>
                  </svg>
                </div>
                <span className="lesson-id">{l.id}</span>
                <div>
                  <h4 className="lesson-title">{l.title}</h4>
                  {!compact && <p className="lesson-desc">{l.desc}</p>}
                </div>
                <div className="lesson-arrow">→</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============== DASHBOARD ============== */
function Dashboard({ done, totalLessons, capstone, setCapstone, commit, setCommit, openLesson }) {
  const completed = Object.keys(done).filter(k => done[k]).length;
  const pct = totalLessons ? completed / totalLessons : 0;

  // Up-next computation
  const modules = window.COURSE_DATA.modules;
  const allLessons = modules.flatMap(m => m.lessons.map(l => ({ ...l, moduleId: m.id, moduleTitle: m.title })));
  const nextLesson = allLessons.find(l => !done[l.id]);
  const currentModule = nextLesson ? modules.find(m => m.id === nextLesson.moduleId) : null;
  const moduleLessonsDone = currentModule
    ? currentModule.lessons.filter(l => done[l.id]).length : 0;
  const moduleLessonsTotal = currentModule ? currentModule.lessons.length : 0;

  // XP - 50 per lesson
  const xp = completed * 50;
  const tiers = [
    { name:'AI Curious', threshold:0 },
    { name:'AI Apprentice', threshold:200 },
    { name:'Builder', threshold:600 },
    { name:'Operator', threshold:1400 },
    { name:'PM-OS Architect', threshold:2400 },
    { name:'Native', threshold:3150 },
  ];
  let currentTier = tiers[0];
  let nextTier = tiers[1];
  for (let i = tiers.length - 1; i >= 0; i--) {
    if (xp >= tiers[i].threshold) {
      currentTier = tiers[i];
      nextTier = tiers[i + 1] || tiers[i];
      break;
    }
  }
  const tierPct = currentTier === nextTier ? 1 :
    Math.min(1, (xp - currentTier.threshold) / (nextTier.threshold - currentTier.threshold));

  // Streak - fake demo, but real-feeling
  const streak = Math.min(completed, 14);

  // Ring math
  const r = 56, c = 2 * Math.PI * r;
  const offset = c - pct * c;

  // Heatmap - derived from completed pattern
  const weeks = 12, days = 7;
  const heatmap = useMemo(() => {
    const cells = [];
    for (let w = 0; w < weeks; w++) {
      const col = [];
      for (let d = 0; d < days; d++) {
        // give some pattern for visual richness - last few weeks more active
        const recency = (w / weeks) ** 1.4;
        const seed = ((w * 7 + d) * 9301 + 49297) % 233280 / 233280;
        const bound = recency * (completed / totalLessons);
        let level = 0;
        if (seed < bound * 1.6) level = Math.min(4, Math.floor(seed * 5 / Math.max(0.05, bound)));
        col.push(level);
      }
      cells.push(col);
    }
    return cells;
  }, [completed, totalLessons]);

  // Commit
  const [venue, setVenue] = useState(commit?.venue || '');
  const [date, setDate] = useState(commit?.date || '');
  const canCommit = venue.trim() && date.trim();
  const saveCommit = () => setCommit({ venue, date });
  const editCommit = () => setCommit(null);

  return (
    <section className="dash" id="dashboard" data-reveal>
      <div className="wrap">
        <div className="dash-head">
          <div className="kicker">Learner dashboard</div>
          <h2>Track the build. <em>Earn the stamps.</em></h2>
          <p>This isn't a marketing dashboard preview - it's the real thing. Tick lessons in the curriculum above and watch every panel here update.</p>
        </div>

        <div className="dash-grid">
          {/* PROGRESS RING */}
          <div className="dash-card dc-progress">
            <div className="dc-label">Course progress</div>
            <h4>You're {Math.round(pct * 100)}% of the way there.</h4>
            <div className="ring">
              <svg className="ring-svg" viewBox="0 0 140 140" aria-hidden="true">
                <defs>
                  <linearGradient id="ringGrad" x1="0" y1="0" x2="1" y2="1">
                    <stop offset="0%" stopColor="#F6891F"/>
                    <stop offset="100%" stopColor="#D7423E"/>
                  </linearGradient>
                </defs>
                <circle className="ring-bg" cx="70" cy="70" r={r}/>
                <circle
                  className="ring-fg"
                  cx="70" cy="70" r={r}
                  strokeDasharray={c}
                  strokeDashoffset={offset}
                  transform="rotate(-90 70 70)"
                />
                <text className="ring-pct" x="70" y="78" textAnchor="middle">{Math.round(pct * 100)}%</text>
              </svg>
              <div className="ring-text">
                <div className="big">{completed} <span style={{color:'var(--ink-mute)'}}>/ {totalLessons}</span></div>
                <div className="lab">Lessons completed across 11 modules.</div>
                <div className="ring-bar"><i style={{width: `${pct * 100}%`}}></i></div>
                <div className="ring-meta">
                  <span>NEXT MILESTONE: 50%</span>
                  <span>{Math.max(0, Math.ceil(totalLessons / 2 - completed))} TO GO</span>
                </div>
              </div>
            </div>
          </div>

          {/* XP */}
          <div className="dash-card dc-xp xp-card">
            <div className="dc-label">XP &amp; tier</div>
            <h4>{currentTier.name}</h4>
            <div className="xp-level">
              <span className="level">Lvl {tiers.indexOf(currentTier) + 1}</span>
              <span className="pts">{xp} / {nextTier.threshold} XP</span>
            </div>
            <div className="xp-bar"><i style={{width: `${tierPct * 100}%`}}></i></div>
            <p className="xp-next">
              {currentTier === nextTier
                ? 'Top tier reached. Run the capstone.'
                : `${nextTier.threshold - xp} XP until ${nextTier.name}.`}
            </p>
            <div className="xp-tiers">
              {tiers.map((t, i) => {
                const idx = tiers.indexOf(currentTier);
                const cls = i < idx ? 'unlocked' : i === idx ? 'current' : '';
                return <span key={t.name} className={`xp-tier ${cls}`}>{t.name}</span>;
              })}
            </div>
          </div>

          {/* STREAK */}
          <div className="dash-card dc-streak streak-card">
            <div className="dc-label">Daily streak</div>
            <div className="streak-num">{streak}<span className="lab">days</span></div>
            <div className="streak-flames">
              {Array.from({length: 7}).map((_, i) => (
                <span key={i} className={`streak-flame ${i < Math.min(streak, 7) ? 'lit' : ''}`}></span>
              ))}
            </div>
            <p>{streak === 0 ? 'Tick your first lesson to start the streak.' : streak < 3 ? 'Keep the streak alive - tomorrow counts double.' : 'You\'re building a daily habit. This is how the OS sticks.'}</p>
          </div>

          {/* UP NEXT - actionable recommendation */}
          <div className="dash-card dc-upnext">
            <div className="dc-label">Up next - resume here</div>
            {nextLesson ? (
              <>
                <div className="upnext-head">
                  <span className="upnext-mod">Module {currentModule.id} · {currentModule.title}</span>
                  <span className="upnext-prog">{moduleLessonsDone} / {moduleLessonsTotal} done</span>
                </div>
                <h4>{nextLesson.title}</h4>
                <p className="upnext-desc">{nextLesson.desc}</p>
                <div className="upnext-bar"><i style={{width: `${(moduleLessonsDone / moduleLessonsTotal) * 100}%`}}></i></div>
                <div className="upnext-actions">
                  <button className="upnext-cta" onClick={() => openLesson(nextLesson.id)}>
                    <span>Open lesson</span>
                    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                      <line x1="2" y1="8" x2="13" y2="8"/>
                      <polyline points="9,4 13,8 9,12"/>
                    </svg>
                  </button>
                  <span className="upnext-meta">~25 min · +50 XP on complete</span>
                </div>
              </>
            ) : (
              <>
                <h4>You've finished every lesson.</h4>
                <p className="upnext-desc">All 63 lessons complete. Lock in the capstone below and demo the build.</p>
                <div className="upnext-actions">
                  <a className="upnext-cta" href="#capstone-track">
                    <span>Pick capstone track</span>
                    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                      <line x1="2" y1="8" x2="13" y2="8"/>
                      <polyline points="9,4 13,8 9,12"/>
                    </svg>
                  </a>
                </div>
              </>
            )}
          </div>

          {/* MINI STATS */}
          <div className="dash-card dc-stats">
            <div className="dc-label">Build stats</div>
            <h4>Your trail</h4>
            <div className="mini-stats">
              <div className="mini-stat"><strong>{completed}</strong><span>Lessons done</span></div>
              <div className="mini-stat"><strong>{Math.floor(completed * 0.6)}</strong><span>Checkpoints</span></div>
              <div className="mini-stat"><strong>{Math.floor(completed / 6)}</strong><span>Modules cleared</span></div>
              <div className="mini-stat"><strong>{xp}</strong><span>XP earned</span></div>
            </div>
          </div>

          {/* HEATMAP */}
          <div className="dash-card dc-heatmap">
            <div className="dc-label">Activity · last 12 weeks</div>
            <h4>Learning rhythm</h4>
            <div className="heatmap">
              {heatmap.map((col, w) => (
                <div className="hm-week" key={w}>
                  {col.map((lvl, d) => (
                    <span key={d} className={`hm-day l${lvl}`} title={`Week ${w + 1}, day ${d + 1}`}></span>
                  ))}
                </div>
              ))}
            </div>
            <div className="hm-legend">
              <span>less</span>
              <span className="swatch hm-day l0"></span>
              <span className="swatch hm-day l1"></span>
              <span className="swatch hm-day l2"></span>
              <span className="swatch hm-day l3"></span>
              <span className="swatch hm-day l4"></span>
              <span>more</span>
            </div>
          </div>

          {/* CAPSTONE */}
          <div className="dash-card dc-capstone" id="capstone-track">
            <div className="dc-label">Capstone - pick your demo</div>
            <h4>Choose the track that matches the workflow you want to demo.</h4>
            <div className="capstone-tracks">
              {[
                { id:'zero-to-one', title:'Zero to One', desc:'Discovery → PRD → launch story for a brand-new surface.', icon:'◆' },
                { id:'scale', title:'Scale & Optimize', desc:'Metrics, experiments, growth loops on an existing product.', icon:'△' },
                { id:'platform', title:'Technical Infrastructure', desc:'Connectors, workflows, automation as the deliverable.', icon:'◯' },
              ].map(t => (
                <button
                  key={t.id}
                  className={`ctrack ${capstone === t.id ? 'active' : ''}`}
                  onClick={() => setCapstone(capstone === t.id ? null : t.id)}
                >
                  <span className="ct-icon">{t.icon}</span>
                  <strong>{t.title}</strong>
                  <span>{t.desc}</span>
                  <span className="check">
                    <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="3,8 7,12 13,4"/>
                    </svg>
                  </span>
                </button>
              ))}
            </div>

            {!commit ? (
              <div className="commit-row">
                <input
                  type="text" placeholder="Where will you demo? (e.g. PM team review)"
                  value={venue} onChange={e => setVenue(e.target.value)}
                />
                <input
                  type="date" value={date} onChange={e => setDate(e.target.value)}
                />
                <button onClick={saveCommit} disabled={!canCommit}>Lock it in →</button>
              </div>
            ) : (
              <div className="commit-saved">
                <p>
                  <strong>Demo locked:</strong> {commit.venue} · {commit.date}
                </p>
                <button onClick={editCommit}>Edit</button>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============== CREATOR ============== */
function Creator() {
  return (
    <section className="creator" id="creator" data-reveal>
      <div className="wrap">
        <div className="creator-grid">
          <div className="creator-photo">
            <span className="badge">The author</span>
            <img src="assets/vishal-profile.png" alt="Vishal Jaiswal"/>
          </div>
          <div>
            <div className="kicker">About the build</div>
            <h2>I built this because <em>nobody else was.</em></h2>
            <p className="lede2">
              I'm Vishal - 15+ years across AI, analytics, data platforms, and product workflows. I kept watching PMs
              get handed "use AI more" without a system. So I built one. Meridian is a fictional B2B SaaS world
              with realistic PRDs, research transcripts, dashboards, and stakeholders. You build agents, workflows,
              and artifacts that work there - and they translate directly to your real job.
            </p>
            <div className="credits-strip">
              <div className="credit"><strong>15+</strong><span>years building</span></div>
              <div className="credit"><strong>63</strong><span>lessons inside</span></div>
              <div className="credit"><strong>$0</strong><span>to start</span></div>
            </div>
            <div className="creator-links">
              <a href="https://jaiswal-vishal.vercel.app/" target="_blank" rel="noopener noreferrer">Portfolio →</a>
              <a href="https://jaiswal-vishal.vercel.app/writing" target="_blank" rel="noopener noreferrer">Writing →</a>
              <a href="https://www.linkedin.com/in/vishal-jaiswal-analytics-leader/" target="_blank" rel="noopener noreferrer">LinkedIn →</a>
              <a href="https://jaiswal-vishal.vercel.app/contact" target="_blank" rel="noopener noreferrer">Contact →</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============== FAQ ============== */
function FAQ() {
  const items = window.COURSE_DATA.faq;
  const [openIdx, setOpenIdx] = useState(0);
  return (
    <section className="faq" id="faq" data-reveal>
      <div className="wrap">
        <div className="faq-head">
          <div className="kicker">Frequently asked</div>
          <h2>The <em>real</em> questions, answered.</h2>
          <p>If something's still unclear, the GitHub README is exhaustive - and the Discord is open.</p>
        </div>
        <div className="faq-list">
          {items.map((f, i) => (
            <div key={i} className={`faq-item ${i === openIdx ? 'open' : ''}`}>
              <button className="faq-q" onClick={() => setOpenIdx(i === openIdx ? -1 : i)}>
                <span className="num">Q.{String(i + 1).padStart(2, '0')}</span>
                <span>{f.q}</span>
                <span className="toggle"></span>
              </button>
              <div className="faq-a">{f.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============== FINAL CTA ============== */
function Final() {
  return (
    <section className="final">
      <div className="final-floats" style={{display:'none'}}>
        <span className="ff" style={{top:'18%', left:'8%', transform:'rotate(-6deg)'}}>63 lessons</span>
        <span className="ff" style={{top:'30%', right:'10%', transform:'rotate(5deg)'}}>11 modules</span>
        <span className="ff" style={{bottom:'25%', left:'14%', transform:'rotate(3deg)', background:'var(--orange)'}}>free now</span>
        <span className="ff" style={{bottom:'15%', right:'8%', transform:'rotate(-4deg)'}}>fork it →</span>
      </div>
      <div className="wrap">
        <h2>Stop reading <span className="strike">about</span> AI.<br/><em>Build with it.</em></h2>
        <p>Open the repo. Run the install lesson. Ship something this weekend that your team can use Monday.</p>
        <div className="cta-row">
          <a href="#curriculum" className="btn btn-primary">
            Start learning now <span className="arrow">→</span>
          </a>
          <a href="https://github.com/vishalmdi/ai-native-pm-os" target="_blank" rel="noopener noreferrer" className="btn btn-ghost">View Source on GitHub</a>
        </div>
      </div>
    </section>
  );
}

/* ============== TWEAKS ============== */
function Tweaks({ tweaks, setTweak }) {
  const { TweaksPanel, TweakSection, TweakColor, TweakToggle, TweakRadio, TweakSelect } = window.TweaksKit;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Theme">
        <TweakColor
          label="Accent"
          value={tweaks.accent}
          onChange={v => setTweak('accent', v)}
          options={['#F6891F', '#2A5BD7', '#5C8A4E', '#D7423E']}
        />
      </TweakSection>
      <TweakSection title="Typography">
        <TweakSelect
          label="Display font"
          value={tweaks.displayFont}
          onChange={v => setTweak('displayFont', v)}
          options={['Instrument Serif', 'Inter Tight', 'JetBrains Mono']}
        />
      </TweakSection>
      <TweakSection title="Layout">
        <TweakToggle label="Compact curriculum" value={tweaks.compactCurriculum} onChange={v => setTweak('compactCurriculum', v)} />
        <TweakToggle label="Show learner dashboard" value={tweaks.showDashboard} onChange={v => setTweak('showDashboard', v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

/* ============== APP ============== */
function App() {
  const [done, setDone] = useState(() => load(STORAGE.done, {}));
  const [capstone, setCapstoneRaw] = useState(() => load(STORAGE.capstone, null));
  const [commit, setCommitRaw] = useState(() => load(STORAGE.commit, null));
  const [openLessonId, setOpenLessonId] = useState(null);
  const tweaksHook = window.TweaksKit ? window.TweaksKit.useTweaks(TWEAK_DEFAULTS) : { tweaks: TWEAK_DEFAULTS, setTweak: () => {} };
  const { tweaks, setTweak } = tweaksHook;

  const allLessons = useMemo(() => window.COURSE_DATA.modules.flatMap(m => m.lessons), []);
  const totalLessons = allLessons.length;

  const lessonById = (id) => allLessons.find(l => l.id === id);

  const navLesson = (delta) => {
    if (!openLessonId) return;
    const idx = allLessons.findIndex(l => l.id === openLessonId);
    const next = allLessons[idx + delta];
    if (next) setOpenLessonId(next.id);
  };

  const toggleDone = (id) => {
    setDone(prev => {
      const next = { ...prev };
      if (next[id]) delete next[id]; else next[id] = Date.now();
      save(STORAGE.done, next);
      return next;
    });
  };
  const setCapstone = (v) => { setCapstoneRaw(v); save(STORAGE.capstone, v); };
  const setCommit = (v) => { setCommitRaw(v); save(STORAGE.commit, v); };

  // Apply tweaks to CSS variables
  useEffect(() => {
    document.documentElement.style.setProperty('--orange', tweaks.accent);
    document.documentElement.style.setProperty('--orange-deep', tweaks.accent);
    document.documentElement.style.setProperty('--display', `"${tweaks.displayFont}", Georgia, serif`);
  }, [tweaks.accent, tweaks.displayFont]);

  // Topbar progress
  useEffect(() => {
    const completed = Object.keys(done).filter(k => done[k]).length;
    const pct = totalLessons ? completed / totalLessons : 0;
    const fill = document.getElementById('topbar-progress-fill');
    if (fill) fill.style.width = `${pct * 100}%`;
  }, [done, totalLessons]);

  // Reveal on scroll
  useEffect(() => {
    const els = document.querySelectorAll('[data-reveal]');
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.08 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, [tweaks]);

  const hasProgress = Object.keys(done).length > 0;

  const dashboardEl = tweaks.showDashboard && (
    <Dashboard
      done={done} totalLessons={totalLessons}
      capstone={capstone} setCapstone={setCapstone}
      commit={commit} setCommit={setCommit}
      openLesson={setOpenLessonId}
    />
  );

  return (
    <>
      {window.VercelAnalytics && <window.VercelAnalytics />}
      <Hero/>
      <Ticker/>
      {dashboardEl}
      <article>
        <Build/>
        <Who/>
        <Curriculum done={done} toggleDone={toggleDone} openLesson={setOpenLessonId} compact={tweaks.compactCurriculum}/>
        <Creator/>
        <FAQ/>
        <Final/>
      </article>
      {window.TweaksKit && <Tweaks tweaks={tweaks} setTweak={setTweak}/>}
      {window.LessonReader && (
        <window.LessonReader
          lessonId={openLessonId}
          lesson={openLessonId ? lessonById(openLessonId) : null}
          isDone={!!done[openLessonId]}
          onClose={() => setOpenLessonId(null)}
          onComplete={() => openLessonId && toggleDone(openLessonId)}
          onNav={navLesson}
        />
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App/>);
