/* ============================================================
   Media SOP — Quản lý/Lead: Tiếp nhận & Estimate, Nhân sự
   ============================================================ */
const { useState, useEffect } = React;

// estimate = giờ định mức gốc + Σ (giờ định mức gốc × % của từng add-on)
function estimateHours(vtype, level, addons = [], addonPcts = {}) {
  const base = RATE[vtype]?.[level];
  if (base == null) return null;
  let total = base;
  addons.forEach(k => { total += base * addonPct(k, vtype, addonPcts[k]); });
  return Math.round(total * 100) / 100;
}
function eligibleLevels(vtype) {
  if (!RATE[vtype]) return LEVELS; // QUAY / LIVE — all
  return LEVELS.filter(l => RATE[vtype][l] != null);
}

// ---------------- Intake & Estimate ----------------
function IntakeQueue() {
  const app = window.useApp();
  const [pick, setPick] = useState(null);
  const queue = app.orders.filter(o => o.stage === "intake");

  return (
    <div className="content-narrow">
      <div className="grid g-4" style={{ marginBottom: 24 }}>
        <Stat label="Chờ tiếp nhận" value={queue.length} icon="inbox" color="var(--violet-500)" />
        <Stat label="Ưu tiên cao / gấp" value={queue.filter(o => ["high","urgent"].includes(o.priority)).length} icon="flame" color="var(--pink)" />
        <Stat label="Editor sẵn sàng" value={app.editors.length} icon="users" color="var(--cyan)" />
        <Stat label="Deadline ≤ 2 ngày" value={queue.filter(o => daysLeft(o.deadline) <= 2).length} icon="clock" color="var(--amber)" />
      </div>

      <div className="card">
        <div className="card-h card-pad" style={{ paddingBottom: 0, marginBottom: 0 }}>
          <div className="brand-mark" style={{ width: 36, height: 36, borderRadius: 10 }}><Icon name="briefcase" size={18} /></div>
          <div><h3>Hàng chờ tiếp nhận</h3><div className="sub">Bước 2 · Gán editor &amp; estimate số giờ theo level</div></div>
        </div>
        {queue.length === 0 ? (
          <Empty icon="checkCircle" title="Đã xử lý hết!" desc="Không còn order nào chờ tiếp nhận." />
        ) : (
          <div style={{ overflowX: "auto", padding: "8px 8px 4px" }}>
            <table className="tbl">
              <thead><tr><th>Ấn phẩm</th><th>Loại</th><th>Người order</th><th>Deadline</th><th>Ưu tiên</th><th></th></tr></thead>
              <tbody>
                {queue.map(o => (
                  <tr key={o.id}>
                    <td>
                      <div style={{ fontWeight: 700 }}>{o.title}</div>
                      <div className="mono muted" style={{ fontSize: 11 }}>{o.id} · {o.dept}</div>
                    </td>
                    <td><VChip vtype={o.vtype} />{o.addons.length > 0 && <span className="badge badge-violet" style={{ marginLeft: 6 }}>+{o.addons.length}</span>}</td>
                    <td style={{ fontSize: 13 }}>{o.requester}</td>
                    <td><DeadlinePill deadline={o.deadline} /></td>
                    <td><PriorityBadge p={o.priority} /></td>
                    <td style={{ textAlign: "right" }}><Btn sm icon="arrowRight" onClick={() => setPick(o)}>Tiếp nhận</Btn></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
      {pick && <EstimateModal order={pick} onClose={() => setPick(null)} />}
    </div>
  );
}

function EstimateModal({ order, onClose }) {
  const app = window.useApp();
  const elig = eligibleLevels(order.vtype);
  const eligEditors = app.editors.filter(e => elig.includes(e.level));
  const [editorId, setEditorId] = useState(eligEditors[0]?.id || "");
  const ed = app.editorById(editorId);
  const isManual = !RATE[order.vtype]; // QUAY / LIVE
  // per add-on % overrides (initialized from defaults; Subtitle editable theo dự án)
  const [pcts, setPcts] = useState(() => {
    const o = {};
    order.addons.forEach(k => { o[k] = addonPct(k, order.vtype); });
    return o;
  });
  const base = !isManual && ed ? RATE[order.vtype][ed.level] : null;
  const auto = ed ? estimateHours(order.vtype, ed.level, order.addons, pcts) : null;
  const [hours, setHours] = useState("");
  useEffect(() => { if (!isManual && auto != null) setHours(String(auto)); }, [editorId, JSON.stringify(pcts)]);

  const setPct = (k, v) => setPcts(s => ({ ...s, [k]: Math.max(0, (parseFloat(v) || 0) / 100) }));
  const confirm = () => { app.intakeOrder(order.id, editorId, parseFloat(hours) || 0, pcts); onClose(); };

  return (
    <Modal title="Tiếp nhận & Estimate" sub={`Bước 2 · ${order.id}`} icon="briefcase" onClose={onClose} wide
      footer={<><Btn variant="ghost" onClick={onClose}>Huỷ</Btn><Btn icon="check" disabled={!editorId || !hours} onClick={confirm}>Tiếp nhận &amp; thông báo</Btn></>}>
      <div className="grid g-2" style={{ gap: 20 }}>
        <div>
          <div className="card" style={{ background: "var(--surface-2)", padding: 15, borderRadius: 13, marginBottom: 18 }}>
            <div className="row" style={{ gap: 8, marginBottom: 8 }}><VChip vtype={order.vtype} /><b style={{ fontSize: 14.5 }}>{order.title}</b></div>
            <div className="muted" style={{ fontSize: 12.5, lineHeight: 1.45 }}>{order.purpose}</div>
            <div className="row wrap" style={{ gap: 8, marginTop: 11 }}>
              <DeadlinePill deadline={order.deadline} /><PriorityBadge p={order.priority} />
              {order.addons.map(a => <Badge key={a} cls="badge-violet">{ADDONS[a].label}</Badge>)}
            </div>
          </div>

          <div className="field" style={{ marginBottom: 0 }}>
            <label>Gán editor phụ trách</label>
            <div className="opt-grid">
              {eligEditors.map(e => (
                <div key={e.id} className={"opt" + (editorId === e.id ? " sel" : "")} onClick={() => setEditorId(e.id)} style={{ padding: 11 }}>
                  <Avatar name={e.name} color={e.color} size={34} />
                  <div style={{ flex: 1 }}>
                    <div className="opt-title">{e.name}</div>
                    <div className="opt-desc">{e.level} · {e.activeTasks} task đang chạy</div>
                  </div>
                  {!isManual && <span className="badge badge-gray mono">{estimateHours(order.vtype, e.level, order.addons, pcts)}h</span>}
                </div>
              ))}
              {eligEditors.length === 0 && <div className="hint">Không có editor đủ level cho loại {order.vtype}. Thêm/nâng cấp nhân sự ở mục Nhân sự.</div>}
            </div>
          </div>
        </div>

        <div>
          <div className="field">
            <label>Số giờ định mức (estimate)</label>
            <div className="row" style={{ gap: 10 }}>
              <input className="input" type="number" step="0.1" value={hours} onChange={e => setHours(e.target.value)} style={{ fontSize: 22, fontFamily: "var(--font-display)", fontWeight: 700, textAlign: "center" }} />
              <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, color: "var(--ink-3)" }}>giờ</span>
            </div>
            {!isManual ? (
              <div className="hint">Tự tính: <b>giờ định mức gốc</b> ({VIDEO_TYPES[order.vtype].name} × {ed?.level}) + % add-on. Có thể chỉnh tay.</div>
            ) : (
              <div className="hint">{order.vtype === "QUAY"
                ? "Quay: dựa theo thời gian order — nhân sự nhập giờ thực tế sau (đảm bảo ≤ +20%)."
                : "Livestream: Cơ bản 1 góc = setup 1h; Trung bình 2–3 góc = setup 2h; cộng thời gian vận hành thực tế."}</div>
            )}
          </div>

          {!isManual && (
            <div className="card" style={{ background: "var(--violet-50)", border: "1px solid var(--violet-100)", padding: 14, borderRadius: 13 }}>
              <div className="row between" style={{ fontSize: 12.5 }}><span className="muted">Giờ định mức gốc ({ed?.level})</span><b className="mono">{base}h</b></div>
              {order.addons.map(k => {
                const a = ADDONS[k], p = addonPct(k, order.vtype, pcts[k]);
                const add = Math.round(base * p * 100) / 100;
                return (
                  <div key={k} style={{ marginTop: 9, paddingTop: 9, borderTop: "1px dashed var(--violet-100)" }}>
                    <div className="row between" style={{ fontSize: 12.5 }}>
                      <span className="muted">{a.label}</span>
                      <span className="row" style={{ gap: 8 }}>
                        {a.editable ? (
                          <span className="row" style={{ gap: 4 }}>
                            <input className="input mono" type="number" step="1" min="0"
                              value={Math.round(p * 100)} onChange={e => setPct(k, e.target.value)}
                              style={{ width: 58, padding: "4px 7px", textAlign: "center", fontWeight: 700, fontSize: 12.5 }} />
                            <span className="mono" style={{ color: "var(--ink-3)" }}>%</span>
                          </span>
                        ) : <b className="mono">+{Math.round(p * 100)}%</b>}
                        <b className="mono" style={{ color: "var(--violet-600)", minWidth: 46, textAlign: "right" }}>+{add}h</b>
                      </span>
                    </div>
                    <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-4)", marginTop: 3 }}>{base} × {Math.round(p*100)}% = {add}h</div>
                  </div>
                );
              })}
              <div className="divider" style={{ margin: "10px 0" }} />
              <div className="row between"><span style={{ fontWeight: 700, fontSize: 13 }}>Tổng estimate</span><b className="mono" style={{ color: "var(--violet-600)", fontSize: 15 }}>{auto}h</b></div>
            </div>
          )}

          <div className="card" style={{ background: "var(--cyan-bg)", padding: 13, borderRadius: 13, marginTop: 14 }}>
            <div className="row" style={{ gap: 8 }}><Icon name="send" size={15} color="oklch(0.42 0.10 220)" /><span style={{ fontSize: 12.5, fontWeight: 600, color: "oklch(0.40 0.10 220)" }}>Sẽ gửi Telegram tới {order.requester}: “Đã tiếp nhận – dự kiến hoàn thành: {fmtDate(order.deadline)}”</span></div>
          </div>
        </div>
      </div>
    </Modal>
  );
}

// ---------------- Staff / Editor management ----------------
function StaffManagement() {
  const app = window.useApp();
  const [adding, setAdding] = useState(false);

  return (
    <div className="content-narrow">
      <div className="row between" style={{ marginBottom: 18 }}>
        <div>
          <h3 style={{ fontSize: 16 }}>Nhân sự Media</h3>
          <div className="sub muted" style={{ fontSize: 13 }}>Cập nhật level theo quý/tháng · thêm nhân sự mới</div>
        </div>
        <Btn icon="plus" onClick={() => setAdding(true)}>Thêm editor</Btn>
      </div>

      <div className="grid g-3">
        {app.editors.map(e => {
          const p = performance(e), band = perfBand(p);
          return (
            <div key={e.id} className="card card-pad rise" style={{ padding: 18 }}>
              <div className="row" style={{ gap: 12, marginBottom: 14 }}>
                <Avatar name={e.name} color={e.color} size={48} fontSize={17} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 15 }}>{e.name}</div>
                  <div className="muted" style={{ fontSize: 12.5 }}>{e.jobTitle || "Editor"} · {e.activeTasks} task</div>
                </div>
              </div>
              <div className="field" style={{ marginBottom: 10 }}>
                <label style={{ fontSize: 12 }}>Vai trò chuyên môn</label>
                <select className="select" value={e.jobTitle || "Editor"} onChange={ev => app.updateEditor(e.id, { jobTitle: ev.target.value })}>
                  {JOB_TITLES.map(j => <option key={j} value={j}>{j}</option>)}
                </select>
              </div>
              <div className="grid g-2" style={{ gap: 10, marginBottom: 12 }}>
                <div className="field" style={{ marginBottom: 0 }}>
                  <label style={{ fontSize: 12 }}>Level (hệ số phí)</label>
                  <select className="select" value={e.level} onChange={ev => app.updateEditor(e.id, { level: ev.target.value })}>
                    {LEVELS.map(l => <option key={l} value={l}>{l}</option>)}
                  </select>
                </div>
                <div className="field" style={{ marginBottom: 0 }}>
                  <label style={{ fontSize: 12 }}>Định mức (giờ/kỳ)</label>
                  <input className="input mono" type="number" step="1" min="0" value={normOf(e)}
                    onChange={ev => app.updateEditor(e.id, { normHours: Math.max(0, parseInt(ev.target.value) || 0) })}
                    style={{ textAlign: "center", fontWeight: 700 }} />
                </div>
              </div>
              {normOf(e) !== NORM_HOURS && (
                <div className="row" style={{ gap: 6, fontSize: 11, color: "var(--violet-600)", fontWeight: 600, marginBottom: 8 }}>
                  <Icon name="briefcase" size={12} />Định mức tùy chỉnh ({normOf(e) > NORM_HOURS ? "+" : "−"}{Math.abs(normOf(e) - NORM_HOURS)}h so với chuẩn)
                </div>
              )}
              <div className="row between" style={{ padding: "10px 0", borderTop: "1px solid var(--line)" }}>
                <span className="muted" style={{ fontSize: 12.5 }}>Hiệu suất ({e.actualHours}/{normOf(e)}h)</span>
                <span className="row" style={{ gap: 8 }}><b className="mono" style={{ fontSize: 14 }}>{pct(p)}%</b><span className={"band " + band.cls}>{band.label}</span></span>
              </div>
              <div className="row" style={{ gap: 6, fontSize: 11.5 }}>
                <span className="badge badge-gray">{e.products} SP</span>
                <span className="badge badge-amber"><Icon name="star" size={11} />{pct(qualityScore(e))}%</span>
                <span className="badge badge-cyan"><Icon name="clock" size={11} />{pct(deadlineScore(e))}%</span>
              </div>
            </div>
          );
        })}
      </div>

      <div className="card card-pad" style={{ marginTop: 22 }}>
        <div className="card-h"><div className="brand-mark" style={{ width: 34, height: 34, borderRadius: 9 }}><Icon name="layers" size={17} /></div><div><h3>Bảng phí định mức (giờ / sản phẩm)</h3><div className="sub">Dùng để tự tính estimate khi tiếp nhận order</div></div></div>
        <RateTable />
      </div>
      {adding && <AddEditorModal onClose={() => setAdding(false)} />}
    </div>
  );
}

function RateTable() {
  return (
    <div style={{ overflowX: "auto" }}>
      <table className="tbl" style={{ minWidth: 900 }}>
        <thead><tr><th>Loại</th>{LEVELS.map(l => <th key={l} style={{ textAlign: "center" }}>{l.replace("Member ", "")}</th>)}</tr></thead>
        <tbody>
          {["V1","V2","V3","V4"].map(v => (
            <tr key={v}>
              <td><span className="row" style={{ gap: 7 }}><VChip vtype={v} /><span style={{ fontSize: 12 }}>{VIDEO_TYPES[v].name}</span></span></td>
              {LEVELS.map(l => <td key={l} style={{ textAlign: "center", color: RATE[v][l] == null ? "var(--ink-4)" : "var(--ink)", fontWeight: RATE[v][l] != null ? 700 : 400 }} className="mono">{RATE[v][l] == null ? "–" : RATE[v][l]}</td>)}
            </tr>
          ))}
        </tbody>
      </table>
      <div className="hint" style={{ marginTop: 10 }}>Công thức add-on: <b>giờ định mức gốc × %</b> — Resize +30% (V1, V2) · +60% (V3, V4); Subtitle Full nhập % theo dự án. Quay/Livestream tính theo giờ thực tế (≤ +20%).</div>
    </div>
  );
}

function AddEditorModal({ onClose }) {
  const app = window.useApp();
  const [name, setName] = useState("");
  const [level, setLevel] = useState("Junior");
  const [jobTitle, setJobTitle] = useState("Editor");
  const [normHours, setNormHours] = useState(155);
  const add = () => { app.addEditor(name.trim(), level, jobTitle, normHours); onClose(); };
  return (
    <Modal title="Thêm nhân sự Media" icon="users" onClose={onClose}
      footer={<><Btn variant="ghost" onClick={onClose}>Huỷ</Btn><Btn icon="plus" disabled={!name.trim()} onClick={add}>Thêm editor</Btn></>}>
      <div className="field"><label>Họ và tên</label><input className="input" placeholder="VD: Nguyễn Văn A" value={name} onChange={e => setName(e.target.value)} autoFocus /></div>
      <div className="grid g-2" style={{ gap: 16 }}>
        <div className="field"><label>Level khởi điểm</label>
          <select className="select" value={level} onChange={e => setLevel(e.target.value)}>{LEVELS.map(l => <option key={l} value={l}>{l}</option>)}</select>
        </div>
        <div className="field"><label>Vai trò chuyên môn</label>
          <select className="select" value={jobTitle} onChange={e => setJobTitle(e.target.value)}>{JOB_TITLES.map(j => <option key={j} value={j}>{j}</option>)}</select>
        </div>
      </div>
      <div className="field" style={{ marginBottom: 0 }}><label>Thời gian định mức (giờ/kỳ)</label>
        <input className="input mono" type="number" step="1" min="0" value={normHours} onChange={e => setNormHours(Math.max(0, parseInt(e.target.value) || 0))} style={{ fontWeight: 700 }} />
        <div className="hint">Mặc định {NORM_HOURS}h. Giảm định mức cho nhân sự kiêm nhiệm quản lý để hiệu suất được tính công bằng theo thời gian chuyên môn thực tế.</div>
      </div>
    </Modal>
  );
}

// small stat helper reused
function Stat({ label, value, sub, icon, color = "var(--violet-500)", foot }) {
  return (
    <div className="stat rise">
      <div className="stat-ic"><Icon name={icon} size={22} color={color} /></div>
      <div className="stat-label">{label}</div>
      <div className="stat-val" style={{ color }}>{value}</div>
      {foot && <div className="stat-foot">{foot}</div>}
      {sub && <div className="stat-foot muted">{sub}</div>}
    </div>
  );
}

Object.assign(window, { IntakeQueue, StaffManagement, Stat, estimateHours, eligibleLevels });
