/* ============================================================
   Media SOP — KPI Dashboard & Leaderboard (Bước 7) — focus screen
   ============================================================ */

const MONTHS = ["T12","T1","T2","T3","T4","T5"];

function Dashboard() {
  const app = window.useApp();
  const eds = app.editors;
  const ranked = [...eds].sort((a, b) => kpiScore(b) - kpiScore(a));

  // team aggregates
  const totalActual = eds.reduce((s, e) => s + e.actualHours, 0);
  const totalProducts = eds.reduce((s, e) => s + e.products, 0);
  const totalHi = eds.reduce((s, e) => s + e.hiStar, 0);
  const totalOnTime = eds.reduce((s, e) => s + e.onTime, 0);
  const teamPerf = totalActual / eds.reduce((s, e) => s + normOf(e), 0);
  const teamQuality = totalProducts ? totalHi / totalProducts : 0;
  const teamDeadline = totalProducts ? totalOnTime / totalProducts : 0;
  const teamBand = perfBand(teamPerf);
  const teamTrend = MONTHS.map((_, i) => Math.round(eds.reduce((s, e) => s + e.trend[i], 0) / eds.length));

  return (
    <div className="content-narrow">
      {/* hero band */}
      <div className="card rise" style={{ background: "linear-gradient(115deg, oklch(0.30 0.10 290), oklch(0.42 0.20 290) 55%, oklch(0.50 0.18 320))", color: "white", padding: "26px 28px", marginBottom: 22, border: "none", overflow: "hidden", position: "relative" }}>
        <div style={{ position: "absolute", right: -40, top: -40, width: 220, height: 220, borderRadius: "50%", background: "oklch(1 0 0 / 0.06)" }} />
        <div style={{ position: "absolute", right: 60, bottom: -60, width: 160, height: 160, borderRadius: "50%", background: "oklch(1 0 0 / 0.05)" }} />
        <div className="row between wrap" style={{ position: "relative", gap: 24 }}>
          <div>
            <div className="row" style={{ gap: 8, opacity: 0.85, fontSize: 13, fontWeight: 600 }}><Icon name="sparkles" size={15} /> KPI Tổng — Kỳ tháng 5/2026</div>
            <div className="row" style={{ gap: 16, marginTop: 12, alignItems: "baseline" }}>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 54, lineHeight: 1, letterSpacing: "-0.03em" }}>{pct(teamPerf)}%</div>
              <span className={"band " + teamBand.cls} style={{ fontSize: 13, padding: "5px 13px" }}>{teamBand.label}</span>
            </div>
            <div style={{ opacity: 0.8, fontSize: 13, marginTop: 8 }}>Hiệu suất trung bình team · định mức theo từng nhân sự</div>
          </div>
          <div className="row" style={{ gap: 26 }}>
            <HeroMetric icon="star" label="Chất lượng" value={pct(teamQuality) + "%"} sub={`${totalHi}/${totalProducts} SP ≥ 4★`} />
            <HeroMetric icon="clock" label="Deadline" value={pct(teamDeadline) + "%"} sub={`${totalOnTime}/${totalProducts} đúng hạn`} />
            <HeroMetric icon="film" label="Thành phẩm" value={totalProducts} sub={`${totalActual}h thực hiện`} />
          </div>
        </div>
      </div>

      {/* KPI formula explainer */}
      <div className="grid g-4" style={{ marginBottom: 22 }}>
        <FormulaCard color="var(--violet-500)" icon="zap" title="Hiệu suất" formula="Giờ thực tế ÷ định mức" value={pct(teamPerf) + "%"} />
        <FormulaCard color="var(--amber)" icon="star" title="Điểm chất lượng" formula="% SP ≥ 4 sao" value={pct(teamQuality) + "%"} />
        <FormulaCard color="var(--cyan)" icon="target" title="Điểm Deadline" formula="% SP đúng hạn" value={pct(teamDeadline) + "%"} />
        <FormulaCard color="var(--green)" icon="trophy" title="KPI tổng hợp" formula="HS × CL × Deadline" value={pct(teamPerf * teamQuality * teamDeadline)} mult />
      </div>

      <div className="grid g-main" style={{ marginBottom: 22 }}>
        {/* Leaderboard */}
        <div className="card card-pad">
          <div className="card-h">
            <div className="brand-mark" style={{ width: 36, height: 36, borderRadius: 10, background: "linear-gradient(135deg,var(--amber),var(--pink))" }}><Icon name="trophy" size={18} /></div>
            <div style={{ flex: 1 }}><h3>Leaderboard Editor</h3><div className="sub">Xếp hạng theo KPI tổng hợp kỳ này</div></div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {ranked.map((e, i) => <LeaderRow key={e.id} ed={e} rank={i + 1} onClick={() => app.openEditor(e.id)} />)}
          </div>
        </div>

        {/* Trend chart */}
        <div className="card card-pad">
          <div className="card-h">
            <div className="brand-mark" style={{ width: 36, height: 36, borderRadius: 10, background: "linear-gradient(135deg,var(--cyan),var(--violet-500))" }}><Icon name="trendUp" size={18} /></div>
            <div><h3>Hiệu suất team</h3><div className="sub">6 tháng gần nhất</div></div>
          </div>
          <BarChart data={teamTrend} height={130} baseline={100} />
          <div className="row between" style={{ marginTop: 8, padding: "0 6px" }}>
            {MONTHS.map(m => <span key={m} className="muted" style={{ fontSize: 11, fontWeight: 600 }}>{m}</span>)}
          </div>
          <div className="divider" />
          <div className="row between" style={{ fontSize: 12.5 }}><span className="muted">Đường định mức (100%)</span><span className="row" style={{ gap: 6 }}><span style={{ width: 18, height: 0, borderTop: "2px dashed var(--line-2)" }} /></span></div>
          {(() => {
            const delta = Math.round((pct(teamPerf) - 100) * 10) / 10;
            const above = delta >= 0;
            const c = above ? "152" : "55";
            return (
              <div className="card" style={{ background: above ? "var(--green-bg)" : "var(--amber-bg)", padding: 12, borderRadius: 11, marginTop: 12 }}>
                <div className="row" style={{ gap: 8 }}><Icon name={above ? "trendUp" : "alert"} size={15} color={`oklch(0.42 0.12 ${c})`} /><span style={{ fontSize: 12.5, fontWeight: 600, color: `oklch(0.40 0.12 ${c})` }}>
                  {above
                    ? `Team vượt định mức tháng này — +${delta}% so với chuẩn.`
                    : `Team dưới định mức tháng này — ${delta}% so với chuẩn (đạt ${pct(teamPerf)}%).`}
                </span></div>
              </div>
            );
          })()}
        </div>
      </div>

      {/* Detailed KPI table */}
      <div className="card">
        <div className="card-h card-pad" style={{ paddingBottom: 0, marginBottom: 0 }}>
          <div className="brand-mark" style={{ width: 34, height: 34, borderRadius: 9 }}><Icon name="dashboard" size={17} /></div>
          <div><h3>Bảng KPI chi tiết</h3><div className="sub">Theo dõi hiệu suất từng editor · cơ chế phân hạng</div></div>
        </div>
        <div style={{ overflowX: "auto", padding: "8px 8px 4px" }}>
          <table className="tbl" style={{ minWidth: 760 }}>
            <thead><tr><th>Editor</th><th>Level</th><th style={{ textAlign: "center" }}>Giờ TT / Định mức</th><th style={{ textAlign: "center" }}>Hiệu suất</th><th style={{ textAlign: "center" }}>Chất lượng</th><th style={{ textAlign: "center" }}>Deadline</th><th style={{ textAlign: "center" }}>KPI</th><th>Phân hạng</th></tr></thead>
            <tbody>
              {ranked.map(e => {
                const p = performance(e), band = perfBand(p);
                return (
                  <tr key={e.id} style={{ cursor: "pointer" }} onClick={() => app.openEditor(e.id)}>
                    <td><div className="row" style={{ gap: 9 }}><Avatar name={e.name} color={e.color} size={30} /><div><b style={{ fontSize: 13 }}>{e.name}</b><div className="muted" style={{ fontSize: 11 }}>{e.jobTitle || "Editor"}</div></div></div></td>
                    <td><Badge cls="badge-violet">{e.level}</Badge></td>
                    <td style={{ textAlign: "center" }} className="mono">{e.actualHours} / {normOf(e)}{normOf(e) !== NORM_HOURS && <span style={{ color: "var(--violet-500)", fontWeight: 700 }}> *</span>}</td>
                    <td style={{ textAlign: "center" }}><b className="mono" style={{ fontSize: 13.5 }}>{pct(p)}%</b></td>
                    <td style={{ textAlign: "center" }} className="mono">{pct(qualityScore(e))}%</td>
                    <td style={{ textAlign: "center" }} className="mono">{pct(deadlineScore(e))}%</td>
                    <td style={{ textAlign: "center" }}><b className="mono" style={{ color: "var(--violet-600)" }}>{pct(kpiScore(e))}</b></td>
                    <td><span className={"band " + band.cls}>{band.label}</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <div className="row wrap card-pad" style={{ gap: 8, paddingTop: 14, borderTop: "1px solid var(--line)" }}>
          <span className="muted" style={{ fontSize: 12, fontWeight: 600 }}>Cơ chế:</span>
          <span className="band band-fail">&lt;95% Không đạt</span>
          <span className="band band-ok">95–105% Đạt</span>
          <span className="band band-bonus">105–120% Thưởng</span>
          <span className="band band-over">&gt;120% Thưởng &amp; Check quá tải</span>
          <span className="muted" style={{ fontSize: 11.5, marginLeft: 4 }}><b style={{ color: "var(--violet-500)" }}>*</b> định mức tùy chỉnh (khác {NORM_HOURS}h)</span>
        </div>
      </div>
    </div>
  );
}

function HeroMetric({ icon, label, value, sub }) {
  return (
    <div>
      <div className="row" style={{ gap: 6, opacity: 0.8, fontSize: 12, fontWeight: 600 }}><Icon name={icon} size={13} />{label}</div>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 26, marginTop: 4 }}>{value}</div>
      <div style={{ opacity: 0.7, fontSize: 11.5, marginTop: 2 }}>{sub}</div>
    </div>
  );
}

function FormulaCard({ color, icon, title, formula, value, mult }) {
  return (
    <div className="stat rise">
      <div className="row between">
        <div className="row" style={{ gap: 8 }}><div style={{ width: 30, height: 30, borderRadius: 9, background: color, opacity: 0.14, position: "relative" }} /><Icon name={icon} size={17} color={color} style={{ marginLeft: -29, marginTop: 6 }} />
        </div>
      </div>
      <div className="stat-label" style={{ marginTop: 10 }}>{title}</div>
      <div className="stat-val" style={{ fontSize: 26, color }}>{value}{mult && <span style={{ fontSize: 14, color: "var(--ink-4)" }}> đ</span>}</div>
      <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 6 }}>{formula}</div>
    </div>
  );
}

function LeaderRow({ ed, rank, onClick }) {
  const p = performance(ed), band = perfBand(p);
  const medals = { 1: "var(--amber)", 2: "var(--ink-4)", 3: "oklch(0.62 0.12 50)" };
  return (
    <div className="card" onClick={onClick} style={{ padding: "12px 14px", borderRadius: 14, cursor: "pointer", display: "flex", alignItems: "center", gap: 13, border: rank === 1 ? "1.5px solid var(--amber)" : "1px solid var(--line)", background: rank === 1 ? "var(--amber-bg)" : "var(--surface)" }}>
      <div style={{ width: 30, height: 30, borderRadius: 9, display: "grid", placeItems: "center", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15, background: medals[rank] ? medals[rank] : "var(--surface-2)", color: medals[rank] ? "white" : "var(--ink-3)", flex: "0 0 auto" }}>{rank}</div>
      <Avatar name={ed.name} color={ed.color} size={40} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="row" style={{ gap: 8 }}><b style={{ fontSize: 14 }}>{ed.name}</b>{rank === 1 && <Icon name="trophy" size={14} color="var(--amber)" />}</div>
        <div className="muted" style={{ fontSize: 12 }}>{ed.level} · {ed.products} SP · {ed.activeTasks} đang chạy</div>
      </div>
      <div style={{ textAlign: "right" }}>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, color: "var(--violet-600)" }}>{pct(kpiScore(ed))}</div>
        <span className={"band " + band.cls} style={{ fontSize: 10 }}>{pct(p)}%</span>
      </div>
    </div>
  );
}

// ------- Editor detail drawer/modal -------
function EditorDetail({ ed, onClose }) {
  const app = window.useApp();
  const p = performance(ed), band = perfBand(p);
  const done = app.orders.filter(o => o.editorId === ed.id && o.stage === "done");
  return (
    <Modal title={ed.name} sub={`${ed.level} · KPI ${pct(kpiScore(ed))}`} icon="users" onClose={onClose} wide>
      <div className="grid g-3" style={{ marginBottom: 20 }}>
        <div className="stat" style={{ textAlign: "center", padding: 16 }}>
          <Ring value={Math.min(1, p)} size={76} color="var(--violet-500)" label={pct(p) + "%"} />
          <div className="stat-label" style={{ marginTop: 8 }}>Hiệu suất</div>
          <span className={"band " + band.cls} style={{ marginTop: 4, display: "inline-block" }}>{band.label}</span>
        </div>
        <div className="stat" style={{ textAlign: "center", padding: 16 }}>
          <Ring value={qualityScore(ed)} size={76} color="var(--amber)" label={pct(qualityScore(ed)) + "%"} track="var(--amber-bg)" />
          <div className="stat-label" style={{ marginTop: 8 }}>Chất lượng</div>
          <div className="muted" style={{ fontSize: 12 }}>{ed.hiStar}/{ed.products} SP ≥ 4★</div>
        </div>
        <div className="stat" style={{ textAlign: "center", padding: 16 }}>
          <Ring value={deadlineScore(ed)} size={76} color="var(--cyan)" label={pct(deadlineScore(ed)) + "%"} track="var(--cyan-bg)" />
          <div className="stat-label" style={{ marginTop: 8 }}>Deadline</div>
          <div className="muted" style={{ fontSize: 12 }}>{ed.onTime}/{ed.products} đúng hạn</div>
        </div>
      </div>
      <div className="field"><label>Hiệu suất 6 tháng</label><BarChart data={ed.trend} height={90} baseline={100} color={ed.color.includes("290") ? "var(--violet-500)" : "var(--cyan)"} /></div>
      <div className="field" style={{ marginBottom: 0 }}>
        <label>Sản phẩm đã hoàn tất ({done.length})</label>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {done.map(o => (
            <div key={o.id} className="row between card" style={{ padding: "10px 12px", borderRadius: 11 }}>
              <span className="row" style={{ gap: 8 }}><VChip vtype={o.vtype} /><span style={{ fontSize: 13, fontWeight: 600 }}>{o.title}</span></span>
              <span className="row" style={{ gap: 10 }}>{o.rating && <Stars value={o.rating} size={13} />}<Badge cls={o.deadlineMet ? "badge-green" : "badge-red"}>{o.deadlineMet ? "Đúng hạn" : "Trễ"}</Badge></span>
            </div>
          ))}
          {done.length === 0 && <div className="hint">Chưa có sản phẩm hoàn tất trong kỳ.</div>}
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { Dashboard, EditorDetail });
