// Quizrs — Quiz Library (wired to /v1/me/quizzes)

function StatusBadge({ status }) {
  return status === "live"
    ? <Badge tone="green" dot>Live</Badge>
    : <Badge tone="amber" dot>Draft</Badge>;
}

function QuizMenu({ q, go, onShare }) {
  const { folders, setFolder } = useStore();
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, [open]);
  const assign = (name) => { setFolder(q.id, name); setOpen(false); };
  return (
    <div ref={ref} style={{ position: "relative" }} onClick={(e) => e.stopPropagation()}>
      <Btn kind="ghost" sm icon="dots" onClick={() => setOpen((o) => !o)} />
      {open && (
        <div className="card" style={{ position: "absolute", right: 0, top: "100%", marginTop: 4, zIndex: 50, width: 200, padding: 6, boxShadow: "var(--shadow-lg)" }}>
          <MenuItem icon="edit" label="Open in creator" onClick={() => go("creator", { id: q.id })} />
          <MenuItem icon="stats" label="View results" onClick={() => go("stats", { id: q.id })} />
          <MenuItem icon="eye" label="Preview / play" onClick={() => go("player", { id: q.id })} />
          <MenuItem icon="copy" label="Share & embed" onClick={() => onShare(q)} />
          <div className="divider" style={{ margin: "5px 0" }} />
          <div className="muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase", padding: "4px 8px" }}>Collection</div>
          {folders.map((f) => (
            <MenuItem key={f.name} icon={q.folder === f.name ? "check" : "library"} label={f.name} onClick={() => assign(f.name)} />
          ))}
          <MenuItem icon="plus" label="New collection…" onClick={() => { const n = prompt("Collection name"); if (n) assign(n.trim()); }} />
          {q.folder && <MenuItem icon="x" label="Remove from collection" onClick={() => assign(null)} />}
        </div>
      )}
    </div>
  );
}

function MenuItem({ icon, label, onClick }) {
  return (
    <button onClick={onClick} className="qz-palette-row" style={{ padding: "8px 10px", borderRadius: "var(--r-sm)", fontSize: 13.5, fontWeight: 500 }}>
      <Icon name={icon} size={15} className="muted" />
      <span style={{ flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{label}</span>
    </button>
  );
}

function QuizCard({ q, go, onShare }) {
  return (
    <div className="card" style={{ overflow: "hidden", display: "flex", flexDirection: "column", transition: "border-color .12s, box-shadow .12s, transform .08s" }}
      onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--accent)"; e.currentTarget.style.boxShadow = "var(--shadow)"; e.currentTarget.style.transform = "translateY(-2px)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--border)"; e.currentTarget.style.boxShadow = "var(--shadow-sm)"; e.currentTarget.style.transform = "none"; }}>
      <button onClick={() => go("stats", { id: q.id })} style={{ border: 0, background: "transparent", padding: 0, cursor: "pointer", textAlign: "left", color: "inherit", font: "inherit" }}>
        <Cover tint={q.tint} glyph={q.glyph} h={104} r={0} />
      </button>
      <div className="card-pad" style={{ display: "flex", flexDirection: "column", gap: 9, flex: 1 }}>
        <div className="row" style={{ justifyContent: "space-between" }}>
          <StatusBadge status={q.status} />
          <div className="row" style={{ gap: 6 }}>
            <span className="muted mono" style={{ fontSize: 11 }}>{q.updated}</span>
            <QuizMenu q={q} go={go} onShare={onShare} />
          </div>
        </div>
        <button onClick={() => go("stats", { id: q.id })} style={{ border: 0, background: "transparent", padding: 0, cursor: "pointer", textAlign: "left", color: "inherit", font: "inherit" }}>
          <div style={{ fontWeight: 650, fontSize: 15, letterSpacing: "-.2px", lineHeight: 1.3 }}>{q.title}</div>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 3 }}>{q.subject}{q.folder ? " · " + q.folder : ""}</div>
        </button>
        <div className="row" style={{ gap: 14, marginTop: "auto", paddingTop: 10, borderTop: "1px solid var(--hairline)" }}>
          <span className="row muted" style={{ gap: 5, fontSize: 12.5, fontWeight: 500 }}><Icon name="list" size={14} />{q.questionCount}</span>
          <span className="row muted" style={{ gap: 5, fontSize: 12.5, fontWeight: 500 }}><Icon name="play" size={14} />{q.plays}</span>
          <span style={{ flex: 1 }} />
          <Btn kind="quiet" sm icon="eye" onClick={() => go("player", { id: q.id })} />
        </div>
      </div>
    </div>
  );
}

function QuizRow({ q, go, onShare, i }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "2.6fr 1fr .8fr .8fr 1fr 40px", alignItems: "center", gap: 12,
      padding: "11px 16px", borderTop: i ? "1px solid var(--hairline)" : "0" }}>
      <button onClick={() => go("stats", { id: q.id })} className="row" style={{ gap: 12, minWidth: 0, border: 0, background: "transparent", cursor: "pointer", font: "inherit", color: "inherit", textAlign: "left" }}>
        <div style={{ width: 36, flex: "0 0 auto" }}><Cover tint={q.tint} glyph={q.glyph} h={36} r={8} /></div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{q.title}</div>
          <div className="muted" style={{ fontSize: 12 }}>{q.folder || q.subject}</div>
        </div>
      </button>
      <span className="muted" style={{ fontSize: 13 }}>{q.subject}</span>
      <span className="muted tnum" style={{ fontSize: 13 }}>{q.questionCount} Qs</span>
      <span className="muted tnum" style={{ fontSize: 13 }}>{q.plays}</span>
      <StatusBadge status={q.status} />
      <QuizMenu q={q} go={go} onShare={onShare} />
    </div>
  );
}

function Library({ go, params }) {
  const { quizzes, libraryLoading, folders, backendIssue } = useStore();
  const [view, setView] = React.useState("grid");
  const [filter, setFilter] = React.useState(params?.filter || "All");
  const [query, setQuery] = React.useState("");
  const [share, setShare] = React.useState(null);

  React.useEffect(() => { if (params?.filter) setFilter(params.filter); }, [params?.filter]);

  const chips = ["All", "Quiz", "Poll", ...folders.map((f) => f.name)];
  const folderNames = new Set(folders.map((f) => f.name));

  const filtered = quizzes.filter((q) => {
    const matchFilter =
      filter === "All" ? true :
      folderNames.has(filter) ? q.folder === filter :
      q.subject === filter;
    const matchQuery = !query || q.title.toLowerCase().includes(query.toLowerCase()) || q.subject.toLowerCase().includes(query.toLowerCase());
    return matchFilter && matchQuery;
  });

  return (
    <div className="screen-pad fade">
      {share && <ShareDialog quiz={share} onClose={() => setShare(null)} />}
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 18, flexWrap: "wrap", gap: 12 }}>
        <div>
          <h2 style={{ fontSize: 24, fontWeight: 700, letterSpacing: "-.5px", margin: 0 }}>Quiz Library</h2>
          <div className="muted" style={{ fontSize: 13.5, marginTop: 2 }}>{quizzes.length} quizzes · {quizzes.filter((q) => q.status === "live").length} live</div>
        </div>
        <Btn kind="primary" icon="plus" onClick={() => go("creator")}>New quiz</Btn>
      </div>

      <ErrorNote>{backendIssue}</ErrorNote>

      <div className="row" style={{ marginBottom: 16, gap: 10, flexWrap: "wrap" }}>
        <div className="search" style={{ minWidth: 260 }}>
          <Icon name="search" size={16} />
          <input placeholder="Search quizzes…" value={query} onChange={(e) => setQuery(e.target.value)} />
        </div>
        <span style={{ flex: 1 }} />
        <SegBar value={view} onChange={setView} options={[["grid", "", "grid"], ["list", "", "list"]]} />
      </div>

      <div className="row" style={{ gap: 8, marginBottom: 18, flexWrap: "wrap" }}>
        {chips.map((s) => {
          const on = filter === s;
          return (
            <button key={s} onClick={() => setFilter(s)}
              style={{ font: "inherit", fontSize: 13, fontWeight: 600, padding: "6px 13px", cursor: "pointer",
                borderRadius: "var(--r-pill)", border: "1px solid " + (on ? "transparent" : "var(--border)"),
                background: on ? "var(--accent)" : "var(--surface)", color: on ? "var(--accent-contrast)" : "var(--ink-2)" }}>
              {s}
            </button>
          );
        })}
      </div>

      {libraryLoading && !quizzes.length ? (
        <Loading label="Loading your quizzes…" />
      ) : quizzes.length === 0 ? (
        <EmptyState icon="library" title="No quizzes yet" hint="Generate your first quiz or poll."
          action={<Btn kind="primary" sm icon="plus" onClick={() => go("creator")}>New quiz</Btn>} />
      ) : filtered.length === 0 ? (
        <EmptyState icon="search" title={`No quizzes match “${query || filter}”`} hint="Try a different search or filter." />
      ) : view === "grid" ? (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(252px, 1fr))", gap: 16 }}>
          {filtered.map((q) => <QuizCard key={q.id} q={q} go={go} onShare={setShare} />)}
        </div>
      ) : (
        <div className="card" style={{ overflow: "hidden" }}>
          <div style={{ display: "grid", gridTemplateColumns: "2.6fr 1fr .8fr .8fr 1fr 40px", gap: 12, padding: "10px 16px",
            background: "var(--surface-2)", fontSize: 11.5, fontWeight: 700, letterSpacing: ".4px", color: "var(--ink-3)", textTransform: "uppercase" }}>
            <span>Quiz</span><span>Type</span><span>Length</span><span>Plays</span><span>Status</span><span></span>
          </div>
          {filtered.map((q, i) => <QuizRow key={q.id} q={q} go={go} onShare={setShare} i={i} />)}
        </div>
      )}
    </div>
  );
}

window.Library = Library;
