// ──────────────────────────────────────────────────────────────────
// staff.jsx — 직원 관리 페이지 (P-01, v3.10)
// ──────────────────────────────────────────────────────────────────
// 담당: 풀스택 + 운영 디렉터
// 권한: owner 전용 (다른 역할은 자동 차단)
// 기능:
//   - 직원 카드 리스트 (이름/이메일/역할/마지막 로그인)
//   - 역할 변경 (owner/mechanic/manager)
//   - 비밀번호 임시 리셋
//   - 모든 세션 종료
//   - 계정 비활성/활성
//   - 새 직원 가입 URL 공유
// ──────────────────────────────────────────────────────────────────

const { useState, useEffect } = React;

const ROLE_LABEL = {
  owner:    { ko: "매장 대표", emoji: "👑", color: "var(--red-500,#E31E26)",   bg: "var(--red-50,#FFE5E6)" },
  mechanic: { ko: "정비 매니저", emoji: "🔧", color: "#DD7D02",                 bg: "#FFF9E7" },
  manager:  { ko: "운영 매니저", emoji: "📦", color: "#1B64DA",                 bg: "#E8F3FF" },
};

const MOCK_STAFF = [
  { id: "u-001", name: "김성호", email: "kimsungho@sejong.kr", role: "owner",    last_seen: "방금",      created_at: "2026-05-20", is_active: true },
  { id: "u-002", name: "한지영", email: "hanjy@sejong.kr",     role: "mechanic", last_seen: "1시간 전",  created_at: "2026-05-21", is_active: true },
  { id: "u-003", name: "박미경", email: "parkmk@sejong.kr",    role: "manager",  last_seen: "오늘 09:14", created_at: "2026-05-21", is_active: true },
  { id: "u-004", name: "이지훈", email: "leejh@sejong.kr",     role: "manager",  last_seen: "3일 전",     created_at: "2026-05-25", is_active: false },
];

// ─── 헤더 + 네비 (다른 페이지와 동일 톤) ────────────────────────────
function Header() {
  return (
    <header className="cat-header">
      <div className="cat-header-inner">
        <a className="cat-brand" href="관리자.html">
          <img className="cat-brand-mark" src="assets/symbol-brush.svg" alt="" />
          <div>
            <div className="cat-brand-name">스페셜라이즈드 세종점</div>
            <div className="cat-brand-sub">Specialized · Sejong</div>
          </div>
        </a>
        <div className="cat-header-sep" />
        <div className="cat-header-title">직원 관리 · <b>Staff</b></div>
        <div className="cat-header-tools">
          <span>현재 <b>{window.AUTH?.user?.email || "owner"}</b> 로그인</span>
        </div>
      </div>
    </header>
  );
}

function PageNav() {
  return (
    <nav className="cat-pagenav">
      <div className="cat-pagenav-inner">
        <a href="관리자.html" className="cat-pagenav-tab">📊 관리자</a>
        <a href="스케줄러.html" className="cat-pagenav-tab">📅 스케줄러</a>
        <a href="2026 카탈로그.html" className="cat-pagenav-tab">📖 카탈로그</a>
        <a href="재고관리.html" className="cat-pagenav-tab">📦 재고관리</a>
        <a href="서비스 견적서.html" className="cat-pagenav-tab">🧾 견적서</a>
        <a href="직원관리.html" className="cat-pagenav-tab on">👥 직원 관리</a>
      </div>
    </nav>
  );
}

// ─── 직원 카드 ─────────────────────────────────────────────────────
function StaffCard({ staff, onAction }) {
  const r = ROLE_LABEL[staff.role] || { ko: staff.role, emoji: "❓", color: "var(--grey-500)", bg: "var(--grey-100)" };
  const inactive = !staff.is_active;
  return (
    <div style={{
      background: "#fff",
      border: "1px solid var(--grey-200,#E5E8EB)",
      borderRadius: 12, padding: 20, opacity: inactive ? 0.55 : 1,
      transition: "transform .15s, box-shadow .15s",
    }}
    onMouseEnter={e=>{e.currentTarget.style.transform="translateY(-2px)";e.currentTarget.style.boxShadow="0 4px 12px rgba(0,0,0,0.06)";}}
    onMouseLeave={e=>{e.currentTarget.style.transform="";e.currentTarget.style.boxShadow="";}}>
      <div style={{display:"flex",alignItems:"flex-start",gap:14,marginBottom:14}}>
        <div style={{
          width:48,height:48,borderRadius:24,
          background:r.color,color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",
          fontSize:20,fontWeight:700
        }}>
          {staff.name?.[0] || "?"}
        </div>
        <div style={{flex:1,minWidth:0}}>
          <div style={{display:"flex",alignItems:"center",gap:6}}>
            <span style={{fontSize:16,fontWeight:700,color:"var(--grey-900)"}}>{staff.name}</span>
            {inactive && <span style={{fontSize:11,padding:"2px 6px",background:"var(--grey-200)",borderRadius:4,color:"var(--grey-600)"}}>비활성</span>}
          </div>
          <div style={{fontSize:13,color:"var(--grey-600)",marginTop:2,wordBreak:"break-all"}}>{staff.email}</div>
        </div>
      </div>

      <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:14}}>
        <span style={{
          padding:"4px 10px",borderRadius:6,
          background:r.bg,color:r.color,fontSize:12,fontWeight:600
        }}>
          {r.emoji} {r.ko}
        </span>
        <span style={{fontSize:12,color:"var(--grey-500)"}}>마지막: {staff.last_seen}</span>
      </div>

      <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
        <button className="cat-btn cat-btn-secondary" style={{flex:1,minWidth:120,fontSize:12,padding:"8px 12px"}}
          onClick={()=>onAction("role", staff)}>역할 변경</button>
        <button className="cat-btn cat-btn-secondary" style={{flex:1,minWidth:120,fontSize:12,padding:"8px 12px"}}
          onClick={()=>onAction("reset", staff)}>비번 리셋</button>
        <button className="cat-btn cat-btn-secondary" style={{flex:1,minWidth:120,fontSize:12,padding:"8px 12px"}}
          onClick={()=>onAction("signout", staff)}>세션 종료</button>
        <button className="cat-btn cat-btn-secondary" style={{flex:"0 0 auto",fontSize:12,padding:"8px 10px"}}
          onClick={()=>onAction("toggle", staff)}>
          {inactive ? "활성화" : "비활성"}
        </button>
      </div>
    </div>
  );
}

// ─── 역할 변경 모달 ────────────────────────────────────────────────
function RoleModal({ staff, onClose, onSave }) {
  const [role, setRole] = useState(staff.role);
  return (
    <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",zIndex:1000,
                 display:"flex",alignItems:"center",justifyContent:"center"}} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{
        background:"#fff",borderRadius:16,padding:28,maxWidth:480,width:"90%"
      }}>
        <h3 style={{margin:"0 0 8px",font:"700 22px/1.3 var(--font-sans)"}}>역할 변경</h3>
        <p style={{margin:"0 0 20px",color:"var(--grey-600)",fontSize:14}}>
          <b>{staff.name}</b> ({staff.email})의 권한을 변경합니다.
        </p>

        <div style={{display:"flex",flexDirection:"column",gap:10,marginBottom:24}}>
          {Object.entries(ROLE_LABEL).map(([k, r])=>(
            <label key={k} style={{
              display:"flex",alignItems:"center",gap:12,padding:"14px 16px",
              border:`2px solid ${role===k ? r.color : "var(--grey-200)"}`,
              borderRadius:10,cursor:"pointer",
              background: role===k ? r.bg : "#fff",
              transition:"all .15s"
            }}>
              <input type="radio" name="role" value={k} checked={role===k} onChange={()=>setRole(k)} />
              <span style={{fontSize:24,lineHeight:1}}>{r.emoji}</span>
              <span style={{flex:1}}>
                <span style={{display:"block",fontSize:15,fontWeight:700,color:"var(--grey-900)"}}>{r.ko}</span>
                <span style={{display:"block",fontSize:12,color:"var(--grey-600)",marginTop:2}}>
                  {k==="owner"  && "전체 권한 — 가격/직원/CSV 모두 가능"}
                  {k==="mechanic" && "재고 R/W + 견적 발행 + 출고 가능"}
                  {k==="manager"  && "재고 입고 + 콘텐츠 편집 (출고 불가)"}
                </span>
              </span>
            </label>
          ))}
        </div>

        <div style={{display:"flex",gap:8,justifyContent:"flex-end"}}>
          <button className="cat-btn cat-btn-secondary" onClick={onClose}>취소</button>
          <button className="cat-btn cat-btn-primary" onClick={()=>onSave(staff.id, role)}
            disabled={role===staff.role}>저장</button>
        </div>
      </div>
    </div>
  );
}

// ─── 가입 신청 URL 공유 모달 (v3.11 — 초대 방식 → 공개 URL 방식) ───────
function InviteModal({ onClose }) {
  const url = location.origin + location.pathname.replace(/[^/]+$/, "") + "가입신청.html";
  const [copied, setCopied] = useState(false);
  const copy = () => {
    navigator.clipboard?.writeText(url);
    setCopied(true);
    setTimeout(()=>setCopied(false), 2000);
  };
  return (
    <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",zIndex:1000,
                 display:"flex",alignItems:"center",justifyContent:"center"}} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{
        background:"#fff",borderRadius:16,padding:28,maxWidth:520,width:"90%"
      }}>
        <h3 style={{margin:"0 0 8px",font:"700 22px/1.3 var(--font-sans)"}}>📨 가입 신청 URL 공유</h3>
        <p style={{margin:"0 0 20px",color:"var(--grey-600)",fontSize:14,lineHeight:1.6}}>
          신규 직원에게 아래 URL만 전달하면 됩니다.<br/>
          직원이 본인 정보로 가입 신청 → <b>아래 "승인 대기"</b> 섹션에 자동 표시됩니다.
        </p>

        <div style={{
          padding:"14px 16px",background:"var(--grey-50,#F9FAFB)",
          borderRadius:8,fontFamily:"var(--font-mono)",fontSize:13,
          color:"var(--grey-800)",wordBreak:"break-all",marginBottom:16
        }}>
          {url}
        </div>

        <div style={{background:"#FFF9E7",border:"1px solid #F5C97A",borderRadius:8,
                     padding:"12px 14px",marginBottom:20,fontSize:13,color:"#7C5A00",lineHeight:1.5}}>
          💡 새 흐름 (v3.11):
          <ol style={{margin:"6px 0 0",paddingLeft:20}}>
            <li>직원이 위 URL에서 본인 이메일·비밀번호 신청</li>
            <li>본 페이지 <b>"⏳ 승인 대기"</b> 섹션에 카드로 자동 표시</li>
            <li>승인 → 즉시 manager 권한으로 로그인 가능</li>
          </ol>
        </div>

        <div style={{display:"flex",gap:8,justifyContent:"flex-end"}}>
          <button className="cat-btn cat-btn-secondary" onClick={onClose}>닫기</button>
          <button className="cat-btn cat-btn-primary" onClick={copy}>
            {copied ? "✓ 복사됨" : "📋 URL 복사"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── 승인 대기 카드 (v3.11 신규) ─────────────────────────────────
function PendingCard({ req, onApprove, onReject }) {
  const requestedAt = new Date(req.requested_at);
  const hours = Math.floor((Date.now() - requestedAt.getTime()) / 3600000);
  const ago = hours < 1 ? "방금" : hours < 24 ? `${hours}시간 전` : `${Math.floor(hours/24)}일 전`;
  return (
    <div style={{
      background:"#fff",
      border:"2px solid #FFB800",
      borderRadius:12,padding:18,
      boxShadow:"0 2px 8px rgba(255,184,0,0.1)",
    }}>
      <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:12}}>
        <span style={{
          padding:"2px 8px",background:"#FFF4E0",color:"#7C5A00",
          fontSize:11,fontWeight:700,borderRadius:4,
        }}>⏳ 승인 대기</span>
        <span style={{fontSize:12,color:"var(--grey-500,#8B95A1)"}}>{ago}</span>
      </div>
      <div style={{fontSize:16,fontWeight:700,color:"var(--grey-900,#191F28)",marginBottom:4}}>
        {req.name}
      </div>
      <div style={{fontSize:13,color:"var(--grey-600,#6B7684)",wordBreak:"break-all",marginBottom:12}}>
        {req.email}
      </div>
      <div style={{fontSize:12,color:"var(--grey-500,#8B95A1)",marginBottom:14}}>
        신청 시각: {requestedAt.toLocaleString("ko-KR")}
      </div>
      <div style={{display:"flex",gap:6}}>
        <button onClick={()=>onReject(req)} style={{
          flex:1,padding:"8px 12px",border:"1px solid var(--grey-300,#D1D6DB)",
          borderRadius:6,background:"#fff",cursor:"pointer",fontSize:13,
          color:"var(--grey-700,#4E5968)",
        }}>거절</button>
        <button onClick={()=>onApprove(req)} style={{
          flex:2,padding:"8px 12px",border:"none",
          borderRadius:6,background:"#0E8F5F",color:"#fff",
          cursor:"pointer",fontSize:13,fontWeight:600,
        }}>✓ 승인 (manager 권한)</button>
      </div>
    </div>
  );
}

// ─── 메인 App ──────────────────────────────────────────────────────
function App() {
  const [staff, setStaff] = useState(MOCK_STAFF);
  const [pending, setPending] = useState([]); // v3.11: 승인 대기 직원
  const [roleModal, setRoleModal] = useState(null);
  const [inviteOpen, setInviteOpen] = useState(false);
  const [filter, setFilter] = useState("all");

  // RBAC v1.1: staff.view 권한 체크 (호환 레이어 — owner 폴백)
  const can = (key) => window.AUTH?.can?.(key) ?? (window.AUTH?.role === "owner");
  const myRole = window.AUTH?.role || "owner";
  const isOwner = can("staff.view"); // 변수명은 보존, 의미만 RBAC로 교체

  // Supabase 통합 (실 운영 시 fetch)
  useEffect(() => {
    if (!window.DAL?.isOnline) return;
    (async () => {
      try {
        const { data, error } = await window.DAL.client
          .from("user_profiles")
          .select("id, name, role, created_at, avatar_color, approval_status")
          .order("created_at");
        if (error) throw error;
        if (data && data.length > 0) {
          // 승인 완료 직원만 카드에
          setStaff(data.filter(d => d.approval_status !== "pending").map(d => ({
            ...d,
            email: d.id, // 임시 — auth.users 조인 필요
            last_seen: "—",
            is_active: d.approval_status !== "rejected",
          })));
          // 승인 대기 직원
          setPending(data.filter(d => d.approval_status === "pending").map(d => ({
            id: d.id, name: d.name, email: d.id,
            requested_at: d.created_at,
          })));
        }
      } catch (e) { console.warn("[staff] fetch fail:", e); }
    })();
  }, []);

  // v3.11: mock 모드에서 localStorage의 가입신청 큐 로드
  useEffect(() => {
    if (window.DAL?.isOnline) return;
    try {
      const raw = localStorage.getItem("sejong-pending-signups");
      if (raw) setPending(JSON.parse(raw));
    } catch (e) { console.warn("[staff] pending load fail:", e); }
  }, []);

  // v3.11: 승인 처리
  const handleApprove = async (req) => {
    if (!confirm(`${req.name}님(${req.email})을 manager 권한으로 승인하시겠습니까?`)) return;
    if (window.DAL?.isOnline) {
      try {
        await window.DAL.client.from("user_profiles")
          .update({ approval_status: "approved", role: "manager" })
          .eq("id", req.id);
      } catch (e) { alert("승인 실패: " + e.message); return; }
    } else {
      // mock: 큐에서 제거 + staff에 추가
      const newStaff = {
        id: req.id, name: req.name, email: req.email,
        role: "manager", last_seen: "방금",
        created_at: new Date().toISOString().slice(0,10), is_active: true,
      };
      setStaff(prev => [...prev, newStaff]);
    }
    const remaining = pending.filter(p => p.id !== req.id);
    setPending(remaining);
    if (!window.DAL?.isOnline) {
      localStorage.setItem("sejong-pending-signups", JSON.stringify(remaining));
    }
    if (window.SECURITY) window.SECURITY.showToast(`${req.name}님 승인 완료`, "success");
    else alert(`✓ ${req.name}님이 manager 권한으로 승인되었습니다.`);
  };

  const handleReject = async (req) => {
    if (!confirm(`${req.name}님의 가입 신청을 거절하시겠습니까?\n계정은 삭제됩니다.`)) return;
    if (window.DAL?.isOnline) {
      try {
        await window.DAL.client.from("user_profiles")
          .update({ approval_status: "rejected" })
          .eq("id", req.id);
      } catch (e) { alert("거절 실패: " + e.message); return; }
    }
    const remaining = pending.filter(p => p.id !== req.id);
    setPending(remaining);
    if (!window.DAL?.isOnline) {
      localStorage.setItem("sejong-pending-signups", JSON.stringify(remaining));
    }
  };

  if (!isOwner) {
    return (
      <div style={{padding:"80px 24px",textAlign:"center"}}>
        <div style={{fontSize:48,marginBottom:16}}>🔒</div>
        <h2 style={{margin:"0 0 8px"}}>접근 권한 없음</h2>
        <p style={{color:"var(--grey-600)",marginBottom:8}}>
          이 페이지는 직원 관리 권한이 필요합니다.<br/>
          현재 역할: <b>{ROLE_LABEL[myRole]?.ko || myRole}</b> · 보유 권한 <b>{(window.AUTH?.permissions || []).length}개</b>
        </p>
        {/* v3.17: 권한 fetch가 비어 있으면 권한 재로딩 가능성 안내 */}
        {(window.AUTH?.permissions || []).length === 0 && (
          <p style={{color:"var(--red-500,#E31E26)", fontSize:13, marginBottom:16}}>
            ⚠️ 권한 목록이 비어 있습니다 — 로그아웃 후 다시 로그인하면 새 권한이 적용됩니다.
          </p>
        )}
        <div style={{display:"flex", gap:8, justifyContent:"center"}}>
          <a href="관리자.html" className="cat-btn cat-btn-secondary">← 관리자 대시보드</a>
          <button className="cat-btn cat-btn-primary" onClick={async () => {
            if (!confirm("로그아웃하고 다시 로그인하시겠습니까?")) return;
            try { await window.DAL?.signOut?.(); } catch {}
            try { localStorage.removeItem("sejong-bike-auth"); } catch {}
            location.href = "로그인.html";
          }}>🚪 로그아웃 + 재로그인</button>
        </div>
      </div>
    );
  }

  const filtered = filter === "all" ? staff
                  : filter === "active" ? staff.filter(s=>s.is_active)
                  : staff.filter(s=>!s.is_active);

  const handleAction = async (action, s) => {
    if (action === "role") {
      setRoleModal(s);
    } else if (action === "reset") {
      if (!confirm(`${s.name}님의 비밀번호를 임시 비번으로 리셋하시겠습니까?\n임시 비번은 토스트로 표시됩니다.`)) return;
      const tmp = Math.random().toString(36).slice(2, 10);
      if (window.DAL?.isOnline) {
        // 실 운영: Supabase Admin API 필요 (service_role)
        alert(`📝 안내: Supabase Dashboard → Authentication → ${s.email} → "Send password recovery" 메일 발송\n또는 SQL Editor에서 admin API 호출 필요`);
      } else {
        navigator.clipboard?.writeText(tmp);
        alert(`임시 비밀번호 (클립보드 복사됨):\n${tmp}\n\n${s.name}님에게 전달 후 첫 로그인 시 본인 비번으로 변경 안내`);
      }
    } else if (action === "signout") {
      if (!confirm(`${s.name}님의 모든 세션을 종료하시겠습니까?\n현재 사용 중이면 즉시 로그아웃됩니다.`)) return;
      if (window.DAL?.isOnline) {
        alert(`📝 안내: Supabase Dashboard → Authentication → Users → ${s.email} → "Sign out user"`);
      } else {
        alert(`(mock) ${s.name}님 세션 종료됨`);
      }
    } else if (action === "toggle") {
      const next = !s.is_active;
      setStaff(staff.map(x => x.id === s.id ? {...x, is_active: next} : x));
      if (window.DAL?.isOnline) {
        await window.DAL.client.from("user_profiles").update({ is_active: next }).eq("id", s.id);
      }
    }
  };

  const saveRole = async (id, newRole) => {
    setStaff(staff.map(s => s.id === id ? {...s, role: newRole} : s));
    if (window.DAL?.isOnline) {
      const { error } = await window.DAL.client.from("user_profiles").update({ role: newRole }).eq("id", id);
      if (error) alert("저장 실패: " + error.message);
    }
    setRoleModal(null);
    if (window.SECURITY) window.SECURITY.showToast(`역할 변경 완료: ${newRole}`, "success");
  };

  return (
    <div className="cat-app">
      <Header />
      <PageNav />
      <main className="adm-main">
        <div className="cat-inner">
          <div className="adm-page-head">
            <div>
              <h1>👥 직원 관리</h1>
              <p>직원 가입 승인 + 역할 부여 + 비밀번호 리셋 + 세션 종료. <b>owner 전용</b>.</p>
            </div>
            <div className="adm-page-head-tools">
              {can("settings.role_edit") && (
                <a className="cat-btn cat-btn-secondary" href="권한설정.html" style={{textDecoration:"none"}}>
                  🔐 권한 편집
                </a>
              )}
              <button className="cat-btn cat-btn-primary" onClick={()=>setInviteOpen(true)}>
                📨 가입 신청 URL
              </button>
            </div>
          </div>

          {/* v3.11: 승인 대기 섹션 — pending이 있을 때만 노출 */}
          {pending.length > 0 && (
            <section style={{marginBottom:28}}>
              <div style={{display:"flex",alignItems:"center",gap:10,marginBottom:12}}>
                <h2 style={{margin:0,font:"700 18px/1.3 var(--font-sans)"}}>⏳ 승인 대기</h2>
                <span style={{
                  padding:"3px 10px",background:"#FFB800",color:"#fff",
                  borderRadius:12,fontSize:12,fontWeight:700,
                }}>{pending.length}건</span>
                <span style={{fontSize:13,color:"var(--grey-500,#8B95A1)"}}>
                  · 직원이 가입신청.html에서 신청한 계정입니다.
                </span>
              </div>
              <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(280px, 1fr))",gap:12}}>
                {pending.map(req => (
                  <PendingCard key={req.id} req={req} onApprove={handleApprove} onReject={handleReject} />
                ))}
              </div>
            </section>
          )}

          {/* 필터 */}
          <div style={{display:"flex",gap:8,marginBottom:20}}>
            {[
              {id:"all", label:"전체"},
              {id:"active", label:"활성"},
              {id:"inactive", label:"비활성"},
            ].map(f => (
              <button key={f.id} onClick={()=>setFilter(f.id)} style={{
                padding:"8px 16px",borderRadius:8,border:0,cursor:"pointer",
                background: filter===f.id ? "var(--grey-900)" : "var(--grey-100)",
                color: filter===f.id ? "#fff" : "var(--grey-700)",
                fontSize:13,fontWeight:600,
              }}>
                {f.label} <span style={{opacity:0.7,marginLeft:4}}>
                  {f.id==="all" ? staff.length : f.id==="active" ? staff.filter(s=>s.is_active).length : staff.filter(s=>!s.is_active).length}
                </span>
              </button>
            ))}
            <div style={{flex:1}}></div>
            <span style={{fontSize:12,color:"var(--grey-500)",alignSelf:"center"}}>
              💡 가입 직후 기본 역할: <b>manager</b>
            </span>
          </div>

          {/* 직원 카드 그리드 */}
          {filtered.length === 0 ? (
            <div style={{padding:80,textAlign:"center",background:"var(--grey-50)",borderRadius:12}}>
              <div style={{fontSize:48,marginBottom:12}}>👥</div>
              <h3 style={{margin:"0 0 8px"}}>직원이 없어요</h3>
              <p style={{color:"var(--grey-600)",marginBottom:20}}>
                "+ 새 직원 초대" 버튼으로 가입 URL을 공유하세요.
              </p>
              <button className="cat-btn cat-btn-primary" onClick={()=>setInviteOpen(true)}>
                + 새 직원 초대
              </button>
            </div>
          ) : (
            <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(320px, 1fr))",gap:14}}>
              {filtered.map(s => <StaffCard key={s.id} staff={s} onAction={handleAction} />)}
            </div>
          )}

          {/* 권한 안내 */}
          <div style={{marginTop:32,padding:"20px 24px",background:"var(--grey-50,#F9FAFB)",borderRadius:12}}>
            <h4 style={{margin:"0 0 12px",fontSize:14}}>📋 권한 비교</h4>
            <table style={{width:"100%",borderCollapse:"collapse",fontSize:13}}>
              <thead>
                <tr style={{borderBottom:"1px solid var(--grey-200)"}}>
                  <th style={{textAlign:"left",padding:"8px 0"}}>기능</th>
                  <th style={{padding:"8px 0"}}>👑 owner</th>
                  <th style={{padding:"8px 0"}}>🔧 mechanic</th>
                  <th style={{padding:"8px 0"}}>📦 manager</th>
                </tr>
              </thead>
              <tbody>
                {[
                  ["가격 수정", "✅", "✅", "✅"],
                  ["재고 입고", "✅", "✅", "✅"],
                  ["재고 출고", "✅", "✅", "❌"],
                  ["견적 발행", "✅", "✅", "❌"],
                  ["카탈로그 콘텐츠 편집", "✅", "❌", "✅"],
                  ["직원 관리 (본 페이지)", "✅", "❌", "❌"],
                  ["매장 정보 설정", "✅", "❌", "❌"],
                  ["활동 로그 조회", "✅", "❌", "❌"],
                  ["전체 매출액 조회", "✅", "🔒", "🔒"],
                ].map(([f, o, m, mg], i) => (
                  <tr key={i} style={{borderBottom:"1px solid var(--grey-100)"}}>
                    <td style={{padding:"8px 0",color:"var(--grey-800)"}}>{f}</td>
                    <td style={{textAlign:"center",padding:"8px 0"}}>{o}</td>
                    <td style={{textAlign:"center",padding:"8px 0"}}>{m}</td>
                    <td style={{textAlign:"center",padding:"8px 0"}}>{mg}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            <p style={{margin:"12px 0 0",fontSize:12,color:"var(--grey-600)"}}>
              🔒 = 매출 마스킹 (₩***로 표시). owner만 실제 금액 확인 가능.
            </p>
          </div>
        </div>
      </main>

      {/* 모달 */}
      {roleModal && <RoleModal staff={roleModal} onClose={()=>setRoleModal(null)} onSave={saveRole} />}
      {inviteOpen && <InviteModal onClose={()=>setInviteOpen(false)} />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
