// ─────────────────────────────────────────────────────────
// ChefVerse · Module detail screen
// Shown when a chef clicks a single module from the syllabus.
// Surfaces: status, duration, learning outcomes, prev/next modules
// (with done/current/next/locked states), and a primary CTA.
// ─────────────────────────────────────────────────────────
const MOD_STRINGS = {
  en: {
    eyebrow: "MODULE",
    of: "of",
    in: "in",
    backToCourse: "Back to course",
    learnHere: "What you'll learn here",
    chapters: "Chapters in this module",
    prevNext: "Module sequence",
    prev: "Previous",
    next: "Up next",
    minutes: "min",
    start: "Start module",
    resume: "Resume module",
    rewatch: "Re-watch module",
    locked: "Locked",
    locked_sub: "Finish the previous modules to unlock this one.",
    done: "Done",
    current: "In progress",
    nextLab: "Next up",
    lockedLab: "Locked",
    chapter: "Chapter",
    seeAll: "See all modules",
    practice: "Practice brief",
    practiceSub: "A short shoot-along you can finish in 30 minutes after watching.",
    chaptersDone: "chapters complete",
    chaptersShort: "chapters",
    toastChapterDone: "Chapter complete",
    toastModuleDone: "Module complete — next one unlocked",
    toastModuleSub: "Opening the next module…",
  },
  de: {
    eyebrow: "MODUL",
    of: "von",
    in: "in",
    backToCourse: "Zurück zum Pfad",
    learnHere: "Was du hier lernst",
    chapters: "Kapitel in diesem Modul",
    prevNext: "Modulreihenfolge",
    prev: "Zurück",
    next: "Als Nächstes",
    minutes: "Min.",
    start: "Modul starten",
    resume: "Modul fortsetzen",
    rewatch: "Modul erneut ansehen",
    locked: "Gesperrt",
    locked_sub: "Schließe die vorherigen Module ab, um dieses freizuschalten.",
    done: "Fertig",
    current: "Läuft",
    nextLab: "Als Nächstes",
    lockedLab: "Gesperrt",
    chapter: "Kapitel",
    seeAll: "Alle Module",
    practice: "Übungs-Brief",
    practiceSub: "Ein kurzer Mit-Dreh, den du danach in 30 Minuten schaffst.",
    chaptersDone: "Kapitel abgeschlossen",
    chaptersShort: "Kapitel",
    toastChapterDone: "Kapitel abgeschlossen",
    toastModuleDone: "Modul abgeschlossen — nächstes freigeschaltet",
    toastModuleSub: "Öffne das nächste Modul…",
  },
  id: {
    eyebrow: "MODUL",
    of: "dari",
    in: "di",
    backToCourse: "Kembali ke jalur",
    learnHere: "Yang kamu pelajari di sini",
    chapters: "Bab di modul ini",
    prevNext: "Urutan modul",
    prev: "Sebelumnya",
    next: "Berikutnya",
    minutes: "mnt",
    start: "Mulai modul",
    resume: "Lanjut modul",
    rewatch: "Tonton ulang",
    locked: "Terkunci",
    locked_sub: "Selesaikan modul sebelumnya untuk membuka yang ini.",
    done: "Selesai",
    current: "Sedang dijalani",
    nextLab: "Berikutnya",
    lockedLab: "Terkunci",
    chapter: "Bab",
    seeAll: "Semua modul",
    practice: "Brief latihan",
    practiceSub: "Shoot-along singkat yang bisa kamu selesaikan dalam 30 menit.",
    chaptersDone: "bab selesai",
    chaptersShort: "bab",
    toastChapterDone: "Bab selesai",
    toastModuleDone: "Modul selesai — yang berikutnya terbuka",
    toastModuleSub: "Membuka modul berikutnya…",
  },
};

// Brief outcome bullets per module index (kept locale-agnostic, short)
const MOD_OUTCOMES = {
  fundamentals: [
    ["Diagnose any kitchen's lighting in 60 seconds", "Spot a green-cast before you press record", "Know which surface in your kitchen is your studio"],
    ["Walk a pass and pick the one frame that works", "Use one window + one warm bulb as a key", "Place yourself relative to the food, not vice versa"],
    ["Lock exposure so the white plate stays white", "Set a frame rate that matches your edit", "Stop your phone auto-correcting your hard work"],
    ["Steady a phone with what's already on the line", "Hold a 30-second take without a tripod", "Eliminate jitter without buying anything"],
    ["Choose between side-light, top-down, and 30°", "Build a 3-shot series in one frame", "Direct the eye to the part of the dish you love"],
    ["Write captions that read in 1.6 seconds", "Localise tone for EN, DE, and ID", "Pass burned-in captions for any aspect ratio"],
  ],
  story: [
    ["Open with one image that earns 3 seconds", "Replace the cold open with a working hook", "Audit a hook in two reads"],
    ["Pick the moment that pulls a thumb back", "Build a 3-second hook from a 30-second shoot", "Stop apologising in your first frame"],
    ["Stack 12 frames into a beat people feel", "Use cuts to manufacture tension", "Vary your shot length on purpose"],
    ["Choose voice-over when the kitchen is loud", "Choose on-camera when the room is calm", "Match audio to the energy of the dish"],
    ["Pick a pace your viewer can chew on", "Slow down for the texture, speed up for action", "Read pace off your own breath"],
    ["Know which rule each platform punishes", "Break a rule on purpose, not on accident", "Track which break earned the watch-time"],
    ["End on a frame that drives saves, not likes", "Test two endings on the same shoot", "Resist the urge to wave goodbye"],
    ["Ship a 30-second recipe story this week", "Get a peer review before you post", "Take feedback without flinching"],
  ],
  voice: [
    ["Pick one viewer and write to them", "Drop crowd-pleaser instincts", "Sound like one person, not a brand"],
    ["Throw the script away after take 3", "Hold a structure with bullet points", "Trust your training, not your wording"],
    ["Find your camera-breathing pattern", "Pace the line, don't rush the line", "Pause without panicking"],
    ["Read your own video and not flinch", "Spot what's not 'you' in 60 seconds", "Edit for cadence, not perfection"],
    ["Recover a take after a mid-sentence break", "Use the break, don't hide it", "Plan a fallback line for the day it goes wrong"],
  ],
  edit: [
    ["Run the 10-minute edit ritual end-to-end", "Skip the parts editors do for ego", "Ship before service, not after"],
    ["Cut to the beat without thinking", "Pick a track that does half the work", "Sync motion to audio in 3 minutes"],
    ["Sync audio without nudging clips", "Trust your phone's sync engine", "Patch silence in two taps"],
    ["Save export presets per platform", "Pick one quality bar, not three", "Skip 'final-final' versioning"],
  ],
  brand: [
    ["Map your kitchen vs three rivals", "Find the one promise none of them make", "Decide what you won't be"],
    ["Write your one-line promise", "Audit it against a real customer", "Hold the line for one quarter"],
    ["Pick 5 visual decisions you won't change", "Stop redesigning every post", "Hand the system to a freelancer"],
    ["Pick 3 content pillars, not seven", "Hold ratio to those pillars over a quarter", "Spot when a pillar isn't earning"],
    ["Price your kitchen's voice for paid work", "Reject jobs that hurt the brand", "Walk into a deal with one number ready"],
    ["Convert audience to a wait-list", "Run the wait-list as a kitchen, not a list", "Earn the right to ask"],
    ["Pick a collaborator who scales you", "Avoid trades that look like favors", "Ship one collaboration this quarter"],
    ["Pitch press without a publicist", "Apply to one award you'll actually win", "Show up at the festival, not the booth"],
    ["Build the org chart you need at scale", "Hire the role you hate doing", "Document so you can step away"],
    ["Plan year-one growth with one number", "Skip vanity metrics for cash-flow signals", "Decide what year-two unlocks"],
  ],
  analytics: [
    ["Read watch-time like a ticket window", "Spot the cut that lost the room", "Trust the data, not the anecdote"],
    ["Decide in the first hour, not the first day", "Cut budget toward the early signal", "Stop A/B-ing what should be killed"],
    ["Tell saves apart from follows", "Optimise for the metric that pays you", "Stop chasing the loudest line"],
    ["Kill formats that don't earn", "Build the courage to drop a winner", "Replace ego with a calendar"],
    ["Read a 28-day trend without panic", "Spot a slow climb under the noise", "Build patience as a skill"],
    ["Set up the one dashboard you'll actually open", "Track 4 metrics, not 40", "Share the dashboard with your team"],
  ],
};

function ModuleDetail({ courseId, moduleIdx, locale, onBack, onOpenModule, onResume, onOpenCourseOverview }) {
  const s = MOD_STRINGS[locale];
  const t = window.I18N[locale];
  const course = window.COURSES.find(c => c.id === courseId) || window.COURSES[0];
  const pillar = window.PILLARS[course.pillar];
  const modules = window.COURSE_MODULES_BY_ID[course.id] || [];
  const progress = window.useCourseProgress();
  const mod = modules[moduleIdx] || modules[0];
  // Live status from the progress store
  const liveStatus = course.enrolled ? progress.moduleStatus(course.id, moduleIdx) : (mod.status || "next");
  const prev = moduleIdx > 0 ? { ...modules[moduleIdx - 1], status: course.enrolled ? progress.moduleStatus(course.id, moduleIdx - 1) : modules[moduleIdx - 1].status } : null;
  const next = moduleIdx < modules.length - 1 ? { ...modules[moduleIdx + 1], status: course.enrolled ? progress.moduleStatus(course.id, moduleIdx + 1) : modules[moduleIdx + 1].status } : null;
  const outcomes = (MOD_OUTCOMES[course.id] || [])[moduleIdx] || [];
  const fundamentals = course.id === "fundamentals";
  // Use the rich chapter list for the fundamentals course's middle module — otherwise generate
  const chapters = (fundamentals && moduleIdx === 4)
    ? window.ACTIVE_MODULE.chapters
    : Array.from({ length: progress.chapterCount(course.id, moduleIdx) }, (_, i) => ({
        t: i * 90,
        en: `${s.chapter} ${i + 1}`,
        de: `${s.chapter} ${i + 1}`,
        id: `${s.chapter} ${i + 1}`,
      }));

  const isLocked = liveStatus === "locked";
  const ctaLabel =
    liveStatus === "done" ? s.rewatch :
    liveStatus === "current" ? s.resume : s.start;
  const pct = course.enrolled ? progress.modulePct(course.id, moduleIdx) : 0;
  const { done: chDone, total: chTotal } = course.enrolled ? progress.moduleChaptersDone(course.id, moduleIdx) : { done: 0, total: chapters.length };

  return (
    <div className="page md-page">
      {/* HERO */}
      <header className="md-hero">
        <div className="md-hero-cover" style={{ background: course.cover }}>
          <img src={window.PHOTOS && window.PHOTOS.moduleCoverFor(courseId, moduleIdx)} alt="" className="md-hero-img" />
          <div className="md-hero-overlay" />
          <div className="md-hero-num">{String(moduleIdx + 1).padStart(2, "0")}</div>
          {!isLocked && (
            <button className="md-hero-play" onClick={() => !isLocked && onResume(course.id, moduleIdx)} aria-label="Play">
              <Icon name="play" size={26} style={{ marginLeft: 3 }} />
            </button>
          )}
          {isLocked && (
            <div className="md-hero-lock">
              <Icon name="lock" size={26} />
            </div>
          )}
          <div className="md-hero-tag" style={{ background: "rgba(255,255,255,0.92)", color: pillar.color }}>
            {pillar.name[locale]}
          </div>
        </div>
        <div className="md-hero-meta">
          <div className="md-eyebrow-row">
            <span className="eyebrow">{s.eyebrow} {moduleIdx + 1} {s.of} {modules.length}</span>
            <ModuleStatusPill status={liveStatus} s={s} />
          </div>
          <h1 className="md-title">{mod.title[locale]}</h1>
          <p className="md-course display-italic">
            with {course.instructor}
          </p>

          {course.enrolled && !isLocked && (
            <div className="md-progress-strip">
              <div className="md-progress-meta">
                <span><Icon name="check-circle" size={13} /> {chDone} / {chTotal} {s.chapter.toLowerCase()}{chTotal === 1 ? "" : "s"}</span>
                <span className="md-progress-pct">{Math.round(pct * 100)}%</span>
              </div>
              <div className="md-progress-track">
                <div className="md-progress-fill" style={{ width: `${pct * 100}%` }} />
              </div>
            </div>
          )}

          <div className="md-stats">
            <div className="md-stat"><Icon name="clock" size={14} /> {Math.floor(mod.dur / 60)} {s.minutes}</div>
            <div className="md-stat"><Icon name="list-video" size={14} /> {chapters.length} {locale === "de" ? "Kapitel" : locale === "id" ? "bab" : "chapters"}</div>
            <div className="md-stat"><Icon name="captions" size={14} /> EN · DE · ID</div>
          </div>

          {isLocked ? (
            <div className="md-locked-card">
              <Icon name="lock" size={16} />
              <div>
                <div className="md-locked-title">{s.locked}</div>
                <div className="md-locked-sub">{s.locked_sub}</div>
              </div>
            </div>
          ) : (
            <div className="md-actions">
              <button className="btn btn-primary btn-lg" onClick={() => onResume(course.id, moduleIdx)}>
                <Icon name="play" size={14} /> {ctaLabel}
              </button>
              <button className="btn btn-outline btn-lg" onClick={onOpenCourseOverview}>
                <Icon name="list" size={14} /> {s.seeAll}
              </button>
            </div>
          )}
        </div>
      </header>

      {/* OUTCOMES */}
      {outcomes.length > 0 && (
        <section className="md-section">
          <h2 className="md-h2">{s.learnHere}</h2>
          <ul className="md-outcomes">
            {outcomes.map((o, i) => (
              <li key={i} className="md-outcome">
                <div className="md-outcome-pin"><Icon name="check" size={13} /></div>
                <div>{o}</div>
              </li>
            ))}
          </ul>
        </section>
      )}

      {/* CHAPTERS */}
      <section className="md-section">
        <h2 className="md-h2">{s.chapters}</h2>
        <ol className="md-chapters">
          {chapters.map((c, i) => {
            const chDone_i = course.enrolled && progress.isChapterDone(course.id, moduleIdx, i);
            return (
              <li key={i} className={"md-chapter" + (chDone_i ? " is-done" : "")}>
                <div className="md-chapter-num">
                  {chDone_i ? <Icon name="check" size={13} /> : String(i + 1).padStart(2, "0")}
                </div>
                <div className="md-chapter-title">{c[locale]}</div>
                <div className="md-chapter-time">{fmtTime(c.t)}</div>
              </li>
            );
          })}
        </ol>
      </section>

      {/* PRACTICE BRIEF */}
      <section className="md-section md-practice">
        <div className="md-practice-icon"><Icon name="briefcase" size={20} /></div>
        <div className="md-practice-body">
          <div className="md-practice-h">{s.practice}</div>
          <div className="md-practice-sub">{s.practiceSub}</div>
        </div>
      </section>

      {/* PREV / NEXT */}
      <section className="md-section">
        <h2 className="md-h2">{s.prevNext}</h2>
        <div className="md-prev-next">
          {prev ? (
            <ModuleNavCard
              dir="prev"
              label={s.prev}
              mod={prev}
              locale={locale}
              s={s}
              onClick={() => onOpenModule(course.id, prev.idx)}
            />
          ) : <div />}
          {next ? (
            <ModuleNavCard
              dir="next"
              label={s.next}
              mod={next}
              locale={locale}
              s={s}
              onClick={() => onOpenModule(course.id, next.idx)}
            />
          ) : <div />}
        </div>
      </section>
    </div>
  );
}

function ModuleStatusPill({ status, s }) {
  if (status === "done") {
    return <span className="md-pill done"><Icon name="check" size={11} /> {s.done}</span>;
  }
  if (status === "current") {
    return <span className="md-pill current"><span className="md-pill-dot" /> {s.current}</span>;
  }
  if (status === "next") {
    return <span className="md-pill next"><Icon name="arrow-right" size={11} /> {s.nextLab}</span>;
  }
  return <span className="md-pill locked"><Icon name="lock" size={11} /> {s.lockedLab}</span>;
}

function ModuleNavCard({ dir, label, mod, locale, s, onClick }) {
  const locked = mod.status === "locked";
  return (
    <button
      className={"md-nav-card " + dir + (locked ? " is-locked" : "")}
      onClick={locked ? undefined : onClick}
      disabled={locked}
    >
      <div className="md-nav-meta">
        {dir === "prev" && <Icon name="arrow-left" size={11} />}
        <span className="md-nav-lab">{label}</span>
        {dir === "next" && <Icon name="arrow-right" size={11} />}
      </div>
      <div className="md-nav-title-row">
        <span className="md-nav-num">{String(mod.idx + 1).padStart(2, "0")}</span>
        <span className="md-nav-title">{mod.title[locale]}</span>
        {locked && <Icon name="lock" size={12} />}
      </div>
      <div className="md-nav-foot">
        <span className="md-nav-dur"><Icon name="clock" size={11} /> {Math.floor(mod.dur / 60)} {s.minutes}</span>
        <ModuleStatusPill status={mod.status} s={s} />
      </div>
    </button>
  );
}

window.MOD_STRINGS = MOD_STRINGS;
window.ModuleDetail = ModuleDetail;
window.ModuleStatusPill = ModuleStatusPill;
