/* ipma.jsx — IPMA Individual Certification: multi-product course view */

/* ─────────────────────────────────────────────────────────────── DATA ── */

const IPMA_CHAPTERS_DATA = [
{ n: 1, title: "General Introduction", status: "done", mins: 18 },
{ n: 2, title: "Structure of the Course", status: "done", mins: 14 },
{
  n: 3, title: "Project Orientation", status: "active", mins: 55,
  blurb: "This chapter helps individuals determine when an initiative should be managed as a project and how to apply project management principles. It covers the definition of a project, the reasons for initiating one, and the conditions necessary to succeed. The chapter also explores key concepts like the triple constraint, project stages, decision-making, and project positioning within an organisation.",
  lessons: [
  { title: "Project Management", mins: 35, status: "active", topics: ["Introduction", "What is a project, and what is project management", "Reasons to initiate a project", "Prerequisites for and characteristics of a project", "The different work forms", "Project lifecycle", "Staging, phasing, controlling and decision-making within projects", "Control aspects in a project", "Magic triangle and the iron square", "Projects within the product lifecycle", "Project at different levels", "Project output, outcome, benefits, and goals", "Agile versus Waterfall approach", "Sustainability and projects", "IPMA Project Excellence Baseline (advanced)"] },
  { title: "Practice Exam", mins: 20, status: "locked", kind: "exam" }]

},
{ n: 4, title: "Project Preparation", status: "locked", mins: 108, lessons: [{ title: "Project Preparation Stage", mins: 22 }, { title: "Stakeholders", mins: 18 }, { title: "Project Organisation", mins: 24 }, { title: "Requirements and Objectives", mins: 20 }, { title: "Risk and Opportunity", mins: 24 }] },
{ n: 5, title: "Project Definition", status: "locked", mins: 168, lessons: [{ title: "Project Definition Stage", mins: 20 }, { title: "Project Design", mins: 18 }, { title: "Scope", mins: 22 }, { title: "Quality", mins: 20 }, { title: "Time", mins: 24 }, { title: "Resources", mins: 22 }, { title: "Finance", mins: 26 }, { title: "Business Case", mins: 16 }] },
{ n: 6, title: "Project Delivery", status: "locked", mins: 132, lessons: [{ title: "Procurement", mins: 22 }, { title: "Change Control", mins: 18 }, { title: "Information and Documentation", mins: 24 }, { title: "Control and Reporting", mins: 26 }, { title: "Change and Transformation", mins: 22 }, { title: "Project Closure", mins: 20 }] },
{ n: 7, title: "Managing Yourself", status: "locked", mins: 66, track: "Behavioural", lessons: [{ title: "Self-reflection and Self-management", mins: 22 }, { title: "Personal Integrity and Reliability", mins: 22 }, { title: "Personal Communication", mins: 22 }] },
{ n: 8, title: "Connecting with Others", status: "locked", mins: 154, track: "Behavioural", lessons: [{ title: "Relationship and Engagement", mins: 22 }, { title: "Leadership", mins: 22 }, { title: "Teamwork", mins: 22 }, { title: "Resourcefulness", mins: 22 }, { title: "Result Orientation", mins: 22 }, { title: "Negotiation", mins: 22 }, { title: "Conflict and Crisis", mins: 22 }] },
{ n: 9, title: "Implementing Changes", status: "locked", mins: 110, track: "Perspective", lessons: [{ title: "Strategy", mins: 22 }, { title: "Programme Management", mins: 22 }, { title: "Portfolio Management", mins: 22 }, { title: "Support Functions and Implementing PPP", mins: 22 }, { title: "Process Development Frameworks", mins: 22 }] },
{ n: 10, title: "Internal Context", status: "locked", mins: 66, track: "Perspective", lessons: [{ title: "Organisation Theory", mins: 22 }, { title: "Personnel Management", mins: 22 }, { title: "Financial Administration", mins: 22 }] },
{ n: 11, title: "External Context", status: "locked", mins: 110, track: "Perspective", lessons: [{ title: "Health, Security, Safety and Environment", mins: 22 }, { title: "Sustainability", mins: 22 }, { title: "Compliance and Regulations", mins: 22 }, { title: "Power and Interests", mins: 22 }, { title: "Culture and Values", mins: 22 }] }];


const IPMA_TOC_COLS = [
{ label: "Practice Competencies", color: "#c0392b",
  groups: [
  { n: 4, title: "Project Preparation", items: [["4.01", "4.5.10", "Project Preparation Stage"], ["4.02", "4.5.12", "Stakeholders"], ["4.03", "4.5.5", "Project Organisation"], ["4.04", "4.5.5", "Requirements and Objectives"], ["4.05", "4.5.11", "Risk and Opportunity"]] },
  { n: 5, title: "Project Definition", items: [["5.01", "4.5.6", "Project Definition Stage"], ["5.02", "4.5.1", "Project Design"], ["5.03", "4.5.6", "Scope"], ["5.04", "4.5.6", "Quality"], ["5.05", "4.5.4", "Time"], ["5.06", "4.5.8", "Resources"], ["5.07", "4.5.7", "Finance"], ["5.08", "4.5.1", "Business Case"]] },
  { n: 6, title: "Project Delivery", items: [["6.01", "4.5.9", "Procurement"], ["6.02", "4.5.13", "Change control"], ["6.03", "4.5.9", "Information and Documentation"], ["6.04", "4.5.10", "Control and Reporting"], ["6.05", "4.5.13", "Change and Transformation"], ["6.06", "4.5.13", "Project Closure"]] }]

},
{ label: "Behavioural Competencies", color: "var(--vh-blue-500)",
  groups: [
  { n: 7, title: "Managing Yourself", items: [["7.01", "4.4.1", "Self-reflection and Self-management"], ["7.02", "4.4.2", "Personal Integrity and Reliability"], ["7.03", "4.4.3", "Personal Communication"]] },
  { n: 8, title: "Connecting with others", items: [["8.01", "4.4.4", "Relationship and Engagement"], ["8.02", "4.4.5", "Leadership"], ["8.03", "4.4.8", "Teamwork"], ["8.04", "4.4.8", "Resourcefulness"], ["8.05", "4.4.10", "Result Orientation"], ["8.06", "4.4.9", "Negotiation"], ["8.07", "4.4.7", "Conflict and Crisis"]] }]

},
{ label: "Perspective Competencies", color: "var(--vh-teal)",
  groups: [
  { n: 9, title: "Implementing Changes", items: [["9.01", "4.3.1", "Strategy"], ["9.02", "4.3.2", "Programme Management"], ["9.03", "4.3.2", "Portfolio Management"], ["9.04", "4.3.2", "Support Functions and Implementing PPP"], ["9.05", "4.3.2", "Process Development Frameworks"]] },
  { n: 10, title: "Internal Context", items: [["10.01", "4.3.2", "Organisation Theory"], ["10.02", "4.3.2", "Personnel Management"], ["10.03", "4.3.2", "Financial Administration"]] },
  { n: 11, title: "External Context", items: [["11.01", "4.3.3", "Health, Security, Safety and Environment"], ["11.02", "4.3.3", "Sustainability"], ["11.03", "4.3.3", "Compliance and Regulations"], ["11.04", "4.4.4", "Power and Interests"], ["11.05", "4.4.5", "Culture and Values"]] }]

}];


const IPMA_SA_GROUPS = [
{ label: "Practice Competencies", color: "#c0392b", short: "Practice", icon: "target",
  ces: ["Project Orientation", "Project Preparation Stage", "Stakeholder Management", "Project Organisation", "Requirements & Objectives", "Risk & Opportunity", "Project Design", "Scope", "Quality", "Time Management", "Resource Management", "Finance & Budget", "Procurement", "Control & Reporting", "Project Closure"] },
{ label: "People Competencies", color: "var(--vh-blue-500)", short: "People", icon: "users",
  ces: ["Self-reflection & Self-management", "Personal Integrity & Reliability", "Personal Communication", "Relationship & Engagement", "Leadership", "Teamwork", "Conflict & Crisis Management", "Resourcefulness", "Negotiation", "Results Orientation"] },
{ label: "Perspective Competencies", color: "var(--vh-teal)", short: "Perspective", icon: "globe",
  ces: ["Strategy", "Governance, Structures & Processes", "Compliance & Standards", "Power & Interests", "Culture & Values"] }];


const SA_LEVELS = ["—", "D", "C", "B"];
const SA_LEVEL_LABELS = ["Not rated", "Associate (D)", "Project Manager (C)", "Senior PM (B)"];
const SA_LEVEL_COLORS = ["var(--line)", "#c0392b", "var(--vh-blue-500)", "var(--vh-teal)"];

/* ─────────────────────────────────────────────────────── E-LEARNING ── */

function IPMAToC() {
  return (
    <div className="card" style={{ marginBottom: 22, overflow: "hidden", padding: 0 }}>
      <div style={{ padding: "12px 18px", borderBottom: "1px solid var(--line)", fontFamily: "var(--display)", fontWeight: 700, fontSize: 15 }}>Table of contents V1.2</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr" }}>
        {IPMA_TOC_COLS.map((col, ci) =>
        <div key={ci} style={{ borderRight: ci < 2 ? "1px solid var(--line)" : "none", padding: "14px 14px 16px" }}>
            <div style={{ fontSize: 11, fontWeight: 700, padding: "4px 8px", borderRadius: 4, marginBottom: 12, color: "#fff", background: col.color, textAlign: "center", textTransform: "uppercase", letterSpacing: ".05em" }}>{col.label}</div>
            {col.groups.map((g) =>
          <div key={g.n} style={{ marginBottom: 12 }}>
                <div style={{ fontWeight: 700, fontSize: 12.5, marginBottom: 5, color: "var(--ink)" }}>{g.n}. {g.title}</div>
                {g.items.map(([num, lvl, name], ii) =>
            <div key={ii} style={{ display: "flex", gap: 5, fontSize: 11, color: "var(--ink-2)", padding: "1.5px 0", lineHeight: 1.4 }}>
                    <span style={{ color: "var(--ink-3)", flex: "none" }}>{num}</span>
                    <span style={{ color: "var(--ink-3)", flex: "none" }}>{lvl}</span>
                    <span>{name}</span>
                  </div>
            )}
              </div>
          )}
          </div>
        )}
      </div>
    </div>);

}

function IPMAGeneralIntroContent() {
  const sections = [
  { title: "General Introduction", body: "The International Project Management Association (IPMA) has developed an Individual Competence Baseline, version 4 (ICB4) — the global standard for individual competence in project, programme and portfolio management. It supports the development of individual competence by presenting a complete inventory of competence elements across projects, programmes and portfolios." },
  { title: "Textbook and Preparation Guide", body: "IPMA also published the textbook Project Management by ICB4 and the Preparation Guide for IPMA Individual Certification. In the textbook, the knowledge areas within the different competence elements are specified. The preparation guide contains a summary of the theories described in the textbook, as well as many multiple-choice and open-ended questions with sample answers and rationale." },
  { title: "Purpose E-learning", body: "This e-learning platform allows you to acquire new skills, information, and concepts at your own pace based on the ICB4 framework. Furthermore, it provides accessibility and convenience, enabling you to access the platform from anywhere, at any time, using various devices." },
  { title: "The Eye of Competence", body: "The Eye of Competence represents the universe of competences for project, programme and portfolio management. Competences are divided into three areas: Perspective, People, and Practice. These areas provide a focus for the aspects of competence and together create the whole, balanced individual." },
  { title: "Competence areas", body: "For project management, the three competence areas are subdivided into 28 competence elements (CEs): 05 Perspective competencies, 10 People competencies, and 13 Practice competencies. The perspective competences define the contextual competences to navigate projects within and across the broader environment." },
  { title: "Taxonomy", body: "The required mastery levels can be related to Bloom's taxonomy. Three composite levels are distinguished: Comprehension (c) — remembering and understanding specific concepts; Application (p) — being able to apply knowledge, models and concepts; Analysis (a) — being able to analyse and evaluate specific issues." }];

  return (
    <div style={{ padding: "22px 26px 10px" }}>
      {sections.map((s, i) =>
      <div key={i} style={{ marginBottom: 20 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 6 }}>
            <svg width="18" height="14" viewBox="0 0 18 14" fill="none" style={{ flex: "none" }}><path d="M2 2l5 5-5 5M8 2l5 5-5 5" stroke="var(--vh-teal)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" /></svg>
            <h4 style={{ fontFamily: "var(--display)", fontSize: 13.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".07em", margin: 0, color: "var(--ink)" }}>{s.title}</h4>
          </div>
          <div style={{ width: 30, height: 2, background: "var(--vh-teal)", margin: "0 0 10px 24px" }} />
          <p style={{ fontSize: 13.5, lineHeight: 1.75, color: "var(--ink-2)", margin: "0 0 0 24px" }}>{s.body}</p>
        </div>
      )}
      <div style={{ margin: "8px 0 20px 24px", overflowX: "auto" }}>
        <table style={{ fontSize: 11.5, borderCollapse: "collapse", border: "1px solid var(--line)", minWidth: 420 }}>
          <thead>
            <tr>{[["c = Comprehension", 2], ["p = Application", 2], ["a = Analysis", 2]].map(([h, cs]) => <th key={h} colSpan={cs} style={{ background: "var(--vh-blue-50)", padding: "7px 10px", border: "1px solid var(--line)", fontFamily: "var(--display)", fontSize: 11.5, fontWeight: 700 }}>{h}</th>)}</tr>
            <tr>{["Verbs", "Nouns", "Verbs", "Nouns", "Verbs", "Nouns"].map((h, i) => <th key={i} style={{ background: "var(--surface-2)", padding: "5px 8px", border: "1px solid var(--line)", fontSize: 11, fontWeight: 600, color: "var(--ink-2)" }}>{h}</th>)}</tr>
          </thead>
          <tbody>
            {[["Recognise", "Terms", "Apply", "Situations", "Analyse", "Analysis"], ["Name", "Facts", "Draw up", "Applications", "Derive", "Models"], ["Compare", "Processes", "Implement", "Principles", "Assess", "Problems"], ["Describe", "Relationships", "Calculate", "Criteria", "Design", "Conclusions"], ["Define", "Standards", "Define", "Rules", "Prioritise", "Predictions"], ["Explain", "Rules", "Choose", "Methods", "Relate", "Comment(s)"], ["Reproduce", "Criteria", "(Re)solve", "Conclusions", "Conclude", "Concepts"], ["Illustrate", "Methods", "Derive", "—", "Consider", "—"]].map((row, ri) =>
            <tr key={ri} style={{ background: ri % 2 ? "var(--surface-2)" : "var(--surface)" }}>{row.map((cell, ci) => <td key={ci} style={{ padding: "4px 8px", border: "1px solid var(--line)", fontSize: 11, color: cell === "—" ? "var(--ink-3)" : "var(--ink-2)" }}>{cell}</td>)}</tr>
            )}
          </tbody>
        </table>
      </div>
    </div>);

}

/* ───────────────────────────── INTRO MODULE ── */
const INTRO_JOBS = [
{ title: "Project Manager", size: 36 }, { title: "Business Analyst", size: 26 },
{ title: "Programme Manager", size: 24 }, { title: "IT Manager", size: 22 },
{ title: "Scrum Master", size: 22 }, { title: "Product Owner", size: 20 },
{ title: "Team Lead", size: 20 }, { title: "Change Manager", size: 20 },
{ title: "Consultant", size: 18 }, { title: "Portfolio Manager", size: 18 },
{ title: "Service Manager", size: 18 }, { title: "Operations Manager", size: 16 },
{ title: "Delivery Manager", size: 16 }, { title: "PMO Coordinator", size: 16 },
{ title: "Department Manager", size: 15 }];

const INTRO_COLS = ["#e8a020", "#3bc1ce", "#1368ce", "#e21b3c", "#26890c", "#a855f7", "#f472b6", "#34d399", "#60a5fa", "#fb923c"];
const INTRO_SLIDES = [
{ id: "welcome" },
{ id: "trainer" },
{ id: "wordcloud" },
{ id: "expectations" },
{ id: "schedule" }];


function IPMAIntroModule({ toast }) {
  const [open, setOpen] = useState(false);
  const [done, setDone] = useState(false);
  const [si, setSi] = useState(0);
  const [myJob, setMyJob] = useState(null);
  const [jobVotes, setJobVotes] = useState(Object.fromEntries(INTRO_JOBS.map((j, i) => [j.title, Math.floor(Math.random() * 4) + 1])));
  const [expectText, setExpectText] = useState("");
  const slide = INTRO_SLIDES[si];
  const total = INTRO_SLIDES.length;

  function next() {if (si + 1 < total) setSi((s) => s + 1);else {setDone(true);setOpen(false);}}
  function prev() {if (si > 0) setSi((s) => s - 1);}

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden", marginBottom: 20 }}>
      {/* header row */}
      <button onClick={() => setOpen((o) => !o)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 14, padding: "16px 20px", background: "none", textAlign: "left", cursor: "pointer", borderBottom: open ? "1px solid var(--line)" : "none" }}>
        <div style={{ width: 40, height: 40, borderRadius: 11, flex: "none", display: "grid", placeItems: "center", background: "linear-gradient(135deg,#46178f,#1a0a3e)" }}>
          <Icon name="sparkle" size={20} style={{ color: "#f9c74f" }} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 15, color: "var(--ink)" }}>Introduction Module</div>
          <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 2 }}>{done ? "Completed · " + total + " slides" : "Not started · " + total + " slides · ~10 min"}</div>
        </div>
        {done ?
        <span className="tag" style={{ background: "color-mix(in oklab,var(--vh-teal),transparent 84%)", color: "var(--vh-teal)", flex: "none" }}><Icon name="check" size={12} />Done</span> :
        <span className="tag accent" style={{ flex: "none" }}>Start here</span>}
        <Icon name="chevD" size={16} style={{ color: "var(--ink-3)", flex: "none", transform: open ? "none" : "rotate(-90deg)", transition: "transform .2s" }} />
      </button>

      {open &&
      <div>
          {/* slide progress */}
          <div style={{ display: "flex", gap: 4, padding: "10px 20px 0" }}>
            {INTRO_SLIDES.map((_, i) =>
          <div key={i} style={{ flex: 1, height: 4, borderRadius: 9, background: i < si ? "var(--vh-teal)" : i === si ? "var(--vh-orange)" : "var(--surface-3)", transition: "background .3s" }} />
          )}
          </div>

          {/* slide area */}
          <div style={{ padding: "0 20px 16px" }}>

            {/* SLIDE 1: Welcome */}
            {slide.id === "welcome" &&
          <div style={{ marginTop: 20, borderRadius: 14, overflow: "hidden", background: "linear-gradient(140deg,#1d3d7c,#0a1429)", position: "relative", minHeight: 260, display: "flex", alignItems: "center", justifyContent: "center", textAlign: "center", padding: "32px 40px", boxSizing: "border-box" }}>
                <div className="hexfield" style={{ opacity: .12 }} />
                <div style={{ position: "relative" }}>
                  <div className="hex-flat" style={{ width: 60, height: 66, margin: "0 auto 16px", clipPath: "polygon(50% 0,93% 25%,93% 75%,50% 100%,7% 75%,7% 25%)", background: "var(--vh-orange)", display: "grid", placeItems: "center" }}><Icon name="graduation" size={30} style={{ color: "#231f20" }} /></div>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 900, fontSize: 30, color: "#fff", marginBottom: 10, lineHeight: 1.1 }}>Welcome to IPMA-D Training</div>
                  <div style={{ fontSize: 16, color: "rgba(255,255,255,.7)", marginBottom: 18, lineHeight: 1.5 }}>4-day intensive programme · ICB4 framework<br />Van Haren Academy · Amsterdam, June 2026</div>
                  <div style={{ display: "flex", gap: 20, justifyContent: "center" }}>
                    {[["4", "Training days"], ["28", "Competence elements"], ["9", "Participants"]].map(([v, l]) =>
                <div key={l} style={{ textAlign: "center" }}>
                        <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 28, color: "var(--vh-orange)" }}>{v}</div>
                        <div style={{ fontSize: 12, color: "rgba(255,255,255,.55)", fontWeight: 600 }}>{l}</div>
                      </div>
                )}
                  </div>
                </div>
              </div>
          }

            {/* SLIDE 2: Trainer */}
            {slide.id === "trainer" &&
          <div style={{ marginTop: 20, display: "grid", gridTemplateColumns: "180px 1fr", gap: 16, borderRadius: 14, overflow: "hidden", border: "1px solid var(--line)" }}>
                <div style={{ background: "linear-gradient(160deg,#1d3d7c,#0a1429)", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "28px 20px", gap: 12 }}>
                  <div className="hexfield" style={{ opacity: .15 }} />
                  <div style={{ position: "relative", width: 72, height: 72, borderRadius: 18, background: "var(--vh-orange)", display: "grid", placeItems: "center", fontSize: 28, fontFamily: "var(--display)", fontWeight: 900, color: "#231f20" }}>RB</div>
                  <div style={{ textAlign: "center", position: "relative" }}>
                    <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 15, color: "#fff" }}>Rik van der Berg</div>
                    <div style={{ fontSize: 12, color: "rgba(255,255,255,.6)", marginTop: 3 }}>IPMA-A Certified</div>
                  </div>
                </div>
                <div style={{ padding: "22px 22px" }}>
                  <div className="eyebrow" style={{ marginBottom: 10 }}>Your trainer</div>
                  <div style={{ fontSize: 14, color: "var(--ink-2)", lineHeight: 1.7, marginBottom: 14 }}>Rik has over 15 years of experience managing complex infrastructure and IT transformation projects. He has trained more than 400 professionals for IPMA certification.</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    {[["IPMA-A", "Certified Projects Director"], ["15+ years", "Project management experience"], ["400+", "Certified professionals trained"], ["Languages", "Dutch, English, German"]].map(([k, v]) =>
                <div key={k} style={{ display: "flex", gap: 10, fontSize: 13 }}>
                        <span style={{ fontWeight: 700, color: "var(--vh-blue-500)", minWidth: 90, flex: "none" }}>{k}</span>
                        <span style={{ color: "var(--ink-2)" }}>{v}</span>
                      </div>
                )}
                  </div>
                </div>
              </div>
          }

            {/* SLIDE 3: Word cloud — who are you? */}
            {slide.id === "wordcloud" &&
          <div style={{ marginTop: 20 }}>
                <div style={{ textAlign: "center", marginBottom: 16 }}>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 22, color: "var(--ink)", marginBottom: 4 }}>Who are you?</div>
                  <div style={{ fontSize: 14, color: "var(--ink-3)" }}>Click your current role — it appears in the group word cloud</div>
                </div>
                <div style={{ borderRadius: 14, background: "#f8f9fb", border: "1px solid var(--line)", padding: "20px 24px", display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "center", gap: 10, minHeight: 160 }}>
                  {INTRO_JOBS.map((job, i) => {
                const votes = jobVotes[job.title] || 0;
                const isMe = myJob === job.title;
                const scale = 1 + votes * 0.05;
                return (
                  <button key={job.title} onClick={() => {
                    if (isMe) {setMyJob(null);setJobVotes((v) => ({ ...v, [job.title]: Math.max(0, v[job.title] - 1) }));} else
                    {if (myJob) setJobVotes((v) => ({ ...v, [myJob]: Math.max(0, v[myJob] - 1) }));setMyJob(job.title);setJobVotes((v) => ({ ...v, [job.title]: (v[job.title] || 0) + 1 }));}
                  }}
                  style={{ fontSize: job.size, fontWeight: 900, lineHeight: 1.2, color: isMe ? "#fff" : INTRO_COLS[i % INTRO_COLS.length], background: isMe ? INTRO_COLS[i % INTRO_COLS.length] : "transparent", border: "none", cursor: "pointer", borderRadius: 8, padding: "2px 8px", transform: "scale(" + scale + ")", transition: "all .2s", outline: isMe ? "3px solid " + INTRO_COLS[i % INTRO_COLS.length] : "none" }}>
                        {job.title}
                      </button>);

              })}
                </div>
                {myJob && <div style={{ textAlign: "center", marginTop: 10, fontSize: 13.5, color: "var(--ink-2)" }}>Your role: <strong style={{ color: "var(--ink)" }}>{myJob}</strong> — visible to everyone in the group</div>}
              </div>
          }

            {/* SLIDE 4: What do you hope to learn? */}
            {slide.id === "expectations" &&
          <div style={{ marginTop: 20 }}>
                <div style={{ textAlign: "center", marginBottom: 16 }}>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 22, color: "var(--ink)", marginBottom: 4 }}>What do you hope to learn?</div>
                  <div style={{ fontSize: 14, color: "var(--ink-3)" }}>Share one learning goal — the trainer will address these during the programme</div>
                </div>
                <div style={{ borderRadius: 14, border: "1px solid var(--line)", overflow: "hidden" }}>
                  <textarea value={expectText} onChange={(e) => setExpectText(e.target.value)}
              placeholder="e.g. I want to understand how to manage stakeholders on complex projects…"
              style={{ width: "100%", minHeight: 100, resize: "none", border: "none", padding: "16px 18px", fontSize: 14, fontFamily: "var(--body)", lineHeight: 1.65, boxSizing: "border-box", outline: "none", color: "var(--ink)", background: "var(--surface)" }} />
                  <div style={{ display: "flex", justifyContent: "flex-end", padding: "10px 16px", borderTop: "1px solid var(--line)", background: "var(--surface-2)" }}>
                    <button className="btn btn-ghost" style={{ fontSize: 13 }} disabled={!expectText.trim()} onClick={() => toast("Expectation shared with trainer ✓", "check")}><Icon name="arrowR" size={14} />Share with trainer</button>
                  </div>
                </div>
                <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 8 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: ".07em" }}>Others shared:</div>
                  {["Prepare well for the IPMA-D exam", "Better understanding of stakeholder management", "How to apply the ICB4 in daily work"].map((ex, i) =>
              <div key={i} style={{ display: "flex", gap: 8, padding: "8px 12px", borderRadius: 9, background: "var(--surface-2)", border: "1px solid var(--line)", fontSize: 13, color: "var(--ink-2)" }}>
                      <span style={{ color: "var(--vh-blue-500)", fontWeight: 700, flex: "none" }}>›</span>{ex}
                    </div>
              )}
                </div>
              </div>
          }

            {/* SLIDE 5: Schedule overview */}
            {slide.id === "schedule" &&
          <div style={{ marginTop: 20 }}>
                <div style={{ textAlign: "center", marginBottom: 16 }}>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 22, color: "var(--ink)", marginBottom: 4 }}>Your 4-day programme</div>
                  <div style={{ fontSize: 14, color: "var(--ink-3)" }}>Amsterdam · 9–12 June 2026 · 09:00–17:00</div>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  {[
              { n: 1, date: "Mon 9 Jun", title: "Introduction & Project Preparation", color: "#c0392b", topics: ["IPMA & ICB4 overview", "Project Orientation (Ch. 3)", "Project Preparation (Ch. 4)", "Stakeholders & Risk"] },
              { n: 2, date: "Tue 10 Jun", title: "Project Definition & Delivery", color: "var(--vh-blue-500)", topics: ["Project Design & Scope (Ch. 5)", "Time, Resources, Finance", "Procurement (Ch. 6)", "Change Control"] },
              { n: 3, date: "Wed 11 Jun", title: "People Competencies", color: "#7a5ad6", topics: ["Self-management (Ch. 7)", "Leadership & Teamwork (Ch. 8)", "Negotiation & Conflict", "Resourcefulness"] },
              { n: 4, date: "Thu 12 Jun", title: "Perspective Competencies", color: "var(--vh-teal)", topics: ["Strategy (Ch. 9)", "Internal Context (Ch. 10)", "External Context (Ch. 11)", "Mock exam & review"] }].
              map((d) =>
              <div key={d.n} style={{ borderRadius: 12, overflow: "hidden", border: "1px solid var(--line)" }}>
                      <div style={{ padding: "11px 14px", background: d.color, position: "relative", overflow: "hidden" }}>
                        <div className="hexfield" style={{ opacity: .18 }} />
                        <div style={{ position: "relative", display: "flex", alignItems: "baseline", gap: 8 }}>
                          <span style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 11, color: "rgba(255,255,255,.7)", textTransform: "uppercase", letterSpacing: ".1em" }}>Day {d.n} · {d.date}</span>
                        </div>
                        <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 14, color: "#fff", lineHeight: 1.2, marginTop: 3 }}>{d.title}</div>
                      </div>
                      <div style={{ padding: "10px 14px", display: "flex", flexDirection: "column", gap: 5 }}>
                        {d.topics.map((t, i) => <div key={i} style={{ display: "flex", gap: 7, fontSize: 12.5, color: "var(--ink-2)" }}><span style={{ color: d.color, fontWeight: 700, flex: "none" }}>›</span>{t}</div>)}
                      </div>
                    </div>
              )}
                </div>
              </div>
          }

            {/* nav */}
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 18 }}>
              <button className="btn btn-outline" style={{ fontSize: 13 }} disabled={si === 0} onClick={prev}><Icon name="chevL" size={14} />Back</button>
              <div style={{ flex: 1, textAlign: "center", fontSize: 13, color: "var(--ink-3)", fontWeight: 600 }}>{si + 1} / {total}</div>
              <button className={"btn " + (si === total - 1 ? "btn-pri" : "btn-acc")} style={{ fontSize: 13 }} onClick={next}>
                {si === total - 1 ? <><Icon name="check" size={14} />Complete intro</> : <>Next<Icon name="arrowR" size={14} /></>}
              </button>
            </div>
          </div>
        </div>
      }
    </div>);

}

function IPMAChapterRow({ ch, onStart }) {
  const defaultOpen = ch.status === "active" || ch.n === 1;
  const [open, setOpen] = useState(defaultOpen);
  const dotBg = ch.status === "done" ? "var(--vh-teal)" : ch.status === "active" ? "var(--vh-orange)" : "transparent";
  const dotBdr = ch.status === "done" ? "var(--vh-teal)" : ch.status === "active" ? "var(--vh-orange)" : "var(--line)";
  const btnLabel = ch.status === "active" ? "Continue" : ch.status === "done" ? null : "Start";
  return (
    <div style={{ display: "flex", gap: 0 }}>
      <div style={{ width: 34, display: "flex", flexDirection: "column", alignItems: "center", flex: "none" }}>
        <div style={{ width: 16, height: 16, borderRadius: "50%", marginTop: 16, flex: "none", zIndex: 1, background: dotBg, border: "2px solid " + dotBdr, display: "grid", placeItems: "center" }}>
          {ch.status === "done" && <Icon name="check" size={9} style={{ color: "#fff" }} />}
        </div>
        <div style={{ flex: 1, width: 2, background: "var(--line-2)", minHeight: 20 }} />
      </div>
      <div style={{ flex: 1, paddingBottom: 10, minWidth: 0 }}>
        <button onClick={() => setOpen((o) => !o)} style={{ display: "flex", width: "100%", alignItems: "center", gap: 12, padding: "10px 0", background: "none", textAlign: "left", cursor: "pointer" }}>
          <span style={{ flex: 1, fontSize: 18, fontWeight: 700, color: ch.status === "locked" ? "var(--ink-2)" : "var(--ink)", lineHeight: 1.2 }}>Chapter {ch.n} – {ch.title}</span>
          {ch.status === "done" && <span className="tag" style={{ background: "color-mix(in oklab,var(--vh-teal),transparent 84%)", color: "var(--vh-teal)", flex: "none" }}><Icon name="check" size={12} />Done</span>}
          {btnLabel && <button className={"btn " + (ch.status === "active" ? "btn-acc" : "btn-pri")} style={{ fontSize: 12.5, padding: "9px 18px", flex: "none" }} onClick={(e) => {e.stopPropagation();onStart && onStart(ch);}}>{btnLabel}</button>}
          <Icon name={open ? "chevD" : "chevD"} size={16} style={{ color: "var(--ink-3)", flex: "none", transform: open ? "none" : "rotate(-90deg)" }} />
        </button>
        {open &&
        <div className="card" style={{ overflow: "hidden", marginBottom: 6 }}>
            {ch.n === 1 && <IPMAGeneralIntroContent />}
            {ch.blurb && <div style={{ display: "flex", gap: 16, padding: "16px 20px", borderBottom: ch.lessons ? "1px solid var(--line)" : "none" }}><div style={{ width: 50, height: 50, flex: "none", borderRadius: 13, background: "var(--surface-2)", display: "grid", placeItems: "center" }}><Icon name="graduation" size={26} style={{ color: "var(--ink-3)" }} /></div><p style={{ fontSize: 13.5, lineHeight: 1.65, color: "var(--ink-2)", margin: 0 }}>{ch.blurb}</p></div>}
            {ch.lessons && ch.lessons.map((lesson, li) =>
          <div key={li} style={{ borderTop: "1px solid var(--line)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 13, padding: "14px 20px" }}>
                  <div style={{ width: 30, height: 30, borderRadius: 8, flex: "none", display: "grid", placeItems: "center", background: lesson.status === "active" ? "color-mix(in oklab,var(--vh-orange),transparent 86%)" : "var(--surface-2)" }}>
                    <Icon name={lesson.kind === "exam" ? "target" : "layers"} size={15} style={{ color: lesson.status === "active" ? "var(--vh-orange)" : "var(--ink-3)" }} />
                  </div>
                  <span style={{ flex: 1, fontSize: 14.5, fontWeight: 700 }}>Chapter {ch.n} – {lesson.title}</span>
                  <span className="dim" style={{ fontSize: 12.5 }}>{lesson.mins}m</span>
                  <button className={"btn " + (lesson.status === "active" ? "btn-acc" : lesson.status === "locked" ? "btn-outline" : "btn-pri")} style={{ fontSize: 12.5, padding: "8px 16px" }} disabled={lesson.status === "locked"}>
                    {lesson.status === "active" ? "Continue" : lesson.status === "locked" ? "Locked" : "Start"}
                  </button>
                </div>
                {lesson.topics &&
            <div style={{ padding: "0 20px 16px 63px", display: "flex", flexDirection: "column", gap: 3 }}>
                    {lesson.topics.map((topic, ti) =>
              <div key={ti} style={{ display: "flex", gap: 8, fontSize: 13, color: "var(--vh-blue-500)" }}>
                        <span style={{ color: "var(--vh-orange)", fontWeight: 700, flex: "none" }}>•</span><span>{topic}</span>
                      </div>
              )}
                  </div>
            }
              </div>
          )}
          </div>
        }
      </div>
    </div>);

}

/* ──────────────────────────────────────────── COURSEWARE PRESENTATION ── */

const PPTX_DAYS = [
{ day: 1, slides: "1–68", count: 68, color: "#c0392b",
  title: "Introduction & Project Preparation",
  topics: ["IPMA overview & certification levels", "ICB4 competence framework", "Project Orientation (Ch. 3)", "Project Preparation Stage (Ch. 4)", "Stakeholders, Organisation, Risk & Opportunity"] },
{ day: 2, slides: "69–171", count: 103, color: "var(--vh-blue-500)",
  title: "Project Definition & Delivery",
  topics: ["Project Definition Stage (Ch. 5)", "Scope, Quality, Time, Resources, Finance", "Procurement & Partnership (Ch. 6)", "Change Control & Reporting", "Project Closure"] },
{ day: 3, slides: "172–240", count: 69, color: "#7a5ad6",
  title: "People Competencies",
  topics: ["Self-management & Integrity (Ch. 7)", "Communication & Relationships (Ch. 8)", "Leadership & Teamwork", "Negotiation & Conflict", "Resourcefulness & Results Orientation"] },
{ day: 4, slides: "241–319", count: 79, color: "var(--vh-teal)",
  title: "Perspective Competencies",
  topics: ["Strategy & Vision (Ch. 9)", "Programme & Portfolio Management", "Internal Context: Organisation Theory (Ch. 10)", "External Context: Sustainability (Ch. 11)", "Compliance, Power & Culture"] }];


function IPMAPresentationView({ toast, onViewSlides, onKahoot, onWordCloud }) {
  return (
    <div className="vh-in">
      {/* header */}
      <div className="card" style={{ padding: 0, overflow: "hidden", marginBottom: 20 }}>
        <div style={{ padding: "22px 24px", background: "linear-gradient(120deg,#1c1c2e,#2d1b4e)", position: "relative", overflow: "hidden" }}>
          <div className="hexfield" style={{ opacity: .2 }} />
          <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
            <div className="hex-flat" style={{ width: 56, height: 62, flex: "none", clipPath: "polygon(50% 0,93% 25%,93% 75%,50% 100%,7% 75%,7% 25%)", background: "var(--vh-orange)", display: "grid", placeItems: "center" }}>
              <Icon name="pptx" size={28} style={{ color: "#231f20" }} />
            </div>
            <div style={{ flex: 1 }}>
              <div className="eyebrow" style={{ color: "rgba(255,255,255,.7)", marginBottom: 5 }}>Courseware · Van Haren Publishing</div>
              <h2 style={{ fontSize: 22, fontWeight: 700, color: "#fff", margin: 0 }}>IPMA-D Training Presentation V1.2</h2>
              <p style={{ color: "rgba(255,255,255,.75)", fontSize: 13.5, marginTop: 5 }}>Complete classroom slide deck — 319 slides across 4 training days</p>
            </div>
            <div style={{ display: "flex", gap: 20, flexWrap: "wrap" }}>
              {[["319", "Slides"], ["4", "Days"], ["~16h", "Content"]].map(([v, l]) =>
              <div key={l} style={{ textAlign: "center" }}>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 26, color: "#fff" }}>{v}</div>
                  <div style={{ fontSize: 11, color: "rgba(255,255,255,.6)", textTransform: "uppercase", letterSpacing: ".08em", fontWeight: 600 }}>{l}</div>
                </div>
              )}
            </div>
          </div>
          <div style={{ position: "relative", display: "flex", gap: 10, marginTop: 18 }}>
            <button className="btn btn-acc" onClick={onViewSlides}><Icon name="play" size={16} />View live slides</button>
            <button className="btn" style={{ background: "rgba(255,255,255,.14)", color: "#fff" }} onClick={() => toast("Downloading PPTX…", "download")}><Icon name="download" size={16} />Download PPTX</button>
            <button className="btn" style={{ background: "rgba(255,255,255,.14)", color: "#fff" }} onClick={onKahoot}><Icon name="dice" size={16} />Gamify slides 15–16</button>
          </div>
        </div>
      </div>

      {/* intro section */}
      <div className="card" style={{ padding: 0, overflow: "hidden", marginBottom: 20 }}>
        <div style={{ padding: "18px 22px 16px", background: "linear-gradient(120deg,#2d0a6e,#46178f)", position: "relative", overflow: "hidden" }}>
          <div className="hexfield" style={{ opacity: .14 }} />
          <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
            <div style={{ flex: 1 }}>
              <div className="eyebrow" style={{ color: "rgba(255,255,255,.65)", marginBottom: 5 }}>Introduction · Before Day 1</div>
              <h3 style={{ fontSize: 20, fontWeight: 800, color: "#fff", margin: "0 0 6px" }}>Welcome &amp; Warm-up</h3>
              <p style={{ fontSize: 13.5, color: "rgba(255,255,255,.7)", margin: 0, lineHeight: 1.5 }}>Start the training with a group warm-up. Introduce yourself, meet your trainer, and share your role and challenges in a live word cloud.</p>
            </div>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              <button className="btn" style={{ background: "rgba(255,255,255,.15)", color: "#fff", fontSize: 13 }} onClick={onViewSlides}>
                <Icon name="play" size={15} />Start presentation
              </button>
            </div>
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", borderTop: "1px solid var(--line)" }}>
          {[["☁️", "Who's in the room?", "Live word cloud of roles"], ["🎯", "Biggest PM challenges", "Group priorities revealed"], ["📅", "Programme overview", "4 days · Amsterdam"]].map(([ic, t, s], i) =>
          <div key={i} style={{ padding: "13px 16px", borderRight: i < 2 ? "1px solid var(--line)" : "none", display: "flex", gap: 10, alignItems: "flex-start" }}>
              <span style={{ fontSize: 20, flex: "none", marginTop: 1 }}>{ic}</span>
              <div><div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink)" }}>{t}</div><div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{s}</div></div>
            </div>
          )}
        </div>
      </div>

      {/* day cards */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        {PPTX_DAYS.map((d) =>
        <div key={d.day} className="card" style={{ padding: 0, overflow: "hidden" }}>
            <div style={{ padding: "14px 18px 12px", background: d.color, position: "relative", overflow: "hidden" }}>
              <div className="hexfield" style={{ opacity: .18 }} />
              <div style={{ position: "relative", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <div>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", color: "rgba(255,255,255,.8)" }}>Day {d.day}</div>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 17, color: "#fff", marginTop: 3, lineHeight: 1.2 }}>{d.title}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 22, color: "#fff" }}>{d.count}</div>
                  <div style={{ fontSize: 11, color: "rgba(255,255,255,.7)", fontWeight: 600 }}>slides {d.slides}</div>
                </div>
              </div>
            </div>
            <div style={{ padding: "14px 18px" }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 5, marginBottom: 14 }}>
                {d.topics.map((t, i) =>
              <div key={i} style={{ display: "flex", gap: 8, fontSize: 13, color: "var(--ink-2)" }}>
                    <span style={{ color: d.color, fontWeight: 700, flex: "none" }}>›</span><span>{t}</span>
                  </div>
              )}
              </div>
              <button className="btn btn-outline" style={{ width: "100%", fontSize: 13 }} onClick={() => toast(`Opening Day ${d.day}…`, "play")}>
                <Icon name="play" size={14} />Start Day {d.day}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>);

}

/* ─────────────────────────────────────────────────── SELF ASSESSMENT ── */

function IPMASelfAssessment({ toast }) {
  const total = IPMA_SA_GROUPS.reduce((s, g) => s + g.ces.length, 0);
  const initRatings = {};
  IPMA_SA_GROUPS.forEach((g) => g.ces.forEach((ce) => {initRatings[ce] = 0;}));
  const [ratings, setRatings] = useState(initRatings);
  const [stage, setStage] = useState("form"); // form | done
  const [open, setOpen] = useState({ 0: true, 1: false, 2: false });

  /* Hosted course app — published from the Educator backend (Course Products → Self-Assessment).
     Prefers the latest imported package for this course; falls back to the bundled sample. */
  const [hosted, setHosted] = useState(null);
  const [useApp, setUseApp] = useState(true);
  useEffect(() => {
    let live = true;
    (async () => {
      let h = { url: "apps/ipma-self-assessment/index.html", name: "IPMA ICB4 Competence Self-Assessment", imported: false };
      try {
        if (window.AppStore && window.AppHost) {
          const all = (await window.AppStore.list()) || [];
          const rec = all.filter((a) => /^app_ipma-d_assessment_/.test(String(a.id))).sort((a, c) => (c.created || 0) - (a.created || 0))[0];
          if (rec) h = { url: await window.AppHost.buildUrl(rec), name: rec.name, imported: true };
        }
      } catch (e) {}
      if (live) setHosted(h);
    })();
    return () => {live = false;};
  }, []);

  const rated = Object.values(ratings).filter((v) => v > 0).length;
  const pct = Math.round(rated / total * 100);

  function setRating(ce, lvl) {
    setRatings((r) => ({ ...r, [ce]: r[ce] === lvl ? 0 : lvl }));
  }

  if (useApp) {
    return (
      <div className="vh-in">
        {hosted ?
        <iframe src={hosted.url} title={hosted.name} style={{ width: "100%", height: "calc(100vh - 210px)", minHeight: 600, border: "1px solid var(--line)", borderRadius: "var(--r-lg)", background: "#fff", display: "block" }}></iframe> :
        <div style={{ height: 300, display: "grid", placeItems: "center", color: "var(--ink-3)", fontWeight: 600, fontSize: 14 }}>Loading course app…</div>}
      </div>);
  }

  if (stage === "done") {
    const groupScores = IPMA_SA_GROUPS.map((g) => ({
      label: g.short, color: g.color,
      avg: g.ces.reduce((s, ce) => s + (ratings[ce] || 0), 0) / (g.ces.length * 3) * 100
    }));
    return (
      <div className="vh-in">
        <div style={{ background: "#f8f9fb", borderRadius: "var(--r-lg)", border: "1px solid var(--line)", padding: "28px 32px", marginBottom: 20 }}>
          <div style={{ display: "flex", gap: 24, alignItems: "center", flexWrap: "wrap", marginBottom: 24 }}>
            <div>
              <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 26, marginBottom: 4 }}>Your IPMA Self Assessment</div>
              <p style={{ fontSize: 14, color: "var(--ink-2)", margin: 0 }}>Based on ICB4 · {rated} of {total} competence elements rated · {new Date().toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" })}</p>
            </div>
            <div style={{ marginLeft: "auto", display: "flex", gap: 10 }}>
              <button className="btn btn-outline" style={{ fontSize: 13 }} onClick={() => setStage("form")}><Icon name="refresh" size={15} />Edit ratings</button>
              <button className="btn btn-pri" style={{ fontSize: 13 }} onClick={() => toast("Generating PDF report…", "download")}><Icon name="download" size={15} />Download report</button>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14 }}>
            {groupScores.map((gs) =>
            <div key={gs.label} style={{ background: "#fff", borderRadius: 14, padding: "18px 20px", border: "1px solid var(--line)" }}>
                <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 13, textTransform: "uppercase", letterSpacing: ".06em", color: gs.color, marginBottom: 10 }}>{gs.label}</div>
                <div style={{ fontSize: 30, fontWeight: 800, fontFamily: "var(--display)", color: "var(--ink)" }}>{Math.round(gs.avg)}%</div>
                <div style={{ height: 7, borderRadius: 999, background: "var(--line)", marginTop: 10, overflow: "hidden" }}>
                  <div style={{ height: "100%", width: gs.avg + "%", background: gs.color, borderRadius: 999, transition: "width .6s ease" }} />
                </div>
                <p style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 8 }}>
                  {gs.avg < 33 ? "Focus area — study recommended" : gs.avg < 66 ? "Developing — keep going" : "Strong foundation — aim higher"}
                </p>
              </div>
            )}
          </div>
        </div>
        <div style={{ background: "#fff", borderRadius: "var(--r-lg)", border: "1px solid var(--line)", padding: "22px 28px" }}>
          <h3 style={{ fontSize: 17, fontWeight: 700, marginBottom: 16 }}>Recommended focus areas</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {IPMA_SA_GROUPS.flatMap((g) => g.ces.map((ce) => ({ ce, g, r: ratings[ce] || 0 }))).filter((x) => x.r <= 1).slice(0, 6).map(({ ce, g }) =>
            <div key={ce} style={{ display: "flex", alignItems: "center", gap: 13, padding: "11px 15px", borderRadius: 11, background: "#f8f9fb", border: "1px solid var(--line)" }}>
                <div style={{ width: 8, height: 8, borderRadius: "50%", background: g.color, flex: "none" }} />
                <span style={{ flex: 1, fontSize: 14, fontWeight: 600 }}>{ce}</span>
                <span style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em" }}>{g.short}</span>
                <button className="btn btn-ghost" style={{ fontSize: 12, padding: "6px 12px" }} onClick={() => toast("Opening course chapter for " + ce, "book")}>Study →</button>
              </div>
            )}
          </div>
        </div>
      </div>);

  }

  return (
    <div className="vh-in">
      {/* header — distinct design */}
      <div style={{ background: "#f8f9fb", borderRadius: "var(--r-lg)", border: "1px solid var(--line-2)", padding: "22px 28px", marginBottom: 20 }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 18, flexWrap: "wrap" }}>
          <div style={{ flex: 1, minWidth: 240 }}>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "#fff", border: "1px solid var(--line)", borderRadius: 999, padding: "4px 12px 4px 8px", marginBottom: 12 }}>
              <div style={{ width: 20, height: 20, borderRadius: "50%", background: "var(--vh-orange)", display: "grid", placeItems: "center" }}><Icon name="target" size={11} style={{ color: "#fff" }} /></div>
              <span style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", color: "var(--ink-2)" }}>IPMA ICB4 · Self Assessment</span>
            </div>
            <h2 style={{ fontFamily: "var(--display)", fontSize: 22, fontWeight: 800, margin: "0 0 8px", color: "var(--ink)" }}>Create IPMA Self Assessment</h2>
            <p style={{ fontSize: 14, color: "var(--ink-2)", lineHeight: 1.6, margin: 0 }}>Rate your current level for each of the 28 competence elements. Your results generate a personalised gap analysis and study plan.</p>
          </div>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 8 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, background: "#fff", border: "1px solid var(--line)", borderRadius: 12, padding: "12px 18px" }}>
              <Ring value={pct} size={48} color="var(--vh-orange)">
                <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 14, textAlign: "center" }}>{pct}%</div>
              </Ring>
              <div>
                <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 15 }}>{rated} / {total}</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)" }}>completed</div>
              </div>
            </div>
            <button className="btn btn-acc" style={{ fontSize: 13 }} disabled={rated < 5} onClick={() => {if (rated < 5) {toast("Rate at least 5 competencies to continue", "target");} else {setStage("done");}}}>
              <Icon name="graduation" size={16} />Generate report
            </button>
            <button className="btn btn-ghost" style={{ fontSize: 12.5 }} onClick={() => setUseApp(true)}><Icon name="globe" size={14} />Open course app</button>
          </div>
        </div>
      </div>

      {/* Rating key */}
      <div style={{ display: "flex", gap: 8, marginBottom: 18, flexWrap: "wrap" }}>
        {SA_LEVELS.map((lv, li) =>
        <div key={lv} style={{ display: "flex", alignItems: "center", gap: 6, padding: "5px 12px", borderRadius: 999, background: "#fff", border: "1px solid var(--line)", fontSize: 12.5, fontWeight: 600, color: "var(--ink-2)" }}>
            <div style={{ width: 14, height: 14, borderRadius: "50%", background: SA_LEVEL_COLORS[li] }} />
            {lv === "—" ? "Not rated" : `Level ${lv} · ${SA_LEVEL_LABELS[li].split(" (")[0]}`}
          </div>
        )}
      </div>

      {/* Groups */}
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {IPMA_SA_GROUPS.map((g, gi) => {
          const groupRated = g.ces.filter((ce) => ratings[ce] > 0).length;
          return (
            <div key={gi} style={{ background: "#fff", borderRadius: "var(--r-lg)", border: "1.5px solid var(--line)", overflow: "hidden" }}>
              <button
                onClick={() => setOpen((o) => ({ ...o, [gi]: !o[gi] }))}
                style={{ width: "100%", display: "flex", alignItems: "center", gap: 14, padding: "16px 20px", background: "none", textAlign: "left", cursor: "pointer", borderBottom: open[gi] ? "1px solid var(--line)" : "none" }}>
                
                <div style={{ width: 32, height: 32, borderRadius: 9, flex: "none", display: "grid", placeItems: "center", background: g.color + "22" }}>
                  <Icon name={g.icon} size={17} style={{ color: g.color }} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 15, color: "var(--ink)" }}>{g.label}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{g.ces.length} competence elements · {groupRated} rated</div>
                </div>
                <div style={{ width: 80, marginRight: 16 }}>
                  <div style={{ height: 5, borderRadius: 999, background: "var(--line)", overflow: "hidden" }}>
                    <div style={{ height: "100%", width: groupRated / g.ces.length * 100 + "%", background: g.color, borderRadius: 999, transition: "width .3s" }} />
                  </div>
                </div>
                <Icon name="chevD" size={16} style={{ color: "var(--ink-3)", transform: open[gi] ? "none" : "rotate(-90deg)", transition: "transform .2s" }} />
              </button>
              {open[gi] &&
              <div>
                  {g.ces.map((ce, ci) => {
                  const val = ratings[ce] || 0;
                  return (
                    <div key={ci} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 20px", borderBottom: ci < g.ces.length - 1 ? "1px solid var(--line-2)" : "none", background: ci % 2 ? "#fafafa" : "#fff" }}>
                        <span style={{ flex: 1, fontSize: 13.5, fontWeight: 500, color: "var(--ink)" }}>{ce}</span>
                        <div style={{ display: "flex", gap: 5 }}>
                          {SA_LEVELS.slice(1).map((lv, li) =>
                        <button key={lv} onClick={() => setRating(ce, li + 1)}
                        style={{ width: 34, height: 34, borderRadius: "50%", border: "2px solid " + (val === li + 1 ? SA_LEVEL_COLORS[li + 1] : "var(--line)"), background: val === li + 1 ? SA_LEVEL_COLORS[li + 1] : "#fff", color: val === li + 1 ? "#fff" : "var(--ink-3)", fontFamily: "var(--display)", fontWeight: 800, fontSize: 13, cursor: "pointer", transition: "all .12s", display: "grid", placeItems: "center" }}>
                              {lv}
                            </button>
                        )}
                        </div>
                      </div>);

                })}
                </div>
              }
            </div>);

        })}
      </div>
    </div>);

}

/* ─────────────────────────────────────────────────────────── BOOK ── */

const BOOK_CHAPTERS = [
{ n: "1", title: "Project Management and the ICB4", pages: 18 },
{ n: "2", title: "Project Orientation", pages: 14 },
{ n: "3", title: "Project Preparation", pages: 22 },
{ n: "4", title: "Project Definition", pages: 28 },
{ n: "5", title: "Project Delivery", pages: 24 },
{ n: "6", title: "People Competencies", pages: 32 },
{ n: "7", title: "Perspective Competencies", pages: 26 },
{ n: "A", title: "Sample Exam Questions", pages: 16 }];


function IPMABookView({ toast, onOpenBook }) {
  const [readBook, setReadBook] = useState(null); // reading inside the course context
  const [opening, setOpening] = useState(false);

  /* open the same Reader as the menu — but stay inside the course overview */
  async function startReading() {
    if (opening) return;
    setOpening(true);
    let b = null;
    try {if (window.resolveLibraryBook) b = await window.resolveLibraryBook({ id: "ipma-prep", track: "IPMA-D® Certification" });} catch (e) {}
    setOpening(false);
    setReadBook(b || { id: "ipma-prep", title: "IPMA Individual Certification — Preparation Guide", author: "Van Haren Publishing", track: "IPMA-D® Certification", pages: 196, read: 0, mins: 14 });
  }

  const LibReader = window.Reader;
  if (readBook && LibReader) {
    return (
      <div style={{ height: "calc(100vh - 250px)", minHeight: 540 }}>
        <LibReader book={readBook} back={() => setReadBook(null)} backLabel="Book overview" toast={toast}
        action={{ label: "Open in Reader", icon: "book", onClick: onOpenBook }} />
      </div>);
  }

  return (
    <div className="vh-in">
      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 24, alignItems: "start" }}>
        {/* book cover */}
        <div>
          <div style={{ borderRadius: "var(--r-lg)", overflow: "hidden", boxShadow: "var(--shadow-lg)", marginBottom: 16, aspectRatio: "3/4", background: "linear-gradient(160deg,var(--vh-navy) 0%,#0a1429 100%)", display: "flex", flexDirection: "column", justifyContent: "flex-end", padding: 22, position: "relative" }}>
            <div className="hexfield" style={{ opacity: .25 }} />
            <div style={{ position: "relative" }}>
              <div className="hex-flat" style={{ width: 46, height: 46, clipPath: "polygon(50% 0,93% 25%,93% 75%,50% 100%,7% 75%,7% 25%)", background: "var(--vh-orange)", display: "grid", placeItems: "center", marginBottom: 14 }}>
                <Icon name="book" size={24} style={{ color: "#231f20" }} />
              </div>
              <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 17, color: "#fff", lineHeight: 1.2, marginBottom: 8 }}>IPMA Individual Certification</div>
              <div style={{ fontSize: 13, color: "rgba(255,255,255,.7)", lineHeight: 1.4, marginBottom: 12 }}>Preparation Guide & Study Companion</div>
              <div style={{ fontSize: 11, color: "rgba(255,255,255,.5)", fontWeight: 600, letterSpacing: ".08em" }}>VAN HAREN PUBLISHING</div>
            </div>
          </div>
          <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.7 }}>
            <div><b>ISBN</b> 978-94-018-1092-0</div>
            <div><b>Publisher</b> Van Haren Publishing</div>
            <div><b>Edition</b> V1.2 · English</div>
            <div><b>Pages</b> 196</div>
          </div>
        </div>

        {/* content */}
        <div>
          <div className="card" style={{ padding: "20px 24px", marginBottom: 16 }}>
            <h3 style={{ fontSize: 18, fontWeight: 700, marginBottom: 6 }}>IPMA Individual Certification — Preparation Guide</h3>
            <p className="muted" style={{ fontSize: 14, lineHeight: 1.65, marginBottom: 16 }}>This preparation guide provides a complete study companion for the IPMA-D certification exam. It covers all 28 competence elements of the ICB4 framework with theory summaries, key definitions, and practice questions.</p>
            <div style={{ display: "flex", gap: 10 }}>
              <button className="btn btn-pri" onClick={startReading}><Icon name="book" size={16} />{opening ? "Opening…" : "Read book"}</button>
              <button className="btn btn-outline" onClick={onOpenBook}><Icon name="share" size={15} />Open in Reader</button>
              <button className="btn btn-ghost" onClick={() => toast("Added to reading list", "check")}><Icon name="check" size={16} />Add to reading list</button>
            </div>
          </div>

          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            <div style={{ padding: "13px 20px", borderBottom: "1px solid var(--line)", fontFamily: "var(--display)", fontWeight: 700, fontSize: 14 }}>Table of contents</div>
            {BOOK_CHAPTERS.map((ch, i) =>
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 20px", borderBottom: i < BOOK_CHAPTERS.length - 1 ? "1px solid var(--line-2)" : "none", background: i % 2 ? "var(--surface-2)" : "var(--surface)" }}>
                <div style={{ width: 30, height: 30, borderRadius: 8, flex: "none", display: "grid", placeItems: "center", background: "var(--vh-blue-50)", fontFamily: "var(--display)", fontWeight: 700, fontSize: 13, color: "var(--vh-blue-500)" }}>{ch.n}</div>
                <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{ch.title}</span>
                <span className="dim" style={{ fontSize: 12.5 }}>{ch.pages} pp.</span>
                <button className="btn btn-outline" style={{ fontSize: 12, padding: "6px 13px" }} onClick={startReading}>Read</button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>);

}

/* ───────────────────────────────────────────── MAIN COURSE DETAIL ── */

const IPMA_PRODUCT_TABS = [
{ id: "elearning", label: "Study Content", icon: "graduation" },
{ id: "assessment", label: "Self Assessment", icon: "layers" },
{ id: "courseware", label: "Courseware", icon: "pptx" },
{ id: "memo", label: "Memo Trainer", icon: "brain" },
{ id: "exam", label: "Exam Trainer", icon: "target" },
{ id: "book", label: "Book", icon: "book" },
{ id: "evaluation", label: "Evaluation", icon: "medal" }];


/* ── SESSION DATA ── */
const IPMA_SESSIONS = [
{ id: 1, label: "Upcoming", type: "physical", city: "Amsterdam", venue: "Van Haren Academy · Hogehilweg 5",
  days: [
  { date: "Mon 9 Jun 2026", time: "09:00–17:00", topic: "Day 1 · Introduction & Project Preparation" },
  { date: "Tue 10 Jun 2026", time: "09:00–17:00", topic: "Day 2 · Project Definition & Delivery" },
  { date: "Wed 11 Jun 2026", time: "09:00–17:00", topic: "Day 3 · People Competencies" },
  { date: "Thu 12 Jun 2026", time: "09:00–17:00", topic: "Day 4 · Perspective Competencies" }],

  trainer: "Rik van der Berg", trainerRole: "IPMA-A Certified Trainer",
  spots: 3, enrolled: true },
{ id: 2, label: "Virtual", type: "virtual", city: "Online (Zoom)",
  days: [
  { date: "Mon 7 Jul 2026", time: "09:00–13:00", topic: "Day 1 · Introduction & Project Preparation" },
  { date: "Tue 8 Jul 2026", time: "09:00–13:00", topic: "Day 2 · Project Definition & Delivery" },
  { date: "Wed 9 Jul 2026", time: "09:00–13:00", topic: "Day 3 · People Competencies" },
  { date: "Thu 10 Jul 2026", time: "09:00–13:00", topic: "Day 4 · Perspective Competencies" }],

  trainer: "Sophie de Wit", trainerRole: "IPMA-B Certified Trainer",
  spots: 12, enrolled: false }];


const IPMA_RECORDINGS = [
{ id: 1, title: "IPMA-D Training · June 2025", type: "physical", city: "Amsterdam",
  days: [
  { n: 1, duration: "7h 12m", topic: "Introduction & Project Preparation" },
  { n: 2, duration: "7h 45m", topic: "Project Definition & Delivery" },
  { n: 3, duration: "6h 58m", topic: "People Competencies" },
  { n: 4, duration: "7h 22m", topic: "Perspective Competencies" }]
},
{ id: 2, title: "IPMA-D Training · February 2025", type: "virtual", city: "Online",
  days: [
  { n: 1, duration: "4h 04m", topic: "Introduction & Project Preparation" },
  { n: 2, duration: "4h 18m", topic: "Project Definition & Delivery" },
  { n: 3, duration: "3h 55m", topic: "People Competencies" },
  { n: 4, duration: "4h 08m", topic: "Perspective Competencies" }]
}];


const IPMA_HOMEWORK = [
{ ch: "Ch. 3", type: "read", text: "Read 'Project Management by ICB4' Chapter 2 (Project Orientation) pp. 25–40" },
{ ch: "Ch. 3", type: "practice", text: "Complete the 10 self-check questions at the end of Chapter 2" },
{ ch: "Ch. 4", type: "read", text: "Read Chapter 3 (Project Preparation) pp. 41–66 before Day 2" },
{ ch: "Ch. 4", type: "reflect", text: "Write a brief stakeholder analysis for a project you have been involved in" },
{ ch: "Ch. 5", type: "read", text: "Read Chapter 4 (Project Definition) pp. 67–102" },
{ ch: "All", type: "exam", text: "Attempt at least 2 mock exams in the Exam Trainer before the final day" }];


/* ── SESSION SIDEBAR ── */
function IPMASessionSidebar({ toast, onViewSlides }) {
  const [recOpen, setRecOpen] = useState(null);
  const session = IPMA_SESSIONS[0];
  const now = new Date();
  const nextDay = session.days[0];
  const daysUntil = Math.ceil((new Date("2026-06-09") - now) / 86400000);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>

      {/* LIVE SESSION CARD */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ padding: "14px 18px 12px", background: "linear-gradient(135deg,#1d3d7c,#0a1429)", position: "relative", overflow: "hidden" }}>
          <div className="hexfield" style={{ opacity: .15 }} />
          <div style={{ position: "relative" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
              <div style={{ width: 8, height: 8, borderRadius: "50%", background: "#4ade80", boxShadow: "0 0 6px #4ade80", animation: "pulse 1.5s infinite" }} />
              <span style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: ".1em", textTransform: "uppercase", color: "rgba(255,255,255,.7)" }}>Enrolled · Upcoming</span>
            </div>
            <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 17, color: "#fff", lineHeight: 1.2, marginBottom: 6 }}>IPMA-D Training · Jun 2026</div>
            <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: "rgba(255,255,255,.75)" }}>
              <Icon name="globe" size={14} />
              <span style={{ fontWeight: 600 }}>{session.type === "physical" ? "📍 Physical" : "🖥 Virtual"}</span>
              <span style={{ opacity: .6 }}>·</span>
              <span>{session.city}</span>
            </div>
            {session.type === "physical" && <div style={{ fontSize: 12, color: "rgba(255,255,255,.5)", marginTop: 3 }}>{session.venue}</div>}
          </div>
        </div>

        {/* countdown */}
        <div style={{ padding: "12px 18px", borderBottom: "1px solid var(--line)", background: "var(--surface-2)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div style={{ fontSize: 13, color: "var(--ink-2)" }}>Starts in</div>
            <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 22, color: "var(--vh-orange)" }}>{daysUntil} days</div>
          </div>
          <div style={{ height: 5, borderRadius: 9, background: "var(--line)", marginTop: 8, overflow: "hidden" }}>
            <div style={{ height: "100%", width: Math.max(4, Math.min(100, 100 - daysUntil / 30 * 100)) + "%", background: "var(--vh-orange)", borderRadius: 9 }} />
          </div>
        </div>

        {/* agenda days */}
        <div style={{ padding: "12px 18px" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Agenda</div>
          {session.days.map((d, i) =>
          <div key={i} style={{ display: "flex", gap: 10, padding: "8px 0", borderBottom: i < session.days.length - 1 ? "1px solid var(--line-2)" : "none" }}>
              <div style={{ width: 22, height: 22, borderRadius: 6, background: i === 0 ? "var(--vh-orange)" : "var(--surface-3)", display: "grid", placeItems: "center", flex: "none", fontFamily: "var(--display)", fontWeight: 800, fontSize: 11, color: i === 0 ? "#231f20" : "var(--ink-3)" }}>{i + 1}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{d.topic}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>{d.date} · {d.time}</div>
              </div>
            </div>
          )}
        </div>

        {/* trainer */}
        <div style={{ padding: "12px 18px", borderTop: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 10 }}>
          <div className="avatar" style={{ width: 32, height: 32, borderRadius: 9, fontSize: 13 }}>RB</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 700 }}>{session.trainer}</div>
            <div className="dim" style={{ fontSize: 11.5 }}>{session.trainerRole}</div>
          </div>
          <button className="btn btn-ghost" style={{ fontSize: 12, padding: "6px 10px" }} onClick={() => toast("Opening trainer profile…", "graduation")}>
            <Icon name="arrowR" size={12} />
          </button>
        </div>

        {/* actions */}
        <div style={{ padding: "12px 18px", borderTop: "1px solid var(--line)", display: "flex", flexDirection: "column", gap: 8 }}>
          <button className="btn btn-pri" style={{ fontSize: 13 }} onClick={onViewSlides}><Icon name="play" size={15} />Join live session</button>
          <button className="btn btn-outline" style={{ fontSize: 13 }} onClick={() => toast("Opening trainer window…", "graduation")}><Icon name="graduation" size={15} />Trainer window</button>
          <button className="btn btn-ghost" style={{ fontSize: 13 }} onClick={() => toast("Opening location in Maps…", "globe")}><Icon name="globe" size={15} />View location · Amsterdam</button>
        </div>
      </div>

      {/* RECORDINGS */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ padding: "13px 18px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 8 }}>
          <Icon name="play" size={15} style={{ color: "var(--vh-orange)" }} />
          <span style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 14 }}>Previous recordings</span>
        </div>
        {IPMA_RECORDINGS.map((rec, ri) =>
        <div key={rec.id}>
            <button onClick={() => setRecOpen(recOpen === rec.id ? null : rec.id)}
          style={{ width: "100%", display: "flex", alignItems: "center", gap: 10, padding: "12px 18px", background: "none", textAlign: "left", cursor: "pointer", borderBottom: "1px solid var(--line-2)" }}>
              <div style={{ width: 28, height: 28, borderRadius: 7, flex: "none", background: rec.type === "virtual" ? "color-mix(in oklab,var(--vh-blue-500),transparent 82%)" : "color-mix(in oklab,var(--vh-orange),transparent 82%)", display: "grid", placeItems: "center" }}>
                <Icon name="play" size={14} style={{ color: rec.type === "virtual" ? "var(--vh-blue-500)" : "var(--vh-orange)" }} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{rec.title}</div>
                <div className="dim" style={{ fontSize: 11.5 }}>{rec.type === "physical" ? "Physical · " + rec.city : "Virtual · " + rec.city} · {rec.days.length} days</div>
              </div>
              <Icon name="chevD" size={14} style={{ color: "var(--ink-3)", transform: recOpen === rec.id ? "none" : "rotate(-90deg)", transition: "transform .2s", flex: "none" }} />
            </button>
            {recOpen === rec.id &&
          <div style={{ background: "var(--surface-2)", padding: "8px 18px 12px" }}>
                {rec.days.map((d, di) =>
            <div key={di} style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 0", borderBottom: di < rec.days.length - 1 ? "1px solid var(--line-2)" : "none" }}>
                    <span style={{ fontSize: 11.5, color: "var(--ink-3)", fontWeight: 700, width: 40, flex: "none" }}>Day {d.n}</span>
                    <span style={{ flex: 1, fontSize: 13, color: "var(--ink-2)" }}>{d.topic}</span>
                    <span className="dim" style={{ fontSize: 11.5, flex: "none" }}>{d.duration}</span>
                    <button className="btn btn-outline" style={{ fontSize: 11.5, padding: "4px 10px", flex: "none" }} onClick={() => toast("Opening recording Day " + d.n + "…", "play")}>Watch</button>
                  </div>
            )}
              </div>
          }
          </div>
        )}
      </div>

      {/* HOMEWORK */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ padding: "13px 18px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 8 }}>
          <Icon name="book" size={15} style={{ color: "var(--vh-blue-500)" }} />
          <span style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 14 }}>Homework &amp; reading</span>
        </div>
        {IPMA_HOMEWORK.map((hw, i) =>
        <div key={i} style={{ display: "flex", gap: 10, padding: "10px 18px", borderBottom: i < IPMA_HOMEWORK.length - 1 ? "1px solid var(--line-2)" : "none", alignItems: "flex-start" }}>
            <div style={{ width: 22, height: 22, borderRadius: 6, flex: "none", marginTop: 1, display: "grid", placeItems: "center",
            background: hw.type === "read" ? "color-mix(in oklab,var(--vh-blue-500),transparent 86%)" : hw.type === "exam" ? "color-mix(in oklab,var(--vh-orange),transparent 86%)" : "color-mix(in oklab,var(--vh-teal),transparent 86%)" }}>
              <Icon name={hw.type === "read" ? "book" : hw.type === "exam" ? "target" : "check"} size={12}
            style={{ color: hw.type === "read" ? "var(--vh-blue-500)" : hw.type === "exam" ? "var(--vh-orange)" : "var(--vh-teal)" }} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: ".07em", marginBottom: 3 }}>{hw.ch}</div>
              <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>{hw.text}</div>
            </div>
          </div>
        )}
      </div>
    </div>);

}

/* ── EXAM TRAINER ── */
const EXAM_QS = [
{ q: "Which of the following best describes a project according to ICB4?", opts: ["A repetitive set of tasks", "A unique, temporary, multi-disciplinary endeavour", "An ongoing operational process", "A programme of related projects"], ans: 1, ch: "Ch. 2", level: "c" },
{ q: "What does the formula E = Q × A represent?", opts: ["Effort = Quality × Acceptance", "Effectiveness = Quality × Acceptance", "Efficiency = Quantity × Availability", "Excellence = Quality × Accountability"], ans: 1, ch: "Ch. 2", level: "c" },
{ q: "How many competence elements does the Practice domain contain in ICB4?", opts: ["5", "10", "13", "28"], ans: 2, ch: "Ch. 1", level: "c" },
{ q: "IPMA-D certification requires a minimum pass mark of:", opts: ["45%", "50%", "55%", "65%"], ans: 2, ch: "Ch. 1", level: "c" },
{ q: "Which stage confirms whether the project investment is justified?", opts: ["Project Execution", "Project Closure", "Project Preparation", "Project Definition"], ans: 2, ch: "Ch. 3", level: "p" },
{ q: "The magic triangle / iron square consists of:", opts: ["Time, Cost, Scope (+ Quality)", "Time, Budget, Resources", "Scope, Risk, Quality", "Budget, Stakeholders, Scope"], ans: 0, ch: "Ch. 2", level: "c" },
{ q: "A stakeholder analysis typically includes how many steps?", opts: ["2", "3", "4", "5"], ans: 2, ch: "Ch. 4", level: "p" },
{ q: "Which ICB4 domain covers Leadership and Teamwork?", opts: ["Practice", "Perspective", "People", "Process"], ans: 2, ch: "Ch. 1", level: "c" },
{ q: "What is the primary purpose of a Work Breakdown Structure (WBS)?", opts: ["Estimate the budget", "Decompose total scope into manageable packages", "Identify project risks", "Define the project schedule"], ans: 1, ch: "Ch. 5", level: "p" },
{ q: "IPMA ICB4 distinguishes how many certification levels?", opts: ["2", "3", "4", "5"], ans: 2, ch: "Ch. 1", level: "c" }];


function IPMAExamTrainer({ toast }) {
  const QTIME = 30;
  const [phase, setPhase] = useState("intro"); // intro | exam | result
  const [qi, setQi] = useState(0);
  const [answers, setAnswers] = useState({});
  const [selected, setSelected] = useState(null);
  const [timer, setTimer] = useState(QTIME);
  const [revealed, setRevealed] = useState(false);

  useEffect(() => {
    if (phase !== "exam" || revealed) return;
    if (timer <= 0) {advance(null);return;}
    const t = setTimeout(() => setTimer((s) => s - 1), 1000);
    return () => clearTimeout(t);
  }, [phase, timer, revealed, qi]);

  function advance(idx) {
    const ans = { ...answers, [qi]: idx };
    setAnswers(ans);
    setSelected(null);
    setRevealed(false);
    if (qi + 1 >= EXAM_QS.length) setPhase("result");else
    {setQi((q) => q + 1);setTimer(QTIME);}
  }

  if (phase === "intro") return (
    <div className="vh-in" style={{ maxWidth: 600, margin: "0 auto" }}>
      <div className="card" style={{ padding: 0, overflow: "hidden", textAlign: "center" }}>
        <div style={{ padding: "36px 32px 24px", background: "linear-gradient(135deg,#c0392b,#7b1c1c)", position: "relative", overflow: "hidden" }}>
          <div className="hexfield" style={{ opacity: .16 }} />
          <div style={{ position: "relative" }}>
            <div className="hex-flat" style={{ width: 66, height: 72, margin: "0 auto 16px", clipPath: "polygon(50% 0,93% 25%,93% 75%,50% 100%,7% 75%,7% 25%)", background: "var(--vh-orange)", display: "grid", placeItems: "center" }}><Icon name="target" size={32} style={{ color: "#231f20" }} /></div>
            <h2 style={{ fontSize: 26, fontWeight: 700, color: "#fff", margin: 0 }}>IPMA-D Exam Trainer</h2>
            <p style={{ color: "rgba(255,255,255,.75)", fontSize: 14, marginTop: 8, lineHeight: 1.5 }}>10 multiple-choice questions · 30 seconds per question<br />Mirrors the real IPMA-D written exam format</p>
          </div>
        </div>
        <div style={{ padding: "24px 32px" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14, marginBottom: 22 }}>
            {[["10", "Questions"], ["5 min", "Duration"], ["55%", "Pass mark"]].map(([v, l]) =>
            <div key={l} style={{ padding: "14px", borderRadius: 12, background: "var(--surface-2)", border: "1px solid var(--line)" }}>
                <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 28 }}>{v}</div>
                <div className="dim" style={{ fontSize: 12, fontWeight: 600 }}>{l}</div>
              </div>
            )}
          </div>
          <button className="btn btn-pri" style={{ width: "100%", fontSize: 15, padding: "14px" }} onClick={() => {setPhase("exam");setQi(0);setAnswers({});setTimer(QTIME);}}>
            <Icon name="play" size={18} />Start mock exam
          </button>
        </div>
      </div>
    </div>);


  if (phase === "result") {
    const correct = EXAM_QS.filter((q, i) => answers[i] === q.ans).length;
    const pct = Math.round(correct / EXAM_QS.length * 100);
    const passed = pct >= 55;
    return (
      <div className="vh-in" style={{ maxWidth: 600, margin: "0 auto" }}>
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ padding: "30px 28px", background: passed ? "linear-gradient(135deg,var(--vh-teal),#0d6e5e)" : "linear-gradient(135deg,#c0392b,#7b1c1c)", textAlign: "center", position: "relative", overflow: "hidden" }}>
            <div className="hexfield" style={{ opacity: .14 }} />
            <div style={{ position: "relative" }}>
              <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 52, color: "#fff" }}>{pct}%</div>
              <div style={{ fontSize: 18, fontWeight: 700, color: "rgba(255,255,255,.9)", marginTop: 4 }}>{passed ? "Passed! ✓" : "Not yet — keep going"}</div>
              <div style={{ fontSize: 13, color: "rgba(255,255,255,.65)", marginTop: 6 }}>{correct} / {EXAM_QS.length} correct · Pass mark 55%</div>
            </div>
          </div>
          <div style={{ padding: "20px 24px" }}>
            {EXAM_QS.map((q, i) => {
              const ua = answers[i];const correct2 = ua === q.ans;
              return (
                <div key={i} style={{ display: "flex", gap: 10, padding: "10px 0", borderBottom: i < EXAM_QS.length - 1 ? "1px solid var(--line-2)" : "none" }}>
                  <div style={{ width: 22, height: 22, borderRadius: "50%", flex: "none", display: "grid", placeItems: "center", background: ua == null ? "var(--surface-3)" : correct2 ? "var(--vh-teal)" : "#c0392b" }}>
                    <Icon name={ua == null ? "layers" : correct2 ? "check" : "layers"} size={12} style={{ color: "#fff" }} />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)", marginBottom: 3 }}>{q.q}</div>
                    <div style={{ fontSize: 12, color: correct2 ? "var(--vh-teal)" : "#c0392b" }}>
                      {ua == null ? "Time expired" : correct2 ? "Correct: " + q.opts[q.ans] : "Your answer: " + q.opts[ua] + " · Correct: " + q.opts[q.ans]}
                    </div>
                  </div>
                  <span className="dim" style={{ fontSize: 11, flex: "none" }}>{q.ch}</span>
                </div>);

            })}
            <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
              <button className="btn btn-ghost" style={{ flex: 1 }} onClick={() => {setPhase("intro");setAnswers({});setQi(0);}}><Icon name="refresh" size={14} />Try again</button>
              <button className="btn btn-pri" style={{ flex: 1 }} onClick={() => toast(passed ? "Cert ready — schedule your exam!" : "Study the missed topics first", passed ? "medal" : "book")}>{passed ? "Schedule real exam" : "Review weak areas"}</button>
            </div>
          </div>
        </div>
      </div>);

  }

  const q = EXAM_QS[qi];
  const timerPct = timer / QTIME * 100;
  return (
    <div className="vh-in" style={{ maxWidth: 680, margin: "0 auto" }}>
      {/* progress */}
      <div style={{ display: "flex", gap: 5, marginBottom: 16 }}>
        {EXAM_QS.map((_, i) =>
        <div key={i} style={{ flex: 1, height: 5, borderRadius: 9, background: i < qi ? "var(--vh-teal)" : i === qi ? "var(--vh-orange)" : "var(--surface-3)", transition: "background .3s" }} />
        )}
      </div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16, fontSize: 13, color: "var(--ink-3)", fontWeight: 600 }}>
        <span>Question {qi + 1} of {EXAM_QS.length} · {q.ch} · Level {q.level}</span>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{ width: 80, height: 6, borderRadius: 9, background: "var(--surface-3)", overflow: "hidden" }}>
            <div style={{ height: "100%", width: timerPct + "%", background: timer > 10 ? "var(--vh-teal)" : "#c0392b", borderRadius: 9, transition: "width 1s linear" }} />
          </div>
          <span style={{ fontFamily: "var(--display)", fontWeight: 700, color: timer > 10 ? "var(--ink-2)" : "#c0392b" }}>{timer}s</span>
        </div>
      </div>
      <div className="card" style={{ padding: "24px 24px 20px", marginBottom: 14 }}>
        <h3 style={{ fontSize: 18, fontWeight: 700, lineHeight: 1.45, margin: 0 }}>{q.q}</h3>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 16 }}>
        {q.opts.map((opt, oi) => {
          const isSelected = selected === oi;
          const isCorrect = revealed && oi === q.ans;
          const isWrong = revealed && isSelected && oi !== q.ans;
          return (
            <button key={oi} onClick={() => {if (!revealed) {setSelected(oi);setRevealed(true);}}}
            style={{ display: "flex", alignItems: "center", gap: 12, padding: "13px 18px", borderRadius: 12, border: `2px solid ${isCorrect ? "var(--vh-teal)" : isWrong ? "#c0392b" : isSelected ? "var(--vh-blue-500)" : "var(--line)"}`, background: isCorrect ? "color-mix(in oklab,var(--vh-teal),transparent 88%)" : isWrong ? "color-mix(in oklab,#c0392b,transparent 90%)" : isSelected ? "color-mix(in oklab,var(--vh-blue-500),transparent 92%)" : "var(--surface)", textAlign: "left", cursor: revealed ? "default" : "pointer", transition: "all .15s" }}>
              <div style={{ width: 26, height: 26, borderRadius: "50%", flex: "none", background: isCorrect ? "var(--vh-teal)" : isWrong ? "#c0392b" : "var(--surface-3)", display: "grid", placeItems: "center", fontFamily: "var(--display)", fontWeight: 700, fontSize: 12, color: isCorrect || isWrong ? "#fff" : "var(--ink-3)" }}>
                {isCorrect ? <Icon name="check" size={13} style={{ color: "#fff" }} /> : isWrong ? "✗" : String.fromCharCode(65 + oi)}
              </div>
              <span style={{ fontSize: 14.5, fontWeight: isSelected || isCorrect ? 600 : 400, color: "var(--ink)" }}>{opt}</span>
            </button>);

        })}
      </div>
      {revealed &&
      <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <button className="btn btn-pri" style={{ fontSize: 14, padding: "11px 28px" }} onClick={() => advance(selected)}>
            {qi + 1 < EXAM_QS.length ? "Next question" : "See results"} <Icon name="arrowR" size={15} />
          </button>
        </div>
      }
    </div>);

}

/* ── EVALUATION ── */
const EVAL_ASPECTS = [
{ id: "content", label: "Course content quality" },
{ id: "trainer", label: "Trainer expertise & delivery" },
{ id: "materials", label: "Study materials & slides" },
{ id: "platform", label: "Learning platform (LMS)" },
{ id: "pace", label: "Pace and schedule" },
{ id: "relevance", label: "Relevance to my work" }];


function IPMAEvaluation({ toast }) {
  const [ratings, setRatings] = useState({});
  const [nps, setNps] = useState(null);
  const [comment, setComment] = useState("");
  const [submitted, setSubmitted] = useState(false);

  const rated = Object.keys(ratings).length;
  const allDone = rated === EVAL_ASPECTS.length && nps !== null;

  if (submitted) return (
    <div className="vh-in" style={{ maxWidth: 500, margin: "0 auto", textAlign: "center" }}>
      <div className="card" style={{ padding: "40px 32px" }}>
        <div style={{ fontSize: 52, marginBottom: 16 }}>🎓</div>
        <h2 style={{ fontSize: 24, fontWeight: 700, marginBottom: 8 }}>Thank you for your feedback!</h2>
        <p className="muted" style={{ fontSize: 14, lineHeight: 1.6, marginBottom: 20 }}>Your evaluation has been submitted to the Van Haren Academy team. Your input helps us continuously improve the training.</p>
        <div style={{ padding: "14px 20px", borderRadius: 12, background: "var(--surface-2)", border: "1px solid var(--line)", marginBottom: 20 }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14 }}>
            <span style={{ color: "var(--ink-2)" }}>Your average rating</span>
            <span style={{ fontWeight: 700, color: "var(--vh-orange)" }}>{(Object.values(ratings).reduce((s, v) => s + v, 0) / rated).toFixed(1)} / 5 ⭐</span>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, marginTop: 8 }}>
            <span style={{ color: "var(--ink-2)" }}>NPS score</span>
            <span style={{ fontWeight: 700 }}>{nps}/10</span>
          </div>
        </div>
        <button className="btn btn-ghost" onClick={() => setSubmitted(false)}><Icon name="refresh" size={14} />Edit evaluation</button>
      </div>
    </div>);


  return (
    <div className="vh-in" style={{ maxWidth: 660, margin: "0 auto" }}>
      <div style={{ marginBottom: 20 }}>
        <h2 style={{ fontSize: 22, fontWeight: 700, margin: 0 }}>Course Evaluation</h2>
        <p className="dim" style={{ fontSize: 14, marginTop: 4 }}>IPMA-D Training · June 2026 · Your feedback is anonymous</p>
      </div>

      {/* star ratings */}
      <div className="card" style={{ padding: "18px 22px", marginBottom: 16 }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>Rate each aspect</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {EVAL_ASPECTS.map((a) =>
          <div key={a.id} style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{a.label}</span>
              <div style={{ display: "flex", gap: 4 }}>
                {[1, 2, 3, 4, 5].map((s) =>
              <button key={s} onClick={() => setRatings((r) => ({ ...r, [a.id]: s }))}
              style={{ fontSize: 22, background: "none", border: "none", cursor: "pointer", color: (ratings[a.id] || 0) >= s ? "var(--vh-orange)" : "var(--line)", lineHeight: 1, padding: "0 1px", transition: "color .1s" }}>★</button>
              )}
              </div>
              {ratings[a.id] && <span style={{ fontSize: 12.5, color: "var(--ink-3)", width: 30, textAlign: "right" }}>{ratings[a.id]}/5</span>}
            </div>
          )}
        </div>
      </div>

      {/* NPS */}
      <div className="card" style={{ padding: "18px 22px", marginBottom: 16 }}>
        <div className="eyebrow" style={{ marginBottom: 4 }}>How likely are you to recommend this training?</div>
        <p className="dim" style={{ fontSize: 13, marginBottom: 14 }}>0 = Not at all · 10 = Extremely likely</p>
        <div style={{ display: "flex", gap: 5, flexWrap: "wrap" }}>
          {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((n) =>
          <button key={n} onClick={() => setNps(n)}
          style={{ width: 38, height: 38, borderRadius: 9, border: `2px solid ${nps === n ? n >= 9 ? "var(--vh-teal)" : n >= 7 ? "var(--vh-orange)" : "#c0392b" : "var(--line)"}`, background: nps === n ? n >= 9 ? "color-mix(in oklab,var(--vh-teal),transparent 82%)" : n >= 7 ? "color-mix(in oklab,var(--vh-orange),transparent 82%)" : "color-mix(in oklab,#c0392b,transparent 85%)" : "var(--surface)", fontFamily: "var(--display)", fontWeight: 700, fontSize: 13, color: "var(--ink)", cursor: "pointer", transition: "all .12s" }}>{n}</button>
          )}
        </div>
        {nps !== null && <p style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 10 }}>{nps >= 9 ? "Promoter — thank you! 🎉" : nps >= 7 ? "Passive — we appreciate your feedback" : "Detractor — we'll work to improve"}</p>}
      </div>

      {/* comment */}
      <div className="card" style={{ padding: "18px 22px", marginBottom: 20 }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>Additional comments (optional)</div>
        <textarea value={comment} onChange={(e) => setComment(e.target.value)}
        placeholder="What did you like most? What could be improved?"
        style={{ width: "100%", minHeight: 96, resize: "vertical", border: "1px solid var(--line)", borderRadius: 10, padding: "10px 12px", fontSize: 14, fontFamily: "var(--body)", lineHeight: 1.6, boxSizing: "border-box", outline: "none", color: "var(--ink)" }} />
      </div>

      <div style={{ display: "flex", gap: 12 }}>
        <div style={{ flex: 1, fontSize: 13, color: "var(--ink-3)", paddingTop: 8 }}>{rated}/{EVAL_ASPECTS.length} aspects rated{nps !== null ? ", NPS scored" : ""}</div>
        <button className="btn btn-pri" disabled={!allDone} onClick={() => {if (allDone) setSubmitted(true);else toast("Please rate all aspects and set your NPS score", "target");}} style={{ fontSize: 14, padding: "11px 28px" }}>
          <Icon name="check" size={16} />Submit evaluation
        </button>
      </div>
    </div>);

}

const MEMO_CARDS = [
{ id: 1, q: "Definition of a project (ICB4)", a: "A unique, temporary, multi-disciplinary and organised endeavour to realise agreed deliverables within predefined requirements.", ch: "Ch. 3" },
{ id: 2, q: "What does E = Q × A stand for?", a: "Effectiveness = Quality × Acceptance. A technically perfect solution without user acceptance yields zero effectiveness.", ch: "Ch. 3" },
{ id: 3, q: "Name the 3 ICB4 competence areas", a: "Perspective (5 CEs), People (10 CEs), Practice (13 CEs) — together forming the Eye of Competence.", ch: "Ch. 1" },
{ id: 4, q: "IPMA-D certification level", a: "Certified Project Management Associate: you have knowledge of all PM elements and can support the project manager of a limited complex project.", ch: "Ch. 1" },
{ id: 5, q: "4 steps of stakeholder analysis", a: "1. Identify stakeholders  2. Define relations  3. Prepare a communication plan  4. Involve stakeholders.", ch: "Ch. 4" },
{ id: 6, q: "The triple constraint / magic triangle", a: "Time, Cost, and Scope — the iron square. Changing one dimension affects the others. Quality is sometimes added as a fourth constraint.", ch: "Ch. 3" },
{ id: 7, q: "Purpose of a Business Case", a: "To justify the investment by documenting objectives, expected benefits, costs, and risks — used by the sponsor to authorise the project.", ch: "Ch. 5" },
{ id: 8, q: "What is a Work Breakdown Structure (WBS)?", a: "A hierarchical decomposition of the total work scope into manageable packages (verb + noun). Differs from PBS (product-only nouns).", ch: "Ch. 5" }];


function IPMAMemoTrainer({ toast }) {
  const SESSION = MEMO_CARDS.slice(0, 5);
  const [idx, setIdx] = useState(0);
  const [flipped, setFlipped] = useState(false);
  const [scores, setScores] = useState({});
  const [done, setDone] = useState(false);

  const card = SESSION[idx];
  const rated = Object.keys(scores).length;
  const mastered = Object.values(scores).filter((v) => v === 'easy').length;

  function rate(v) {
    const next = { ...scores, [card.id]: v };
    setScores(next);
    setFlipped(false);
    if (idx + 1 >= SESSION.length) setDone(true);else
    setIdx((i) => i + 1);
  }

  function restart() {setIdx(0);setFlipped(false);setScores({});setDone(false);}

  if (done) {
    return (
      <div className="vh-in" style={{ maxWidth: 580, margin: "0 auto" }}>
        <div className="card" style={{ padding: 0, overflow: "hidden", textAlign: "center" }}>
          <div style={{ padding: "36px 32px 28px", background: "linear-gradient(135deg,var(--vh-blue-500),var(--vh-navy))", position: "relative", overflow: "hidden" }}>
            <div className="hexfield" style={{ opacity: .3 }} />
            <div style={{ position: "relative" }}>
              <div className="hex-flat" style={{ width: 72, height: 78, margin: "0 auto 16px", clipPath: "polygon(50% 0,93% 25%,93% 75%,50% 100%,7% 75%,7% 25%)", background: "var(--accent)", display: "grid", placeItems: "center" }}>
                <Icon name="brain" size={36} style={{ color: "#231f20" }} />
              </div>
              <h2 style={{ fontSize: 24, fontWeight: 700, color: "#fff", margin: 0 }}>Session complete!</h2>
              <p style={{ color: "rgba(255,255,255,.8)", fontSize: 14, marginTop: 8 }}>You reviewed {SESSION.length} memory items</p>
            </div>
          </div>
          <div style={{ padding: "24px 32px 28px" }}>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14, marginBottom: 22 }}>
              {[["Mastered", mastered, "var(--vh-teal)"], ["Got it", Object.values(scores).filter((v) => v === "good").length, "var(--vh-orange)"], ["Needs work", Object.values(scores).filter((v) => v === "hard").length, "var(--ink-3)"]].map(([l, v, c]) =>
              <div key={l} style={{ padding: "14px 12px", borderRadius: 13, background: "var(--surface-2)", border: "1px solid var(--line)" }}>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 28, color: c }}>{v}</div>
                  <div className="dim" style={{ fontSize: 11.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".06em" }}>{l}</div>
                </div>
              )}
            </div>
            <div style={{ display: "flex", gap: 12 }}>
              <button className="btn btn-ghost" style={{ flex: 1 }} onClick={restart}><Icon name="refresh" size={15} />Restart</button>
              <button className="btn btn-pri" style={{ flex: 1 }} onClick={() => toast("Great work! +45 XP earned", "bolt")}><Icon name="check" size={15} />Done for today</button>
            </div>
          </div>
        </div>
      </div>);

  }

  return (
    <div className="vh-in">
      <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 20, flexWrap: "wrap" }}>
        <div>
          <h2 style={{ fontSize: 20, fontWeight: 700, margin: 0 }}>Memo Trainer</h2>
          <p className="dim" style={{ fontSize: 13.5, marginTop: 3 }}>Spaced repetition · IPMA-D key concepts</p>
        </div>
        <div style={{ flex: 1 }} />
        {[["Today", "5 cards"], ["Mastered", "142"], ["Accuracy", "84%"]].map(([l, v]) =>
        <div key={l} style={{ textAlign: "center", padding: "10px 16px", borderRadius: 11, background: "var(--surface)", border: "1px solid var(--line)" }}>
            <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 18 }}>{v}</div>
            <div className="dim" style={{ fontSize: 11.5, fontWeight: 600 }}>{l}</div>
          </div>
        )}
      </div>

      {/* session progress bar */}
      <div style={{ display: "flex", gap: 5, marginBottom: 20 }}>
        {SESSION.map((c, i) => {
          const s = scores[c.id];
          const bg = i < rated ? s === "easy" ? "var(--vh-teal)" : s === "good" ? "var(--vh-orange)" : "var(--ink-3)" : i === idx ? "var(--accent)" : "var(--surface-3)";
          return <div key={i} style={{ flex: 1, height: 6, borderRadius: 9, background: bg, transition: "background .3s" }} />;
        })}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 290px", gap: 20, alignItems: "start" }}>
        {/* flashcard */}
        <div>
          <div style={{ fontSize: 13, color: "var(--ink-3)", fontWeight: 600, marginBottom: 12 }}>Card {idx + 1} of {SESSION.length} · {card.ch}</div>
          <div className="card" onClick={() => !flipped && setFlipped(true)}
          style={{ padding: "32px 28px", minHeight: 200, cursor: flipped ? "default" : "pointer", position: "relative", overflow: "hidden" }}>
            {!flipped ?
            <>
                <div className="eyebrow" style={{ marginBottom: 14 }}>Question — tap to reveal answer</div>
                <h3 style={{ fontSize: 20, fontWeight: 600, lineHeight: 1.35 }}>{card.q}</h3>
                <div style={{ position: "absolute", bottom: 16, right: 20, opacity: .12 }}><Icon name="layers" size={64} /></div>
              </> :

            <>
                <div className="eyebrow" style={{ marginBottom: 14, color: "var(--vh-teal)" }}>Answer</div>
                <p style={{ fontSize: 15.5, lineHeight: 1.7, color: "var(--ink-2)" }}>{card.a}</p>
              </>
            }
          </div>
          {flipped &&
          <div className="vh-in" style={{ display: "flex", gap: 10, marginTop: 12 }}>
              {[["hard", "refresh", "Needs work", "var(--ink-3)"], ["good", "check", "Got it", "var(--vh-orange)"], ["easy", "bolt", "Easy!", "var(--vh-teal)"]].map(([v, ic, lbl, col]) =>
            <button key={v} className="btn" style={{ flex: 1, background: `color-mix(in oklab,${col},transparent 86%)`, color: "var(--ink)", fontSize: 14, border: `1.5px solid color-mix(in oklab,${col},transparent 70%)` }} onClick={() => rate(v)}>
                  <Icon name={ic} size={15} />{lbl}
                </button>
            )}
            </div>
          }
        </div>

        {/* sidebar */}
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div className="card" style={{ padding: "16px 18px" }}>
            <div className="eyebrow" style={{ marginBottom: 12 }}>In this session</div>
            {SESSION.map((c, i) =>
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 0", borderBottom: i < SESSION.length - 1 ? "1px solid var(--line-2)" : "none", opacity: i > idx ? .5 : 1 }}>
                <div style={{ width: 20, height: 20, borderRadius: "50%", flex: "none", display: "grid", placeItems: "center",
                background: i < rated ? scores[c.id] === "easy" ? "var(--vh-teal)" : "var(--vh-orange)" : i === idx ? "var(--accent)" : "var(--surface-3)" }}>
                  {i < rated ? <Icon name="check" size={10} style={{ color: "#fff" }} /> : <span style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 10, color: i === idx ? "#231f20" : "var(--ink-3)" }}>{i + 1}</span>}
                </div>
                <span style={{ fontSize: 12.5, fontWeight: i === idx ? 700 : 500, color: i === idx ? "var(--ink)" : "var(--ink-2)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.q.length > 38 ? c.q.slice(0, 38) + "…" : c.q}</span>
              </div>
            )}
          </div>
          <div className="card" style={{ padding: "18px 18px", textAlign: "center" }}>
            <Icon name="brain" size={28} style={{ color: "var(--vh-blue-500)", marginBottom: 8 }} />
            <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 14, marginBottom: 5 }}>MemoTrainer App</div>
            <p className="dim" style={{ fontSize: 12.5, lineHeight: 1.5, marginBottom: 12 }}>Review cards anywhere. Syncs with your e-learning progress.</p>
            <div style={{ display: "flex", gap: 8 }}>
              <button className="btn btn-ghost" style={{ flex: 1, fontSize: 12 }} onClick={() => toast("Redirecting to App Store…", "download")}>iOS</button>
              <button className="btn btn-ghost" style={{ flex: 1, fontSize: 12 }} onClick={() => toast("Redirecting to Play Store…", "download")}>Android</button>
            </div>
          </div>
        </div>
      </div>
    </div>);

}

function IPMACourseDetail({ course, toast, onGameify, onViewSlides, onOpenBook, onKahoot, onWordCloud }) {
  const [tab, setTab] = useState("elearning");
  const [showToc, setShowToc] = useState(true);
  const [bannerVisible, setBannerVisible] = useState(true);
  const continueCh = IPMA_CHAPTERS_DATA.find((c) => c.status === "active") || IPMA_CHAPTERS_DATA[0];

  return (
    <div style={{ paddingBottom: 8 }}>
      {/* product type tabs */}
      <div style={{ display: "flex", gap: 6, marginBottom: 20, flexWrap: "wrap" }}>
        {IPMA_PRODUCT_TABS.map((pt) =>
        <button key={pt.id} onClick={() => setTab(pt.id)}
        className={"btn " + (tab === pt.id ? "btn-pri" : "btn-outline")}
        style={{ fontSize: 13.5, padding: "10px 18px" }}>
            <Icon name={pt.icon} size={15} />{pt.label}
          </button>
        )}
        <div style={{ flex: 1 }} />
      </div>

      {/* E-learning tab — 2 col: content + session sidebar */}
      {tab === "elearning" &&
      <div style={{ display: "grid", gridTemplateColumns: "1fr 300px", gap: 20, alignItems: "start" }}>
          <div>
            {bannerVisible &&
          <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 18px", borderRadius: 11, background: "var(--vh-orange)", marginBottom: 18 }}>
                <Icon name="arrowR" size={18} style={{ color: "#231f20", flex: "none" }} />
                <span style={{ flex: 1, fontSize: 14, fontWeight: 700, color: "#231f20" }}>Continue with: Chapter {continueCh.n} – {continueCh.title}</span>
                <button onClick={() => setBannerVisible(false)} style={{ background: "none", border: "none", color: "#231f20", cursor: "pointer", fontSize: 20, lineHeight: 1, padding: "0 2px", opacity: .7 }}>×</button>
              </div>
          }
            <div style={{ display: "flex", gap: 10, marginBottom: 20, alignItems: "center", flexWrap: "wrap" }}>
              <button className={"btn " + (showToc ? "btn-ghost" : "btn-outline")} style={{ fontSize: 13 }} onClick={() => setShowToc((t) => !t)}>
                <Icon name="layers" size={15} />View objectives
              </button>
              <label className="search" style={{ flex: 1, maxWidth: 320 }}>
                <Icon name="search" size={16} /><input placeholder="Search content…" />
              </label>
            </div>
            {showToc && <IPMAToC />}
            <div>
              {IPMA_CHAPTERS_DATA.map((ch) =>
            <IPMAChapterRow key={ch.n} ch={ch} onStart={() => toast("Opening Chapter " + ch.n + " – " + ch.title, "book")} />
            )}
            </div>
          </div>
          <IPMASessionSidebar toast={toast} onViewSlides={onViewSlides} />
        </div>
      }

      {tab === "courseware" && <IPMAPresentationView toast={toast} onViewSlides={onViewSlides} onKahoot={onKahoot} onWordCloud={onWordCloud} />}
      {tab === "memo" && <IPMAMemoTrainer toast={toast} />}
      {tab === "exam" && <IPMAExamTrainer toast={toast} />}
      {tab === "assessment" && <IPMASelfAssessment toast={toast} />}
      {tab === "book" && <IPMABookView toast={toast} onOpenBook={onOpenBook} />}
      {tab === "evaluation" && <IPMAEvaluation toast={toast} />}
    </div>);

}

Object.assign(window, { IPMACourseDetail });