// ─────────────────────────────────────────────────────────────
// DASHBOARD — stat cards, recent activity, upcoming deadlines
// ─────────────────────────────────────────────────────────────
function Dashboard({ profile, tasks, projects, profiles, onOpenTask, onNav }) {
  const { Card, StatusBadge, PriorityBadge, Empty } = window.PUI;
  const P = window.PORTAL;
  const [activity, setActivity] = React.useState([]);

  React.useEffect(() => {
    sb.from("activity_logs").select("*, actor:profiles(full_name)")
      .order("created_at", { ascending: false }).limit(10)
      .then(({ data }) => setActivity(data || []));
  }, [tasks]);

  const today = new Date(); today.setHours(0,0,0,0);
  const weekAgo = new Date(Date.now() - 7 * 86400000);
  const isToday = (d) => { if (!d) return false; const x = new Date(d + "T00:00:00"); return x.getTime() === today.getTime(); };

  const stats = [
    { label: "Active Projects",     value: projects.filter(p => p.status === "active").length, view: "projects" },
    { label: "Tasks Due Today",     value: tasks.filter(t => isToday(t.due_date) && t.status !== "completed").length, view: "tasks" },
    { label: "Awaiting Review",     value: tasks.filter(t => t.status === "awaiting_review").length, view: "tasks" },
    { label: "Completed This Week", value: tasks.filter(t => t.status === "completed" && new Date(t.updated_at) > weekAgo).length, view: "tasks" },
  ];

  const upcoming = tasks
    .filter(t => t.due_date && t.status !== "completed")
    .sort((a, b) => a.due_date.localeCompare(b.due_date))
    .slice(0, 6);

  const nameOf = (id) => profiles.find(p => p.id === id)?.full_name || "—";
  const projectOf = (id) => projects.find(p => p.id === id)?.name || "—";

  return (
    <div>
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 13, color: "var(--text-tertiary)", marginBottom: 4 }}>
          {new Date().toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" })}
        </div>
        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 30, letterSpacing: "-0.03em" }}>
          Welcome back, <span style={{ color: "var(--gold-500)" }}>{(profile.full_name || "there").split(" ")[0]}</span>.
        </h1>
      </div>

      {/* Stat cards */}
      <div className="pgrid-4" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14, marginBottom: 28 }}>
        {stats.map(s => (
          <Card key={s.label} hover onClick={() => onNav(s.view)} padding={22}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 34, letterSpacing: "-0.04em", color: "var(--text-primary)" }}>{s.value}</div>
            <div style={{ fontSize: 12, color: "var(--text-tertiary)", marginTop: 4, letterSpacing: "0.02em" }}>{s.label}</div>
          </Card>
        ))}
      </div>

      <div className="pgrid-2" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 14 }}>
        {/* Upcoming deadlines */}
        <Card padding={0}>
          <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border-subtle)", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16 }}>Upcoming Deadlines</div>
          {upcoming.length === 0
            ? <Empty icon="✓" title="Nothing due" sub="No open tasks with deadlines." />
            : upcoming.map(t => {
              const overdue = new Date(t.due_date + "T23:59:59") < new Date();
              return (
                <div key={t.id} onClick={() => onOpenTask(t.id)} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 22px", borderBottom: "1px solid var(--border-subtle)", cursor: "pointer" }}
                  onMouseEnter={(e) => e.currentTarget.style.background = "rgba(255,255,255,0.02)"}
                  onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{t.title}</div>
                    <div style={{ fontSize: 12, color: "var(--text-tertiary)", marginTop: 2 }}>{projectOf(t.project_id)} · {nameOf(t.assigned_editor)}</div>
                  </div>
                  <PriorityBadge priority={t.priority} />
                  <span style={{ fontSize: 12, fontWeight: 700, color: overdue ? "#E2492E" : "var(--text-secondary)", whiteSpace: "nowrap" }}>{P.fmtDate(t.due_date)}</span>
                </div>
              );
            })}
        </Card>

        {/* Recent activity */}
        <Card padding={0}>
          <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border-subtle)", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16 }}>Recent Activity</div>
          {activity.length === 0
            ? <Empty icon="◷" title="No activity yet" />
            : activity.map(a => (
              <div key={a.id} onClick={() => a.task_id && onOpenTask(a.task_id)} style={{ display: "flex", gap: 12, padding: "13px 22px", borderBottom: "1px solid var(--border-subtle)", cursor: "pointer" }}>
                <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--gold-500)", flexShrink: 0, marginTop: 6 }} />
                <div>
                  <div style={{ fontSize: 13, color: "var(--text-secondary)", lineHeight: 1.5 }}>
                    <strong style={{ color: "var(--text-primary)" }}>{a.actor?.full_name || "Someone"}</strong> {a.action}
                  </div>
                  <div style={{ fontSize: 11, color: "var(--text-tertiary)", marginTop: 2 }}>{P.timeAgo(a.created_at)}</div>
                </div>
              </div>
            ))}
        </Card>
      </div>
    </div>
  );
}
window.Dashboard = Dashboard;
