// ============================================
// Detail drawers — StaffDetailDrawer, WorkDetailDrawer
// ============================================

// Compute which works a staff appears in (as P / director / team member)
function worksForStaff(staffId, works) {
  const out = [];
  works.forEach(w => {
    const roles = [];
    if (w.producer === staffId) roles.push("R001");      // プロデューサー
    if (w.director === staffId) roles.push("R005");      // 監督
    (w.team || []).forEach(t => { if (t.staffId === staffId) roles.push(t.roleId); });
    if (roles.length) out.push({ work: w, roles: Array.from(new Set(roles)) });
  });
  // sort by status: in_production, post_production, planning, completed
  const order = { in_production: 0, post_production: 1, planning: 2, on_hold: 3, completed: 4 };
  out.sort((a, b) => (order[a.work.status] ?? 9) - (order[b.work.status] ?? 9));
  return out;
}

// All team members (P + director + team) for a work
function teamForWork(work) {
  const seen = new Set();
  const out = [];
  const add = (staffId, roleId) => {
    const key = `${staffId}|${roleId}`;
    if (seen.has(key)) return;
    seen.add(key);
    out.push({ staffId, roleId });
  };
  if (work.producer) add(work.producer, "R001");
  if (work.director && work.director !== "—") add(work.director, "R005");
  (work.team || []).forEach(t => add(t.staffId, t.roleId));
  return out;
}

// ====== Drawer shell ======
function Drawer({ open, onClose, children, width = 480 }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose?.(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <>
      <div className="drawer-backdrop" onClick={onClose} />
      <div className="drawer" style={{ width }}>
        {children}
      </div>
    </>
  );
}

// ====== Section block for drawers ======
function DrawerSection({ title, action, children }) {
  return (
    <section style={{ padding: "16px 20px", borderTop: "1px solid var(--border)" }}>
      <div style={{ display: "flex", alignItems: "center", marginBottom: 10 }}>
        <h3 style={{ fontSize: 11, fontWeight: 600, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: "0.06em", margin: 0 }}>
          {title}
        </h3>
        <div style={{ flex: 1 }} />
        {action}
      </div>
      {children}
    </section>
  );
}

// ====== Key/value row ======
function KV({ label, children }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: 8, padding: "5px 0", fontSize: 12.5 }}>
      <div style={{ color: "var(--text-subtle)", fontSize: 11.5 }}>{label}</div>
      <div style={{ color: "var(--text)" }}>{children}</div>
    </div>
  );
}

// ============================================
// StaffDetailDrawer
// ============================================
function StaffDetailDrawer({ staffId, staff, works, log, depts, roles, onClose, onEdit, onJumpToWork, canEdit }) {
  const s = staff.find(x => x.id === staffId);
  if (!s) return null;

  const assignments = useMemo(() => worksForStaff(staffId, works), [staffId, works]);
  const relevantLog = useMemo(() =>
    log.filter(l => (l.entity === "staff" && l.entityId === staffId) || l.user === staffId).slice(0, 8)
  , [log, staffId]);

  const dept = DEPT_BY_ID[s.dept];
  const yearsAgo = (() => {
    const d = new Date(s.joined); if (isNaN(d)) return null;
    const ms = Date.now() - d.getTime();
    return (ms / (365.25 * 24 * 3600 * 1000)).toFixed(1);
  })();

  return (
    <Drawer open onClose={onClose} width={520}>
      {/* Header */}
      <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 8 }}>
        <span className="mono text-xs faint">{s.code}</span>
        <Badge tone={STAFF_STATUS[s.status].tone} dot>{STAFF_STATUS[s.status].label}</Badge>
        <div style={{ flex: 1 }} />
        {canEdit && <Button size="sm" icon="edit" onClick={onEdit}>編集</Button>}
        <IconButton icon="close" onClick={onClose} title="閉じる" />
      </div>

      {/* Body */}
      <div style={{ overflow: "auto", flex: 1 }}>
        {/* Identity */}
        <section style={{ padding: "20px 20px 12px", display: "flex", gap: 16, alignItems: "center" }}>
          <Avatar id={s.id} name={initialsFor(s)} size="xl" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <h2 style={{ fontSize: 18, fontWeight: 600, margin: 0, letterSpacing: "-0.01em" }}>
              {s.lastName} {s.firstName}
            </h2>
            <div style={{ fontSize: 12, color: "var(--text-subtle)" }}>
              {s.lastKana} {s.firstKana}
            </div>
            <div style={{ marginTop: 6, fontSize: 12, color: "var(--text-muted)" }}>
              <a href={`mailto:${s.email}`} style={{ color: "var(--accent)", textDecoration: "none" }}>{s.email}</a>
            </div>
          </div>
        </section>

        {/* Primary info */}
        <DrawerSection title="基本情報">
          <KV label="所属部署">
            {dept ? (
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                <Icon name="building" size={12} style={{ color: "var(--text-subtle)" }} />
                <strong>{dept.name}</strong>
                <span className="muted mono text-xs">({dept.code})</span>
              </span>
            ) : <span className="muted">—</span>}
          </KV>
          <KV label="入社日">
            <span className="mono">{s.joined}</span>
            {yearsAgo && <span className="faint text-xs" style={{ marginLeft: 6 }}>（在籍 {yearsAgo} 年）</span>}
          </KV>
          {s.note && (
            <KV label="備考">
              <span>{s.note}</span>
            </KV>
          )}
        </DrawerSection>

        {/* Roles */}
        <DrawerSection title={`職種・兼任 (${(s.roles || []).length})`}>
          {s.roles && s.roles.length > 0 ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {s.roles.map(rid => {
                const r = ROLE_BY_ID[rid];
                if (!r) return null;
                return (
                  <div key={rid} style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 8px", background: "var(--bg-subtle)", borderRadius: 4, fontSize: 12.5 }}>
                    <span className="mono text-xs faint" style={{ width: 48 }}>{r.code}</span>
                    <span style={{ flex: 1, fontWeight: 500 }}>{r.name}</span>
                    <span className="tag">{r.category}</span>
                    <span className="mono text-xs faint">L{r.level}</span>
                  </div>
                );
              })}
            </div>
          ) : <span className="muted text-sm">職種が設定されていません</span>}
        </DrawerSection>

        {/* Assignments */}
        <DrawerSection title={`担当作品 (${assignments.length})`}>
          {assignments.length === 0 ? (
            <div className="text-sm muted">担当中の作品はありません</div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {assignments.map(({ work, roles: roleIds }) => (
                <button
                  key={work.id}
                  onClick={() => onJumpToWork(work.id)}
                  style={{
                    display: "block", textAlign: "left", width: "100%",
                    padding: "10px 12px",
                    background: "var(--surface)",
                    border: "1px solid var(--border)",
                    borderRadius: 6,
                    cursor: "pointer",
                  }}
                  onMouseOver={e => e.currentTarget.style.borderColor = "var(--border-strong)"}
                  onMouseOut={e => e.currentTarget.style.borderColor = "var(--border)"}
                >
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                    <span className="mono text-xs faint">{work.code}</span>
                    <Badge tone={WORK_STATUS[work.status].tone} dot>{WORK_STATUS[work.status].label}</Badge>
                    <Tag>{work.type}</Tag>
                    <div style={{ flex: 1 }} />
                    <Icon name="chevron-right" size={12} style={{ color: "var(--text-faint)" }} />
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 2 }}>{work.title}</div>
                  <div className="text-xs muted">{CLIENT_BY_ID[work.clientId]?.name || "—"}</div>
                  <div style={{ marginTop: 6, display: "flex", flexWrap: "wrap", gap: 3 }}>
                    {roleIds.map(rid => <span key={rid} className="tag" style={{ background: "var(--accent-soft)", color: "var(--accent)", borderColor: "var(--accent-border)" }}>{ROLE_BY_ID[rid]?.name}</span>)}
                  </div>
                </button>
              ))}
            </div>
          )}
        </DrawerSection>

        {/* Activity */}
        <DrawerSection title="変更履歴">
          {relevantLog.length === 0 ? (
            <div className="text-sm muted">該当する履歴がありません</div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column" }}>
              {relevantLog.map(l => {
                const isSelf = l.entity === "staff" && l.entityId === staffId;
                return (
                  <div key={l.id} style={{ padding: "8px 0", borderBottom: "1px solid var(--border)", fontSize: 12 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 2 }}>
                      <Badge tone={l.action === "create" ? "success" : l.action === "delete" ? "danger" : "info"}>
                        {l.action === "create" ? "作成" : l.action === "delete" ? "削除" : "更新"}
                      </Badge>
                      <span className="muted">{isSelf ? "本人情報の変更" : `${ENTITY_LABEL[l.entity]} ${l.entityId} を操作`}</span>
                      <div style={{ flex: 1 }} />
                      <span className="mono faint text-xs">{l.ts.slice(5, 16)}</span>
                    </div>
                    {l.note && <div className="text-xs muted">{l.note}</div>}
                  </div>
                );
              })}
            </div>
          )}
        </DrawerSection>
      </div>
    </Drawer>
  );
}

// ============================================
// WorkDetailDrawer
// ============================================
function WorkDetailDrawer({ workId, works, staff, log, onClose, onEdit, onJumpToStaff, canEdit }) {
  const w = works.find(x => x.id === workId);
  if (!w) return null;

  const teamList = useMemo(() => teamForWork(w), [w]);
  // group team by role category
  const byCat = useMemo(() => {
    const map = {};
    teamList.forEach(t => {
      const r = ROLE_BY_ID[t.roleId];
      const cat = r?.category || "その他";
      (map[cat] = map[cat] || []).push(t);
    });
    return map;
  }, [teamList]);
  const relevantLog = useMemo(() =>
    log.filter(l => l.entity === "work" && l.entityId === workId).slice(0, 8)
  , [log, workId]);

  const days = (() => {
    if (!w.startDate || !w.endDate) return null;
    const s = new Date(w.startDate); const e = new Date(w.endDate);
    if (isNaN(s) || isNaN(e)) return null;
    return Math.round((e - s) / (24 * 3600 * 1000));
  })();

  const producer = STAFF_BY_ID[w.producer];
  const director = STAFF_BY_ID[w.director];

  return (
    <Drawer open onClose={onClose} width={560}>
      {/* Header */}
      <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 8 }}>
        <span className="mono text-xs faint">{w.code}</span>
        <Badge tone={WORK_STATUS[w.status].tone} dot>{WORK_STATUS[w.status].label}</Badge>
        <Tag>{w.type}</Tag>
        <div style={{ flex: 1 }} />
        {canEdit && <Button size="sm" icon="edit" onClick={onEdit}>編集</Button>}
        <IconButton icon="close" onClick={onClose} title="閉じる" />
      </div>

      <div style={{ overflow: "auto", flex: 1 }}>
        {/* Title + key visual */}
        <section style={{ padding: "20px 20px 12px" }}>
          <div style={{ display: "flex", gap: 16 }}>
            <div className="photo-stripes" style={{ width: 96, height: 72, borderRadius: 6, flexShrink: 0 }}>
              KV
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <h2 style={{ fontSize: 18, fontWeight: 600, margin: 0, letterSpacing: "-0.01em", lineHeight: 1.3 }}>
                {w.title}
              </h2>
              <div style={{ fontSize: 12, color: "var(--text-subtle)", marginTop: 2 }}>{w.titleEn}</div>
              <div style={{ fontSize: 12.5, marginTop: 8, color: "var(--text-muted)" }}>
                <Icon name="building" size={12} style={{ marginRight: 4, color: "var(--text-faint)" }} />
                {CLIENT_BY_ID[w.clientId]?.name || "—"}
                {CLIENT_BY_ID[w.clientId] && (
                  <span className="mono text-xs faint" style={{ marginLeft: 6 }}>({CLIENT_BY_ID[w.clientId].code})</span>
                )}
              </div>
            </div>
          </div>
          {w.tags && w.tags.length > 0 && (
            <div style={{ marginTop: 12, display: "flex", flexWrap: "wrap", gap: 4 }}>
              {w.tags.map(t => <Tag key={t}>{t}</Tag>)}
            </div>
          )}
        </section>

        {/* Quick stats */}
        <section style={{ padding: "0 20px 16px", display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
          <div style={{ background: "var(--bg-subtle)", padding: 10, borderRadius: 6 }}>
            <div className="text-xs faint">話数</div>
            <div style={{ fontSize: 18, fontWeight: 600, marginTop: 2 }}>{w.episodes}<span className="text-xs muted" style={{ fontWeight: 400, marginLeft: 2 }}>話</span></div>
          </div>
          <div style={{ background: "var(--bg-subtle)", padding: 10, borderRadius: 6 }}>
            <div className="text-xs faint">予算</div>
            <div style={{ fontSize: 18, fontWeight: 600, marginTop: 2 }}>¥{formatYen(w.budget)}</div>
          </div>
          <div style={{ background: "var(--bg-subtle)", padding: 10, borderRadius: 6 }}>
            <div className="text-xs faint">期間</div>
            <div style={{ fontSize: 18, fontWeight: 600, marginTop: 2 }}>{days || "—"}<span className="text-xs muted" style={{ fontWeight: 400, marginLeft: 2 }}>日</span></div>
          </div>
        </section>

        <DrawerSection title="スケジュール">
          <KV label="開始日"><span className="mono">{w.startDate || "—"}</span></KV>
          <KV label="終了日"><span className="mono">{w.endDate || "—"}</span></KV>
          <KV label="ステータス"><Badge tone={WORK_STATUS[w.status].tone} dot>{WORK_STATUS[w.status].label}</Badge></KV>
        </DrawerSection>

        {/* Team */}
        <DrawerSection
          title={`チーム (${teamList.length})`}
          action={canEdit && <Button size="sm" variant="ghost" icon="plus" onClick={onEdit}>追加</Button>}
        >
          {teamList.length === 0 ? (
            <div className="text-sm muted">チームメンバーが登録されていません</div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              {Object.entries(byCat).map(([cat, members]) => (
                <div key={cat}>
                  <div style={{ fontSize: 10.5, fontWeight: 500, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 6 }}>
                    {cat}
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                    {members.map((t, i) => {
                      const s = STAFF_BY_ID[t.staffId];
                      const r = ROLE_BY_ID[t.roleId];
                      if (!s) return null;
                      return (
                        <button
                          key={t.staffId + i}
                          onClick={() => onJumpToStaff(t.staffId)}
                          style={{
                            display: "flex", alignItems: "center", gap: 8,
                            padding: "6px 8px", borderRadius: 4,
                            background: "transparent", border: "none", textAlign: "left",
                            width: "100%", cursor: "pointer",
                          }}
                          onMouseOver={e => e.currentTarget.style.background = "var(--surface-active)"}
                          onMouseOut={e => e.currentTarget.style.background = "transparent"}
                        >
                          <Avatar id={s.id} name={initialsFor(s)} />
                          <span style={{ fontSize: 12.5, fontWeight: 500 }}>{s.lastName} {s.firstName}</span>
                          <span className="mono text-xs faint">{s.code}</span>
                          <div style={{ flex: 1 }} />
                          <span className="tag" style={{ background: "var(--accent-soft)", color: "var(--accent)", borderColor: "var(--accent-border)" }}>
                            {r?.name || t.roleId}
                          </span>
                        </button>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          )}
        </DrawerSection>

        {/* Activity */}
        <DrawerSection title="変更履歴">
          {relevantLog.length === 0 ? (
            <div className="text-sm muted">該当する履歴がありません</div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column" }}>
              {relevantLog.map(l => {
                const user = STAFF_BY_ID[l.user];
                return (
                  <div key={l.id} style={{ padding: "8px 0", borderBottom: "1px solid var(--border)", fontSize: 12 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 2 }}>
                      <Badge tone={l.action === "create" ? "success" : l.action === "delete" ? "danger" : "info"}>
                        {l.action === "create" ? "作成" : l.action === "delete" ? "削除" : "更新"}
                      </Badge>
                      <span className="muted">{l.field !== "—" ? `${l.field} を変更` : "情報の変更"}</span>
                      <div style={{ flex: 1 }} />
                      <span className="mono faint text-xs">{l.ts.slice(5, 16)}</span>
                    </div>
                    {l.before !== "—" && l.after !== "—" && (
                      <div className="text-xs muted" style={{ marginLeft: 0 }}>
                        <span className="mono">{l.before}</span> → <span className="mono" style={{ color: "var(--text)" }}>{l.after}</span>
                      </div>
                    )}
                    {l.note && <div className="text-xs faint">{user ? `${user.lastName} ${user.firstName}` : l.user} · {l.note}</div>}
                  </div>
                );
              })}
            </div>
          )}
        </DrawerSection>
      </div>
    </Drawer>
  );
}

Object.assign(window, {
  StaffDetailDrawer, WorkDetailDrawer,
  worksForStaff, teamForWork,
});
