// Lumen — Course builder (drag modules/lessons)
function CourseBuilder({ onBack }) {
  const [modules, setModules] = React.useState(window.LUMEN_DATA.BUILDER_MODULES.map(m => ({...m, lessons: [...m.lessons]})));
  const [selectedLesson, setSelectedLesson] = React.useState("bl3");
  const [drag, setDrag] = React.useState(null); // {kind, mid, lid?}
  const [dropTarget, setDropTarget] = React.useState(null);
  const [title, setTitle] = React.useState("Course Creator OS");
  const [published, setPublished] = React.useState(false);

  const allLessons = modules.flatMap(m => m.lessons);
  const lesson = allLessons.find(l => l.id === selectedLesson) || allLessons[0];

  const addModule = () => {
    setModules([...modules, { id: "bm" + Date.now(), title: "New module", lessons: [] }]);
  };
  const addLesson = (mid, type = "video") => {
    setModules(modules.map(m => m.id === mid ? {
      ...m, lessons: [...m.lessons, { id: "bl" + Date.now(), title: "New lesson", type, duration: "—" }]
    } : m));
  };
  const deleteLesson = (mid, lid) => {
    setModules(modules.map(m => m.id === mid ? { ...m, lessons: m.lessons.filter(l => l.id !== lid) } : m));
  };

  // Drag handlers — module reorder
  const onModuleDrop = (toMid) => {
    if (drag?.kind !== "module" || drag.mid === toMid) return;
    const fromIdx = modules.findIndex(m => m.id === drag.mid);
    const toIdx = modules.findIndex(m => m.id === toMid);
    const next = [...modules];
    const [removed] = next.splice(fromIdx, 1);
    next.splice(toIdx, 0, removed);
    setModules(next);
  };
  // Drag handlers — lesson reorder (within or across modules)
  const onLessonDrop = (toMid, toLid) => {
    if (drag?.kind !== "lesson") return;
    const fromMod = modules.find(m => m.id === drag.mid);
    const lessonObj = fromMod.lessons.find(l => l.id === drag.lid);
    if (!lessonObj) return;
    let next = modules.map(m => m.id === drag.mid ? { ...m, lessons: m.lessons.filter(l => l.id !== drag.lid) } : m);
    next = next.map(m => {
      if (m.id !== toMid) return m;
      const ls = [...m.lessons];
      const idx = toLid ? ls.findIndex(l => l.id === toLid) : ls.length;
      ls.splice(idx, 0, lessonObj);
      return { ...m, lessons: ls };
    });
    setModules(next);
  };

  return (
    <div className="page">
      {/* Builder topbar */}
      <div style={{ display: "flex", alignItems: "center", padding: "12px 24px", borderBottom: "1px solid var(--border)", gap: 16, background: "var(--bg)", position: "sticky", top: 0, zIndex: 10 }}>
        <button className="btn btn--ghost btn--sm" onClick={onBack}>← Studio</button>
        <div style={{ width: 1, height: 20, background: "var(--border)" }}/>
        <input value={title} onChange={e => setTitle(e.target.value)}
          style={{ background: "transparent", border: "none", outline: "none", fontSize: 15, fontWeight: 600, fontFamily: "var(--font-display)", letterSpacing: "-0.01em", width: 320 }}/>
        <span className={`badge ${published ? "badge--green" : "badge--amber"} badge--dot`}>{published ? "Published" : "Draft"}</span>
        <span className="muted" style={{ fontSize: 12 }}>· Auto-saved 2s ago</span>
        <div className="spacer"/>
        <button className="btn btn--ghost btn--sm"><I.eye size={13}/> Preview</button>
        <button className="btn btn--secondary btn--sm">Schedule</button>
        <button className="btn btn--primary btn--sm" onClick={() => setPublished(!published)}>
          {published ? "Update live" : "Publish"}
        </button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "320px 1fr 320px", height: "calc(100vh - 56px)" }}>
        {/* Left: outline */}
        <div style={{ overflowY: "auto", borderRight: "1px solid var(--border)", background: "var(--bg-elev)" }}>
          <div className="row" style={{ padding: "16px 16px 8px", justifyContent: "space-between" }}>
            <div style={{ fontSize: 12, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--ink-3)" }}>Curriculum</div>
            <button className="btn btn--ghost btn--sm btn--icon" onClick={addModule}><I.plus size={14}/></button>
          </div>

          {modules.map((m, mi) => (
            <div key={m.id}
                 draggable
                 onDragStart={() => setDrag({ kind: "module", mid: m.id })}
                 onDragOver={e => { e.preventDefault(); if (drag?.kind === "module") setDropTarget(m.id); }}
                 onDrop={() => { onModuleDrop(m.id); setDrag(null); setDropTarget(null); }}
                 onDragEnd={() => { setDrag(null); setDropTarget(null); }}
                 style={{
                   borderTop: dropTarget === m.id && drag?.kind === "module" ? "2px solid var(--accent)" : "1px solid var(--border)",
                   padding: "8px 0",
                 }}>
              <div className="row" style={{ padding: "6px 12px", gap: 6 }}>
                <I.drag size={14} style={{ color: "var(--ink-4)", cursor: "grab" }}/>
                <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 600 }}>0{mi+1}</span>
                <input defaultValue={m.title} style={{ flex: 1, background: "transparent", border: "none", outline: "none", fontSize: 13, fontWeight: 600 }}/>
                <button className="btn btn--ghost btn--sm btn--icon" onClick={() => addLesson(m.id)}><I.plus size={12}/></button>
                <button className="btn btn--ghost btn--sm btn--icon"><I.more size={12}/></button>
              </div>

              <div onDragOver={e => { if (drag?.kind === "lesson") e.preventDefault(); }}
                   onDrop={() => { if (drag?.kind === "lesson") { onLessonDrop(m.id, null); setDrag(null); }}}
                   style={{ minHeight: 4 }}>
                {m.lessons.map(l => {
                  const Ic = l.type === "video" ? I.video : l.type === "quiz" ? I.quiz : I.text;
                  return (
                    <div key={l.id}
                         draggable
                         onDragStart={(e) => { e.stopPropagation(); setDrag({ kind: "lesson", mid: m.id, lid: l.id }); }}
                         onDragOver={e => { if (drag?.kind === "lesson") { e.preventDefault(); e.stopPropagation(); }}}
                         onDrop={(e) => { e.stopPropagation(); if (drag?.kind === "lesson") { onLessonDrop(m.id, l.id); setDrag(null); }}}
                         onClick={() => setSelectedLesson(l.id)}
                         style={{
                           padding: "8px 12px 8px 32px",
                           display: "flex", alignItems: "center", gap: 8,
                           cursor: "pointer",
                           background: selectedLesson === l.id ? "var(--bg)" : "transparent",
                           borderLeft: selectedLesson === l.id ? "2px solid var(--ink)" : "2px solid transparent",
                           opacity: drag?.kind === "lesson" && drag.lid === l.id ? 0.4 : 1,
                         }}>
                      <I.drag size={11} style={{ color: "var(--ink-4)" }}/>
                      <Ic size={12}/>
                      <span style={{ flex: 1, fontSize: 12, fontWeight: selectedLesson === l.id ? 500 : 400 }}>{l.title}</span>
                      <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{l.duration}</span>
                    </div>
                  );
                })}
              </div>

              {/* Add quick types */}
              <div className="row" style={{ padding: "4px 12px 4px 32px", gap: 4 }}>
                <button className="btn btn--ghost btn--sm" style={{ fontSize: 11, height: 22, padding: "0 6px" }} onClick={() => addLesson(m.id, "video")}>+ Video</button>
                <button className="btn btn--ghost btn--sm" style={{ fontSize: 11, height: 22, padding: "0 6px" }} onClick={() => addLesson(m.id, "text")}>+ Text</button>
                <button className="btn btn--ghost btn--sm" style={{ fontSize: 11, height: 22, padding: "0 6px" }} onClick={() => addLesson(m.id, "quiz")}>+ Quiz</button>
              </div>
            </div>
          ))}

          <div style={{ padding: "12px 16px", borderTop: "1px solid var(--border)" }}>
            <button className="btn btn--secondary btn--sm" style={{ width: "100%", justifyContent: "center" }} onClick={addModule}>
              <I.plus size={14}/> Add module
            </button>
          </div>
        </div>

        {/* Middle: lesson editor */}
        <div style={{ overflowY: "auto", padding: 32 }}>
          <div style={{ maxWidth: 720, margin: "0 auto" }}>
            <div className="row" style={{ marginBottom: 16, color: "var(--ink-3)", fontSize: 12 }}>
              <span>Module 2 · Audience & positioning</span>
              <span>/</span>
              <strong style={{ color: "var(--ink)" }}>{lesson.title}</strong>
            </div>
            <input defaultValue={lesson.title}
              style={{ background: "transparent", border: "none", outline: "none", fontSize: 28, fontWeight: 600, fontFamily: "var(--font-display)", letterSpacing: "-0.025em", width: "100%", marginBottom: 8 }}/>
            <input placeholder="Add a short description that appears on the lesson page…" defaultValue="The math behind 1,000 true fans, why most creators get it wrong, and the framework Mara used to find her first 200 buyers."
              style={{ background: "transparent", border: "none", outline: "none", fontSize: 14, color: "var(--ink-3)", width: "100%", marginBottom: 24 }}/>

            {/* Video upload */}
            <div style={{ border: "2px dashed var(--border-strong)", borderRadius: 12, padding: 32, textAlign: "center", marginBottom: 24, background: "var(--bg-elev)" }}>
              <div style={{ width: 56, height: 56, borderRadius: 12, background: "var(--bg)", border: "1px solid var(--border)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 12 }}>
                <I.video size={20}/>
              </div>
              <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 4 }}>positioning-1000-fans.mp4</div>
              <div className="muted" style={{ fontSize: 12, marginBottom: 12 }}>1080p · 12:08 · 184 MB · uploaded 3 days ago</div>
              <div className="row" style={{ justifyContent: "center" }}>
                <button className="btn btn--secondary btn--sm"><I.upload size={13}/> Replace</button>
                <button className="btn btn--secondary btn--sm"><I.sparkle size={13}/> Generate chapters with AI</button>
                <button className="btn btn--secondary btn--sm"><I.text size={13}/> Edit transcript</button>
              </div>
            </div>

            {/* Rich text body */}
            <div style={{ border: "1px solid var(--border)", borderRadius: 12, overflow: "hidden", background: "var(--bg)" }}>
              <div className="row" style={{ padding: "8px 12px", borderBottom: "1px solid var(--border)", background: "var(--bg-elev)", gap: 4 }}>
                {["B","i","U","H₁","H₂","≡","“","</>"].map(b => (
                  <button key={b} className="btn btn--ghost btn--sm btn--icon" style={{ fontSize: 12, fontWeight: 500 }}>{b}</button>
                ))}
                <div style={{ width: 1, height: 18, background: "var(--border)", margin: "0 4px" }}/>
                <button className="btn btn--ghost btn--sm" style={{ fontSize: 11 }}><I.sparkle size={12}/> AI</button>
              </div>
              <div style={{ padding: 24, fontSize: 14, lineHeight: 1.7, color: "var(--ink-2)" }}>
                <p style={{ margin: "0 0 12px" }}>The 1,000 true fans essay is brilliant — but the math everyone quotes is wrong. <strong>$100/year × 1,000</strong> assumes infinite supply of attention and zero churn.</p>
                <p style={{ margin: "0 0 12px" }}>Here's the reframe I want you to walk away with:</p>
                <ul style={{ marginTop: 0, paddingLeft: 20 }}>
                  <li>You don't need 1,000 fans. You need <em>200 paying ones</em> who care.</li>
                  <li>The bar isn't "true fan." It's "this solved my problem this quarter."</li>
                  <li>Outcome &gt; aesthetic. Always.</li>
                </ul>
              </div>
            </div>
          </div>
        </div>

        {/* Right: settings */}
        <div style={{ overflowY: "auto", borderLeft: "1px solid var(--border)", background: "var(--bg-elev)", padding: 16 }}>
          <div style={{ fontSize: 12, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--ink-3)", marginBottom: 12 }}>Lesson settings</div>

          <div className="col" style={{ gap: 14 }}>
            <div>
              <label className="label">Visibility</label>
              <select className="select"><option>Drip — unlocks on day 7</option><option>Available immediately</option><option>Locked until previous complete</option></select>
            </div>
            <div>
              <label className="label">Type</label>
              <div className="row" style={{ gap: 4 }}>
                {[["video","Video",I.video],["text","Text",I.text],["quiz","Quiz",I.quiz]].map(([k,l,Ic]) => (
                  <button key={k} className={`btn ${lesson.type===k?"btn--primary":"btn--secondary"} btn--sm`} style={{ flex: 1, justifyContent: "center" }}>
                    <Ic size={12}/> {l}
                  </button>
                ))}
              </div>
            </div>
            <div>
              <label className="label">Free preview</label>
              <div className="row" style={{ justifyContent: "space-between", padding: "8px 12px", border: "1px solid var(--border)", borderRadius: 6, background: "var(--bg)" }}>
                <span style={{ fontSize: 13 }}>Available without purchase</span>
                <Toggle/>
              </div>
            </div>
            <div>
              <label className="label">Downloads (3)</label>
              <div className="col" style={{ gap: 6 }}>
                {["Positioning workbook.pdf", "Niche-finder template.notion", "Slides.key"].map(f => (
                  <div key={f} className="row" style={{ padding: "6px 10px", background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 6, fontSize: 12 }}>
                    <I.download size={11}/>
                    <span style={{ flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f}</span>
                    <I.x size={11} style={{ color: "var(--ink-3)", cursor: "pointer" }}/>
                  </div>
                ))}
                <button className="btn btn--secondary btn--sm" style={{ justifyContent: "center" }}><I.plus size={12}/> Add file</button>
              </div>
            </div>

            <div style={{ height: 1, background: "var(--border)", margin: "8px 0" }}/>

            <div style={{ fontSize: 12, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--ink-3)" }}>AI assistant</div>
            <div style={{ padding: 14, background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 8 }}>
              <div className="row" style={{ marginBottom: 8 }}><I.sparkle size={13}/> <strong style={{ fontSize: 13 }}>Suggested next steps</strong></div>
              <div className="col" style={{ gap: 6, fontSize: 12, color: "var(--ink-2)" }}>
                <div className="row"><I.check size={11} style={{color:"var(--green)"}}/> Add 5 quiz questions from transcript</div>
                <div className="row"><I.check size={11} style={{color:"var(--green)"}}/> Generate lesson summary</div>
                <div className="row"><I.check size={11} style={{color:"var(--ink-3)"}}/> Translate captions to ES, FR, PT</div>
              </div>
              <button className="btn btn--primary btn--sm" style={{ width: "100%", justifyContent: "center", marginTop: 10 }}>Run all <I.arrowRight size={12}/></button>
            </div>

            <button className="btn btn--ghost btn--sm" style={{ color: "var(--red)", justifyContent: "center" }}>
              <I.trash size={13}/> Delete lesson
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function Toggle({ defaultOn = true }) {
  const [on, setOn] = React.useState(defaultOn);
  return (
    <button onClick={() => setOn(!on)} style={{
      width: 32, height: 18, borderRadius: 999,
      background: on ? "var(--ink)" : "var(--border-strong)",
      position: "relative", transition: "background 120ms"
    }}>
      <span style={{
        position: "absolute", top: 2, left: on ? 16 : 2,
        width: 14, height: 14, borderRadius: "50%", background: "white",
        transition: "left 120ms",
      }}/>
    </button>
  );
}

window.CourseBuilder = CourseBuilder;
