/* educator-seed-decks.jsx — seeds a sample courseware deck per course so the
   embedded Presentation Studio is immediately usable (rebuild-to-HTML, styling,
   live learner preview, gamified assignments). Idempotent per course. */

(function () {
  function esc(s) { return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }
  function wrap(text, max) {
    const words = String(text).split(/\s+/); const lines = []; let cur = "";
    words.forEach((w) => { if ((cur + " " + w).trim().length > max) { if (cur) lines.push(cur); cur = w; } else cur = (cur + " " + w).trim(); });
    if (cur) lines.push(cur); return lines;
  }
  function tspans(lines, x, y, lh) { return lines.map((l, i) => `<tspan x="${x}" y="${y + i * lh}">${esc(l)}</tspan>`).join(""); }
  function dataURL(svg) { return "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg); }

  function hexmark(x, y, s, color) {
    return `<g transform="translate(${x},${y})"><path d="M${s / 2} 0 ${s} ${s * 0.28} ${s} ${s * 0.72} ${s / 2} ${s} 0 ${s * 0.72} 0 ${s * 0.28}z" fill="${color}"/><path d="M${s * 0.3} ${s * 0.66}V${s * 0.4}l${s * 0.2} ${s * 0.12} ${s * 0.2}-${s * 0.12}v${s * 0.26}" stroke="#fff" stroke-width="${s * 0.06}" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>`;
  }

  function titleSlide(course, color, total) {
    return dataURL(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 900">
      <rect width="1600" height="900" fill="#0c1830"/>
      <rect width="1600" height="900" fill="url(#g)"/>
      <defs><radialGradient id="g" cx="78%" cy="0%" r="80%"><stop offset="0" stop-color="${color}" stop-opacity="0.35"/><stop offset="0.6" stop-color="#0c1830" stop-opacity="0"/></radialGradient></defs>
      ${hexmark(120, 110, 92, color)}
      <rect x="120" y="372" width="84" height="9" fill="${color}"/>
      <text x="120" y="350" font-family="Arial,sans-serif" font-size="26" font-weight="700" letter-spacing="6" fill="#7fc0ec">VAN HAREN  ·  COURSEWARE</text>
      <text font-family="Arial,sans-serif" font-size="86" font-weight="800" fill="#ffffff">${tspans(wrap(course, 22), 120, 470, 96)}</text>
      <text x="120" y="700" font-family="Arial,sans-serif" font-size="34" fill="rgba(200,216,240,.75)">Foundation certification programme · sample deck</text>
      <text x="1480" y="840" text-anchor="end" font-family="Arial,sans-serif" font-size="24" font-weight="700" fill="rgba(200,216,240,.5)">01 / ${total}</text>
    </svg>`);
  }

  function contentSlide(eyebrow, title, bullets, course, color, page, total) {
    return dataURL(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 900">
      <rect width="1600" height="900" fill="#ffffff"/>
      <rect width="1600" height="10" fill="${color}"/>
      <text x="120" y="150" font-family="Arial,sans-serif" font-size="25" font-weight="700" letter-spacing="5" fill="${color}">${esc(eyebrow.toUpperCase())}</text>
      <text font-family="Arial,sans-serif" font-size="62" font-weight="800" fill="#1c2740">${tspans(wrap(title, 30), 120, 232, 70)}</text>
      ${bullets.map((b, i) => `<circle cx="136" cy="${356 + i * 92}" r="9" fill="${color}"/><text x="172" y="${367 + i * 92}" font-family="Arial,sans-serif" font-size="33" fill="#2f3b54">${tspans(wrap(b, 64), 172, 367 + i * 92, 42)}</text>`).join("")}
      <text x="120" y="842" font-family="Arial,sans-serif" font-size="23" fill="#7b899f">${esc(course)}</text>
      <text x="1480" y="842" text-anchor="end" font-family="Arial,sans-serif" font-size="23" font-weight="700" fill="#7b899f">${String(page).padStart(2, "0")} / ${total}</text>
    </svg>`);
  }

  /* ── HTML-native versions of the same slides ──────────────────────────
     The actual courseware: every seeded slide ships as a real, self-contained
     HTML document (stored in deck.enhance[i].html) so the study IS HTML —
     crisp at any size, restylable per slide, and ready for gamification.
     The SVG images above remain only as thumbnails / fallback. */
  function htmlTitle(course, color, total) {
    return `<!DOCTYPE html><html><head><meta charset="utf-8"><style>
html,body{margin:0;width:100vw;height:100vh;overflow:hidden}*{box-sizing:border-box}
body{font-family:Arial,Helvetica,sans-serif;background:#0c1830;color:#fff}
.slide{position:relative;width:100vw;height:100vh;display:flex;flex-direction:column;justify-content:center;padding:0 7.5vw;background:radial-gradient(70vw 55vw at 78% 0%,${color}55,rgba(12,24,48,0) 62%)}
.hx{width:5.8vw;height:5.8vw;margin-bottom:3.6vw}
.eyebrow{font-size:1.55vw;font-weight:700;letter-spacing:.42em;color:#7fc0ec;margin:0}
.bar{width:5.2vw;height:.55vw;background:${color};margin:1.3vw 0 2.2vw}
h1{font-size:5.4vw;font-weight:800;line-height:1.06;margin:0;max-width:70vw}
.sub{font-size:2.05vw;color:rgba(200,216,240,.75);margin-top:2.6vw}
.page{position:absolute;right:4.5vw;bottom:4vw;font-size:1.45vw;font-weight:700;color:rgba(200,216,240,.5)}
</style></head><body><div class="slide">
<svg class="hx" viewBox="0 0 36 36"><path d="M18 2 32 11v14L18 34 4 25V11z" fill="${color}"/><path d="M11 24v-9l7 4 7-4v9" stroke="#fff" stroke-width="2.4" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>
<p class="eyebrow">VAN HAREN · COURSEWARE</p>
<div class="bar"></div>
<h1>${esc(course)}</h1>
<p class="sub">Foundation certification programme · sample deck</p>
<div class="page">01 / ${total}</div>
</div></body></html>`;
  }

  function htmlContent(eyebrow, title, bullets, course, color, page, total) {
    return `<!DOCTYPE html><html><head><meta charset="utf-8"><style>
html,body{margin:0;width:100vw;height:100vh;overflow:hidden}*{box-sizing:border-box}
body{font-family:Arial,Helvetica,sans-serif;background:#fff;color:#1c2740}
.top{position:absolute;top:0;left:0;right:0;height:1.1vh;background:${color}}
.slide{position:relative;width:100vw;height:100vh;display:flex;flex-direction:column;padding:7.5vh 7.5vw 0}
.eyebrow{font-size:1.5vw;font-weight:700;letter-spacing:.32em;color:${color};margin:0 0 1.4vw;text-transform:uppercase}
h1{font-size:3.9vw;font-weight:800;margin:0 0 3vw;line-height:1.1}
ul{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:2.3vw}
li{position:relative;padding-left:3.2vw;font-size:2vw;line-height:1.45;color:#2f3b54}
li::before{content:"";position:absolute;left:0;top:.65vw;width:1.15vw;height:1.15vw;border-radius:50%;background:${color}}
.foot{position:absolute;left:7.5vw;right:4.5vw;bottom:4vh;display:flex;justify-content:space-between;font-size:1.4vw;color:#7b899f}
.foot b{font-weight:700}
</style></head><body><div class="slide">
<div class="top"></div>
<p class="eyebrow">${esc(eyebrow)}</p>
<h1>${esc(title)}</h1>
<ul>${bullets.map((b) => `<li>${esc(b)}</li>`).join("")}</ul>
<div class="foot"><span>${esc(course)}</span><b>${String(page).padStart(2, "0")} / ${total}</b></div>
</div></body></html>`;
  }

  function buildDeck(course, color) {
    const T = 5;
    const mods = [
      ["Module 1 · Foundations", "Learning objectives", [
        "Understand the purpose, principles and core vocabulary of " + course.replace(/®/g, "") + ".",
        "Recognise the key roles and how responsibilities are divided.",
        "Apply the framework to a realistic delivery scenario.",
        "Prepare confidently for the certification exam."]],
      ["Module 2 · Framework", "The core framework", [
        "Principles — the guiding ideas that shape every decision.",
        "Themes — the aspects that must be addressed continuously.",
        "Processes — the structured steps from start-up to closure.",
        "Tailoring — adapting the method to the project's context."]],
      ["Module 3 · People", "Roles & responsibilities", [
        "Sponsor / Executive — owns the business case and justification.",
        "Manager — plans, monitors and controls day-to-day delivery.",
        "Team — produces the specialist products to agreed quality.",
        "Assurance — independent check that the work stays on track."]],
      ["Checkpoint", "Quick knowledge check", [
        "Which document carries the ongoing justification for the project?",
        "Ready to make this interactive? Use Build study to add a quiz.",
        "Style any slide, rebuild it in HTML, or preview as a learner."]]
    ];
    const slides = [
      titleSlide(course, color, T),
      ...mods.map((m, i) => contentSlide(m[0], m[1], m[2], course, color, i + 2, T))
    ];
    /* HTML-native courseware: each slide carries its HTML twin from the start */
    const enhance = { 0: { html: htmlTitle(course, color, T), accent: color } };
    mods.forEach((m, i) => { enhance[i + 1] = { html: htmlContent(m[0], m[1], m[2], course, color, i + 2, T), accent: color }; });
    return {
      id: "deck_seed_" + course.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, ""),
      title: course + " — Courseware",
      slides: slides,
      ratio: 16 / 9,
      created: Date.now(),
      gamified: false,
      course: course,
      source: "Sample courseware deck",
      htmlNative: true,
      enhance: enhance
    };
  }

  async function ensureForCourse(course, color) {
    if (!course || !window.DeckStore) return false;
    const flag = "vh_seeded_deck_v2::" + course;
    try {
      if (localStorage.getItem(flag)) return false;
      const existing = await window.DeckStore.list();
      const mine = (existing || []).filter((d) => (d.course || null) === course);
      const fresh = buildDeck(course, color || "#1281c4");
      const seeded = mine.find((d) => String(d.id).indexOf("deck_seed_") === 0);
      if (seeded) {
        /* v2 upgrade: make the existing seeded deck HTML-native in place,
           keeping any styling / gamification the educator already added. */
        const enhance = { ...(fresh.enhance || {}) };
        Object.keys(seeded.enhance || {}).forEach((k) => {
          enhance[k] = { ...(enhance[k] || {}), ...(seeded.enhance[k] || {}) };
        });
        await window.DeckStore.save({ ...seeded, slides: fresh.slides, enhance: enhance, htmlNative: true });
        localStorage.setItem(flag, "1");
        return true;
      }
      if (mine.length) { localStorage.setItem(flag, "1"); return false; }
      await window.DeckStore.save(fresh);
      localStorage.setItem(flag, "1");
      return true;
    } catch (e) { return false; }
  }

  window.SeedDecks = { ensureForCourse, buildDeck };
})();
