/* ===== Manager dashboard (overview of whole team) ===== */
const { useMemo: useMemoD } = React;

function ManagerDashboard({ tasks, members, onAddTask, onOpenTask, onGotoBoard }) {
  const stats = useMemoD(() => {
    const total = tasks.length;
    const byStatus = Object.fromEntries(STATUSES.map(s => [s.id, 0]));
    tasks.forEach(t => byStatus[t.status]++);
    const done = byStatus.done;
    const pct = total ? Math.round((done / total) * 100) : 0;

    // deadline alerts: not-done, sorted by urgency
    const alerts = tasks
      .filter(t => t.status !== "done")
      .map(t => ({ t, info: deadlineInfo(t.deadline) }))
      .filter(x => x.info.n <= 2)
      .sort((a, b) => a.info.n - b.info.n);

    // per member
    const perMember = members.map(m => {
      const mt = tasks.filter(t => t.assignee === m.id);
      const counts = Object.fromEntries(STATUSES.map(s => [s.id, 0]));
      mt.forEach(t => counts[t.status]++);
      const mDone = counts.done;
      const overdue = mt.filter(t => t.status !== "done" && deadlineInfo(t.deadline).n < 0).length;
      return { m, total: mt.length, counts, pct: mt.length ? Math.round((mDone / mt.length) * 100) : 0, overdue };
    });
    return { total, byStatus, done, pct, alerts, perMember };
  }, [tasks, members]);

  return (
    <div className="animate-pop">
      {/* page head */}
      <div style={mdStyles.head}>
        <div>
          <div style={mdStyles.kicker}>ภาพรวมทีม · Team overview</div>
          <h1 style={mdStyles.h1}>ภาพรวมงานของทีม วันนี้ 👋</h1>
          <div style={mdStyles.sub}>
            {fmtDate(TODAY.toISOString().slice(0,10))} 2569 · ทีม {members.length} คน · ทั้งหมด {stats.total} งาน
          </div>
        </div>
        <button className="btn btn-primary" onClick={() => onAddTask(null)}><PlusIcon /> มอบหมายงานใหม่</button>
      </div>

      {/* status summary + progress */}
      <div style={mdStyles.summaryGrid} className="summary-grid">
        {STATUSES.map(s => {
          const c = stats.byStatus[s.id];
          const share = stats.total ? Math.round((c / stats.total) * 100) : 0;
          return (
            <div key={s.id} className="card" style={mdStyles.statCard}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span className="dot" style={{ background: s.color, width: 9, height: 9 }}></span>
                <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink-2)", whiteSpace: "nowrap" }}>{s.label}</span>
              </div>
              <div style={{ display: "flex", alignItems: "flex-end", gap: 8, margin: "10px 0 4px" }}>
                <span style={{ fontFamily: "var(--font-num)", fontSize: 38, fontWeight: 700, lineHeight: 1, color: s.color }}>{c}</span>
                <span style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 5 }}>งาน · {share}%</span>
              </div>
              <div style={{ marginTop: 8 }}><ProgressBar value={share} color={s.color} height={6} /></div>
            </div>
          );
        })}
      </div>

      <div style={mdStyles.twoCol} className="two-col">
        {/* left: progress ring + deadline alerts */}
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <div className="card" style={{ padding: 22, display: "flex", alignItems: "center", gap: 22 }}>
            <ProgressRing pct={stats.pct} />
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink-2)" }}>ความคืบหน้ารวมของทีม</div>
              <div style={{ fontFamily: "var(--font-num)", fontSize: 30, fontWeight: 700, margin: "2px 0", color: "var(--ink)" }}>
                {stats.pct}<span style={{ fontSize: 18, color: "var(--ink-3)" }}>%</span>
              </div>
              <div style={{ fontSize: 13.5, color: "var(--ink-3)" }}>เสร็จแล้ว {stats.done} จาก {stats.total} งาน</div>
            </div>
          </div>

          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            <div style={mdStyles.panelHead}>
              <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                <span style={mdStyles.alertIco}><AlertIcon /></span>
                <span style={{ fontWeight: 700, fontSize: 15.5 }}>เตือน Deadline</span>
              </div>
              <span style={mdStyles.alertCount}>{stats.alerts.length}</span>
            </div>
            <div style={{ padding: "6px 10px 12px" }}>
              {stats.alerts.length === 0 && (
                <div style={{ padding: "22px 12px", textAlign: "center", color: "var(--ink-3)", fontSize: 13.5 }}>
                  เยี่ยม! ไม่มีงานที่ใกล้หรือเลยกำหนด 🎉
                </div>
              )}
              {stats.alerts.map(({ t, info }) => (
                <button key={t.id} className="hov-row" style={mdStyles.alertRow} onClick={() => onOpenTask(t)}>
                  <Avatar member={MEMBER_MAP[t.assignee]} size={32} />
                  <div style={{ flex: 1, minWidth: 0, textAlign: "left" }}>
                    <div style={mdStyles.alertTitle}>{t.title}</div>
                    <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{MEMBER_MAP[t.assignee].nick} · {STATUS_MAP[t.status].label}</div>
                  </div>
                  <DeadlineChip dateStr={t.deadline} />
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* right: per-member workload table */}
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div style={mdStyles.panelHead}>
            <span style={{ fontWeight: 700, fontSize: 15.5 }}>งานของแต่ละคน · Workload</span>
            <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>คลิกชื่อเพื่อเปิดบอร์ด</span>
          </div>
          <div style={mdStyles.tableHeadRow} className="wl-head">
            <span>สมาชิก</span>
            <span style={{ textAlign: "center" }}>To Do</span>
            <span style={{ textAlign: "center" }}>Doing</span>
            <span style={{ textAlign: "center" }}>Review</span>
            <span style={{ textAlign: "center" }}>Done</span>
            <span>ความคืบหน้า</span>
          </div>
          <div>
            {stats.perMember.map(({ m, total, counts, pct, overdue }) => (
              <button key={m.id} className="hov-row wl-row" style={mdStyles.memberRow} onClick={() => onGotoBoard(m.id)}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
                  <Avatar member={m} size={36} />
                  <div style={{ minWidth: 0, textAlign: "left" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                      <span style={{ fontWeight: 600, fontSize: 14 }}>{m.nick}</span>
                      {overdue > 0 && <span style={mdStyles.overdueTag}>เลย {overdue}</span>}
                    </div>
                    <div style={{ fontSize: 11.5, color: "var(--ink-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{m.role}</div>
                  </div>
                </div>
                <CountCell n={counts.todo} color="var(--todo)" />
                <CountCell n={counts.progress} color="var(--progress)" />
                <CountCell n={counts.review} color="var(--review)" />
                <CountCell n={counts.done} color="var(--done)" />
                <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                  <div style={{ flex: 1 }}><ProgressBar value={pct} color="var(--done)" height={7} /></div>
                  <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)", width: 34, textAlign: "right" }}>{pct}%</span>
                </div>
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function CountCell({ n, color }) {
  return (
    <div style={{ textAlign: "center" }}>
      <span style={{
        fontFamily: "var(--font-num)", fontWeight: 700, fontSize: 15,
        color: n ? color : "var(--ink-3)", opacity: n ? 1 : .4,
      }}>{n}</span>
    </div>
  );
}

function ProgressRing({ pct }) {
  const r = 34, c = 2 * Math.PI * r;
  const off = c - (pct / 100) * c;
  return (
    <svg width="92" height="92" viewBox="0 0 92 92" style={{ flex: "none" }}>
      <circle cx="46" cy="46" r={r} fill="none" stroke="var(--line-soft)" strokeWidth="11" />
      <circle cx="46" cy="46" r={r} fill="none" stroke="var(--done)" strokeWidth="11" strokeLinecap="round"
        strokeDasharray={c} strokeDashoffset={off} transform="rotate(-90 46 46)"
        style={{ transition: "stroke-dashoffset .7s cubic-bezier(.4,0,.2,1)" }} />
      <text x="46" y="46" textAnchor="middle" dominantBaseline="central"
        fontFamily="var(--font-num)" fontWeight="700" fontSize="21" fill="var(--ink)">{pct}%</text>
    </svg>
  );
}

const mdStyles = {
  head: { display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, flexWrap: "wrap", margin: "28px 0 22px" },
  kicker: { fontSize: 12.5, fontWeight: 700, color: "var(--primary)", letterSpacing: ".4px", textTransform: "uppercase" },
  h1: { fontSize: 26, fontWeight: 700, margin: "8px 0 8px", letterSpacing: "-.4px", lineHeight: 1.3, maxWidth: 620 },
  sub: { fontSize: 14, color: "var(--ink-3)" },
  summaryGrid: { display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 18 },
  statCard: { padding: "16px 18px" },
  twoCol: { display: "grid", gridTemplateColumns: "minmax(320px, 0.85fr) 1.15fr", gap: 18, alignItems: "start" },
  panelHead: { display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 18px", borderBottom: "1px solid var(--line-soft)" },
  alertIco: { width: 26, height: 26, borderRadius: 8, background: "var(--high-soft)", color: "var(--high)", display: "grid", placeItems: "center" },
  alertCount: { fontSize: 12.5, fontWeight: 700, color: "var(--high)", background: "var(--high-soft)", borderRadius: 20, padding: "3px 11px" },
  alertRow: { display: "flex", alignItems: "center", gap: 11, width: "100%", padding: "10px 10px", borderRadius: 12, border: 0, background: "transparent", transition: ".12s" },
  alertTitle: { fontWeight: 600, fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" },
  tableHeadRow: {
    display: "grid", gridTemplateColumns: "1.6fr .6fr .6fr .6fr .6fr 1.5fr", gap: 10, alignItems: "center",
    padding: "11px 18px", fontSize: 11.5, fontWeight: 700, color: "var(--ink-3)", textTransform: "uppercase",
    letterSpacing: ".3px", background: "var(--surface-soft)", borderBottom: "1px solid var(--line-soft)",
  },
  memberRow: {
    display: "grid", gridTemplateColumns: "1.6fr .6fr .6fr .6fr .6fr 1.5fr", gap: 10, alignItems: "center",
    width: "100%", padding: "13px 18px", border: 0, borderBottom: "1px solid var(--line-soft)",
    background: "transparent", transition: ".12s", cursor: "pointer",
  },
  overdueTag: { fontSize: 10.5, fontWeight: 700, color: "var(--high)", background: "var(--high-soft)", borderRadius: 6, padding: "1px 6px" },
};

Object.assign(window, { ManagerDashboard });
