/* ============================================================
   CURIO — My library (creator-only)
   ============================================================ */

/* ---------- Shared app topbar ---------- */
function Topbar({ go, title, sub, children, back, user }) {
  const u = user || window.__user || null;
  const displayName = u?.name || u?.email || 'Alex Rivera';
  return (
    <div className="topbar">
      {back && <button className="btn btn-icon btn-ghost" onClick={back}><ChevL size={18} /></button>}
      <div style={{ minWidth: 0, flexShrink: 0 }}>
        <div className="row" style={{ gap: 10 }}>
          <h1 style={{ fontSize: 19, letterSpacing: '-0.02em', whiteSpace: 'nowrap' }}>{title}</h1>
          {sub && <span className="muted topbar-sub" style={{ fontSize: 13.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</span>}
        </div>
      </div>
      <div className="grow" />
      {children}
      <button className="btn btn-icon btn-ghost"><Search size={18} /></button>
      <button className="btn btn-icon btn-ghost" style={{ position: 'relative' }}>
        <Bell size={18} /><span style={{ position: 'absolute', top: 8, right: 9, width: 7, height: 7, borderRadius: 50, background: 'var(--rose)', border: '1.5px solid var(--surface)' }} />
      </button>
      <Avatar name={displayName} size={34} style={{ cursor: 'pointer', marginLeft: 4 }} />
    </div>
  );
}

/* ---------- Library (the only mode) ---------- */
function Browser({ go, params = {}, view = 'library', user }) {
  const [myCourses, setMyCourses] = useState(null); // null = loading
  useEffect(() => {
    let cancelled = false;
    window.API.listCourses()
      .then(d => { if (!cancelled) setMyCourses(d?.courses || []); })
      .catch(() => { if (!cancelled) setMyCourses([]); });
    return () => { cancelled = true; };
  }, []);

  const u = user || window.__user || null;
  const sub = u?.name || u?.email || '';
  const count = (myCourses || []).length;

  return (
    <div data-app-scroll className="scroll" style={{ height: '100vh', overflowY: 'auto' }} data-screen-label="My library">
      <Topbar go={go} title="My library" sub={sub} user={user}>
        <Btn variant="ai" size="sm" onClick={() => go('creator')} icon={<Sparkles size={15} />}>New course</Btn>
      </Topbar>

      <div style={{ maxWidth: 1180, margin: '0 auto', padding: '28px 32px 64px' }}>
        {myCourses == null ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 18 }}>
            {[0, 1, 2, 3].map(i => (
              <div key={i} className="card" style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div className="skeleton" style={{ aspectRatio: '16/10', borderRadius: 10 }} />
                <div className="skeleton" style={{ height: 14, width: '70%' }} />
                <div className="skeleton" style={{ height: 11, width: '90%' }} />
                <div className="skeleton" style={{ height: 11, width: '55%' }} />
              </div>
            ))}
          </div>
        ) : count === 0 ? (
          <EmptyLibrary go={go} />
        ) : (
          <>
            <SectionHeading title="Your courses" count={count} />
            <CourseGrid courses={myCourses.map(uiFromList)} go={go} />
          </>
        )}
      </div>
    </div>
  );
}

function EmptyLibrary({ go }) {
  return (
    <div className="center" style={{ minHeight: '60vh' }}>
      <div className="card" style={{ padding: '44px 40px', maxWidth: 460, textAlign: 'center', boxShadow: 'var(--sh-sm)' }}>
        <div className="center" style={{ width: 64, height: 64, borderRadius: 18, background: 'var(--ai-grad)', margin: '0 auto', boxShadow: 'var(--sh-brand)' }}>
          <Sparkles size={28} style={{ color: '#fff' }} />
        </div>
        <h2 style={{ fontSize: 22, letterSpacing: '-0.02em', marginTop: 22 }}>No courses yet</h2>
        <p className="muted" style={{ fontSize: 14.5, marginTop: 10, lineHeight: 1.55 }}>
          Describe what you'd like to teach and Coursedy builds a complete course — modules, lessons, quizzes, and slide notes.
        </p>
        <div style={{ marginTop: 22 }}>
          <Btn variant="brand" onClick={() => go('creator')} icon={<Plus size={15} />}>Create your first course</Btn>
        </div>
      </div>
    </div>
  );
}

function SectionHeading({ title, count, link, onLink }) {
  return (
    <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
      <div className="row" style={{ gap: 10 }}>
        <h2 style={{ fontSize: 19, letterSpacing: '-0.02em' }}>{title}</h2>
        {count != null && <span className="pill" style={{ height: 24, fontSize: 12.5 }}>{count}</span>}
      </div>
      {link && <a className="row" style={{ gap: 4, fontSize: 13.5, fontWeight: 600, color: 'var(--brand)', cursor: 'pointer' }} onClick={onLink}>{link} <ChevR size={15} /></a>}
    </div>
  );
}

function CourseGrid({ courses, go }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 18 }}>
      {courses.map(c => <CourseCard key={c.id} course={c} onClick={() => go('creator', { editId: c.id })} />)}
    </div>
  );
}

/* ============================================================
   CourseDetail — legacy redirect to the creator editor
   ============================================================ */
const isRealCourseId = (id) => typeof id === 'string' && /^c[a-z0-9]{20,}$/i.test(id);

function CourseDetail({ go, id }) {
  useEffect(() => {
    if (id) go('creator', { editId: id });
    else go('library');
  }, []); // eslint-disable-line react-hooks/exhaustive-deps
  return null;
}

function LessonIcon({ type }) {
  const map = { lesson: 'PlayCircle', quiz: 'Help', project: 'Target' };
  const Icon = ICON_BY_NAME(map[type] || 'PlayCircle');
  const color = { lesson: 'var(--brand)', quiz: 'var(--amber)', project: 'var(--green)' }[type] || 'var(--brand)';
  return <Icon size={16} style={{ color, flexShrink: 0 }} />;
}

// Map a backend list-row (from GET /api/courses) to the card shape expected by CourseCard.
function uiFromList(c) {
  return {
    id: c.id,
    title: c.title,
    subtitle: c.description?.split(/[.!?]\s/)[0]?.slice(0, 140) || "",
    cat: window.guessCat ? window.guessCat(c.title) : "data",
    level: ({ beginner: "Beginner", intermediate: "Intermediate", advanced: "Advanced" })[c.difficulty] || "Beginner",
    rating: 4.9, learners: 0,
    hours: ((c.moduleCount || 1) * 0.8).toFixed(1),
    author: { name: c.audience || "AI-generated", kind: "ai" },
    lessonsN: c.moduleTotal * 3 || 0,
    quizzes: c.moduleTotal || 0,
    tags: [c.difficulty, c.tone].filter(Boolean),
    modules: [],
    status: c.status || "ready",
  };
}

Object.assign(window, { Browser, CourseDetail, Topbar, LessonIcon, SectionHeading, CourseGrid, uiFromList, isRealCourseId });
