// Quizrs — Dashboard / Home (wired to real usage + library)

function Dashboard({ go }) {
  const { user, quizzes, usage, libraryLoading, backendIssue } = useStore();

  const live = quizzes.filter((q) => q.status === "live");
  const drafts = quizzes.filter((q) => q.status === "draft");
  const totalPlays = quizzes.reduce((a, q) => a + (q.plays || 0), 0);
  const recent = [...live].sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt)).slice(0, 3);

  const quotaLabel = usage
    ? `${usage.quizzesUsed}${usage.quotaLimit != null ? " / " + usage.quotaLimit : ""}`
    : "—";

  const hour = new Date().getHours();
  const greet = hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening";
  const today = new Date().toLocaleDateString(undefined, { weekday: "long", month: "long", day: "numeric" });

  // Activity feed derived from real quiz events (publish/update), newest first.
  const activity = [...quizzes]
    .sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
    .slice(0, 5)
    .map((q) => ({
      who: user?.name || "You",
      did: q.status === "live" ? "published" : "drafted",
      what: q.title,
      meta: `${q.questionCount} ${q.isPoll ? "options" : "questions"}`,
      when: q.updated,
    }));

  return (
    <div className="screen-pad fade">
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 22, flexWrap: "wrap", gap: 12 }}>
        <div>
          <div className="muted" style={{ fontSize: 13.5, fontWeight: 600 }}>{today}</div>
          <h2 style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-.6px", margin: "2px 0 0" }}>{greet}, {(user?.name || "there").split(" ")[0]}</h2>
        </div>
        <div className="row">
          <Btn kind="ghost" icon="play" onClick={() => go("library")}>Browse quizzes</Btn>
          <Btn kind="primary" icon="plus" onClick={() => go("creator")}>New quiz</Btn>
        </div>
      </div>

      <ErrorNote>{backendIssue}</ErrorNote>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14, marginBottom: 22 }}>
        <Stat k="Total quizzes" icon="library" v={String(quizzes.length)} delta={`${drafts.length} drafts`} up />
        <Stat k="Published" icon="check" v={String(live.length)} delta="live" up />
        <Stat k="Total plays" icon="play" v={totalPlays.toLocaleString()} delta="all time" up />
        <Stat k="Quota used" icon="stats" v={quotaLabel} delta={usage?.plan ? usage.plan + " plan" : ""} up={false} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.55fr 1fr", gap: 18, alignItems: "start" }}>
        <div className="col" style={{ gap: 18 }}>
          <section>
            <div style={{ display: "flex", alignItems: "center", marginBottom: 11 }}>
              <h3 className="h-sec" style={{ margin: 0 }}>Continue building</h3>
              <span className="muted" style={{ fontSize: 12.5, marginLeft: 8 }}>{drafts.length} drafts</span>
              <span style={{ flex: 1 }} />
              <Btn kind="quiet" sm iconR="arrowR" onClick={() => go("library")}>All quizzes</Btn>
            </div>
            {libraryLoading && !quizzes.length ? (
              <Loading label="Loading your quizzes…" />
            ) : drafts.length === 0 ? (
              <EmptyState icon="edit" title="No drafts yet" hint="Generate a quiz or poll to get started."
                action={<Btn kind="primary" sm icon="plus" onClick={() => go("creator")}>New quiz</Btn>} />
            ) : (
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                {drafts.slice(0, 4).map((q) => (
                  <button key={q.id} className="card" onClick={() => go("creator", { id: q.id })}
                    style={{ textAlign: "left", cursor: "pointer", padding: 0, overflow: "hidden", font: "inherit", color: "inherit" }}>
                    <div className="card-pad" style={{ display: "flex", gap: 13 }}>
                      <div style={{ width: 52, flex: "0 0 auto" }}><Cover tint={q.tint} glyph={q.glyph} h={52} /></div>
                      <div style={{ minWidth: 0, flex: 1 }}>
                        <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 5 }}>
                          <Badge tone="amber" dot>Draft</Badge>
                          <span className="muted mono" style={{ fontSize: 11 }}>{q.updated}</span>
                        </div>
                        <div style={{ fontWeight: 650, fontSize: 14.5, letterSpacing: "-.2px", lineHeight: 1.25,
                          whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{q.title}</div>
                        <div className="muted" style={{ fontSize: 12.5, marginTop: 3 }}>{q.questionCount} {q.isPoll ? "options" : "questions"} · {q.subject}</div>
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </section>

          <section className="card card-pad">
            <div style={{ display: "flex", alignItems: "center", marginBottom: 14 }}>
              <h3 className="h-sec" style={{ margin: 0 }}>Recently published</h3>
              <span style={{ flex: 1 }} />
              {live.length > 0 && <Badge tone="green" dot>{live.length} live</Badge>}
            </div>
            {recent.length === 0 ? (
              <div className="muted" style={{ fontSize: 13.5, padding: "8px 2px" }}>Nothing published yet — publish a quiz to share it.</div>
            ) : (
              <div className="col" style={{ gap: 2 }}>
                {recent.map((q, i) => (
                  <button key={q.id} onClick={() => go("stats", { id: q.id })}
                    style={{ display: "flex", alignItems: "center", gap: 13, padding: "11px 8px", border: 0,
                      borderTop: i ? "1px solid var(--hairline)" : "0", background: "transparent",
                      cursor: "pointer", font: "inherit", color: "inherit", textAlign: "left", borderRadius: 8 }}
                    onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-2)")}
                    onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
                    <div style={{ width: 34 }}><Cover tint={q.tint} glyph={q.glyph} h={34} r={8} /></div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{q.title}</div>
                      <div className="muted" style={{ fontSize: 12 }}>{q.subject} · {q.plays} plays</div>
                    </div>
                    <Icon name="chevR" size={16} className="muted" />
                  </button>
                ))}
              </div>
            )}
          </section>
        </div>

        <div className="col" style={{ gap: 18 }}>
          <section className="card card-pad">
            <div style={{ display: "flex", alignItems: "center", marginBottom: 14 }}>
              <h3 className="h-sec" style={{ margin: 0 }}>Plan &amp; usage</h3>
              <span style={{ flex: 1 }} />
              <Badge tone="accent">{usage?.plan || user?.plan || "free"}</Badge>
            </div>
            <div className="muted" style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 6 }}>Quizzes this period</div>
            <div className="row" style={{ gap: 10, marginBottom: 6 }}>
              <div style={{ flex: 1 }}><Progress pct={usage?.quotaLimit ? Math.min(100, (usage.quizzesUsed / usage.quotaLimit) * 100) : 0} /></div>
              <span className="tnum" style={{ fontWeight: 700, fontSize: 14 }}>{quotaLabel}</span>
            </div>
            {usage?.quotaLimit != null && usage.quizzesUsed >= usage.quotaLimit && (
              <div className="muted" style={{ fontSize: 12 }}>You've reached your plan limit.</div>
            )}
          </section>

          <section className="card card-pad">
            <h3 className="h-sec" style={{ margin: "0 0 14px" }}>Activity</h3>
            {activity.length === 0 ? (
              <div className="muted" style={{ fontSize: 13 }}>No activity yet.</div>
            ) : (
              <div className="col" style={{ gap: 14 }}>
                {activity.map((a, i) => (
                  <div key={i} className="row" style={{ alignItems: "flex-start", gap: 10 }}>
                    <Avatar name={a.who} size={28} />
                    <div style={{ flex: 1, fontSize: 13, lineHeight: 1.4 }}>
                      <span style={{ fontWeight: 600 }}>{a.who}</span>
                      <span className="muted"> {a.did} </span>
                      <span style={{ fontWeight: 500 }}>{a.what}</span>
                      <div className="muted" style={{ fontSize: 11.5, marginTop: 1 }}>{a.meta} · {a.when}</div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </section>
        </div>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
