// Client Company Workspace shell — sidebar + topbar + page router

const WS_NAV = [
  { id:"dashboard",   label:"Dashboard",        icon:"dashboard" },
  { id:"matrix",      label:"RACI Matrix",      icon:"table" },
  { id:"process",     label:"Process Master",   icon:"workflow" },
  { id:"org",         label:"Organization Chart", icon:"network" },
  { id:"mapping",     label:"Employee Mapping", icon:"users" },
  { id:"users",       label:"User Management",  icon:"user" },
  { id:"audit",       label:"Audit Logs",       icon:"history" },
  { id:"settings",    label:"Settings",         icon:"settings" },
];

const ROLE_META = {
  super_admin: { label:"Super Admin", color:"bg-indigo-950 text-white" },
  admin: { label:"Company Admin", color:"bg-indigo-600 text-white" },
  manager:{ label:"Manager / Approver", color:"bg-violet-600 text-white" },
  employee:{ label:"Employee / Preparer", color:"bg-blue-600 text-white" },
  viewer:{ label:"Viewer / Executive", color:"bg-slate-600 text-white" },
};

const ClientWorkspace = ({
  tenant, currentRole, setCurrentRole, currentUserId, setCurrentUserId,
  onLogout, onReturnSuperAdmin, supportMode,
  tweaks, setTweak,
  tasks, setTasks, taskHistory, setTaskHistory, comments, setComments, auditLog, setAuditLog,
  subprocesses, setSubprocesses, // editable master data
  positions, setPositions,
  divisions, setDivisions,
  departments, setDepartments,
  users, setUsers,
  mainProcesses, setMainProcesses,
  processes, setProcesses,
}) => {
  const [page, setPage] = useState("dashboard");
  const [collapsed, setCollapsed] = useState(false);
  const [period, setPeriod] = useState({ month: 5, year: 2026 });
  const [matrixFullscreen, setMatrixFullscreen] = useState(false);
  const [pendingMatrixDate, setPendingMatrixDate] = useState(null); // when user jumps from dashboard

  const accentClass = tweaks.accent === "emerald" ? "from-emerald-500 to-emerald-700"
    : tweaks.accent === "sky" ? "from-sky-500 to-sky-700"
    : tweaks.accent === "violet" ? "from-violet-500 to-violet-700"
    : "from-indigo-500 to-indigo-700";

  // current user object for role
  const currentUser = users.find(u => u.id === currentUserId) || null;

  // Wrap setAuditLog: also POST to API for persistence.
  // Use a callback shape: appendAudit({ action, reason, entity_type, entity_id, who })
  const appendAudit = (entry) => {
    const optimistic = {
      id: "a" + Math.random().toString(36).slice(2, 7),
      scope: "tenant", tenant_id: tenant?.id,
      action: entry.action || "update",
      reason: entry.reason || "",
      performed_by: entry.who || currentUser?.full_name || "ผู้ใช้",
      at: nowStamp(),
    };
    setAuditLog(prev => [optimistic, ...prev]);
    if (window.apiClient && tenant?.id) {
      window.apiClient.addAuditLog(tenant.id, {
        action: entry.action,
        reason: entry.reason,
        entity_type: entry.entity_type,
        entity_id: entry.entity_id,
      }).catch(() => {});
    }
  };
  // Expose to child pages (process-master / org-chart / etc passes setAuditLog still)
  // Override setAuditLog wrapper that also posts to API
  const setAuditLogPersist = (updater) => {
    setAuditLog(prev => {
      const next = typeof updater === "function" ? updater(prev) : updater;
      // Detect newly added entries (compared to prev) — POST them to API
      if (window.apiClient && tenant?.id && Array.isArray(next) && Array.isArray(prev)) {
        const prevIds = new Set(prev.map(x => x.id));
        next.filter(x => !prevIds.has(x.id)).forEach(entry => {
          window.apiClient.addAuditLog(tenant.id, {
            action: entry.action,
            reason: entry.reason,
            entity_type: entry.entity_type,
            entity_id: entry.entity_id,
          }).catch(() => {});
        });
      }
      return next;
    });
  };

  // Only Company Admin (or Super Admin in support mode) can edit master data
  const canEdit = currentRole === "admin" || supportMode;

  // === Persistence: Process Master + Org Chart + Employee Mapping + Tasks State ===
  const pmHydratedRef = useRef(false);
  const orgHydratedRef = useRef(false);
  const epHydratedRef = useRef(false);
  const tsHydratedRef = useRef(false);
  const toastApi = useToast();
  // Track recent save errors so we don't spam — show one toast per category per 30s.
  const lastErrorAtRef = useRef({});
  const reportSaveError = (category, err) => {
    const now = Date.now();
    if ((now - (lastErrorAtRef.current[category] || 0)) < 30000) return;
    lastErrorAtRef.current[category] = now;
    toastApi({ kind: "error", msg: `บันทึก ${category} ลงระบบไม่สำเร็จ — เครือข่ายหรือสิทธิ์มีปัญหา · กรุณาลองรีเฟรชหน้า (${err?.message || "unknown"})` });
  };

  useEffect(() => {
    if (!tenant?.id || !window.apiClient) return;
    pmHydratedRef.current = false;
    orgHydratedRef.current = false;
    epHydratedRef.current = false;
    tsHydratedRef.current = false;

    // Process Master — always replace (empty arrays from API mean "tenant has no data yet")
    window.apiClient.getProcessMaster(tenant.id).then(data => {
      setMainProcesses(Array.isArray(data?.main_processes) ? data.main_processes : []);
      setProcesses(Array.isArray(data?.processes) ? data.processes : []);
      setSubprocesses(Array.isArray(data?.sub_processes) ? data.sub_processes : []);
      setTimeout(() => { pmHydratedRef.current = true; }, 200);
    }).catch(() => { setTimeout(() => { pmHydratedRef.current = true; }, 200); });

    // Org Chart — always replace
    window.apiClient.getOrgChart(tenant.id).then(data => {
      setDivisions(Array.isArray(data?.divisions) ? data.divisions : []);
      setDepartments(Array.isArray(data?.departments) ? data.departments : []);
      setPositions(Array.isArray(data?.positions) ? data.positions : []);
      setTimeout(() => { orgHydratedRef.current = true; }, 200);
    }).catch(() => { setTimeout(() => { orgHydratedRef.current = true; }, 200); });

    // Users (tenant members) + Employee Positions — load both, then merge
    Promise.all([
      window.apiClient.getUsers(tenant.id).catch(() => []),
      window.apiClient.getEmployeePositions(tenant.id).catch(() => []),
    ]).then(([rows, posRows]) => {
      const userList = Array.isArray(rows) ? rows : [];
      const byUser = {};
      (Array.isArray(posRows) ? posRows : []).forEach(r => {
        if (!byUser[r.user_id]) byUser[r.user_id] = [];
        byUser[r.user_id].push(r.position_id);
      });
      const mapped = userList.map(r => ({
        id: r.user_id || r.id,
        membership_id: r.id,
        api_user_id: r.user_id,
        full_name: ((r.first_name || '') + ' ' + (r.last_name || '')).trim() || r.email,
        email: r.email,
        employee_code: r.employee_code || '',
        system_role: r.role,
        status: r.status,
        positions: byUser[r.user_id || r.id] || [],
        from_api: true,
      }));
      setUsers(mapped);
      setTimeout(() => { epHydratedRef.current = true; }, 200);
    });

    // Tenant Audit Log
    window.apiClient.getTenantAuditLogs(tenant.id, 200).then(rows => {
      if (Array.isArray(rows)) {
        setAuditLog(rows.map(r => ({
          id: r.id, scope: "tenant",
          tenant_id: r.tenant_id, action: r.action,
          reason: r.details || r.action,
          performed_by: r.performed_by || "system",
          at: r.created_at,
        })));
      }
    }).catch(() => {});

    // Tasks State — always replace
    window.apiClient.getTasksState(tenant.id).then(data => {
      setTasks(Array.isArray(data?.tasks) ? data.tasks : []);
      setTaskHistory(data?.task_history && typeof data.task_history === 'object' ? data.task_history : {});
      setComments(data?.comments && typeof data.comments === 'object' ? data.comments : {});
      setTimeout(() => { tsHydratedRef.current = true; }, 300);
    }).catch(() => { setTimeout(() => { tsHydratedRef.current = true; }, 300); });
    // eslint-disable-next-line
  }, [tenant?.id]);

  // Autosave Process Master
  useEffect(() => {
    if (!pmHydratedRef.current || !tenant?.id || !window.apiClient || !canEdit) return;
    const handle = setTimeout(() => {
      window.apiClient.saveProcessMaster(tenant.id, {
        main_processes: mainProcesses, processes, sub_processes: subprocesses,
      }).catch(e => reportSaveError("Process Master", e));
    }, 800);
    return () => clearTimeout(handle);
  }, [mainProcesses, processes, subprocesses, tenant?.id, canEdit]);

  // Autosave Org Chart
  useEffect(() => {
    if (!orgHydratedRef.current || !tenant?.id || !window.apiClient || !canEdit) return;
    const handle = setTimeout(() => {
      window.apiClient.saveOrgChart(tenant.id, { divisions, departments, positions })
        .catch(e => reportSaveError("Organization Chart", e));
    }, 800);
    return () => clearTimeout(handle);
  }, [divisions, departments, positions, tenant?.id, canEdit]);

  // Autosave Employee Mapping (extract user.positions[] back into mapping rows)
  useEffect(() => {
    if (!epHydratedRef.current || !tenant?.id || !window.apiClient || !canEdit) return;
    const handle = setTimeout(() => {
      const items = [];
      users.forEach(u => {
        // Persist API-backed users only — must have a real users.id from server
        if (!u.id || !String(u.id).startsWith('usr-')) return;
        (u.positions || []).forEach((pid, idx) => {
          items.push({ user_id: u.id, position_id: pid, is_primary: idx === 0 ? 1 : 0 });
        });
      });
      window.apiClient.saveEmployeePositions(tenant.id, items)
        .catch(e => reportSaveError("Employee Mapping", e));
    }, 800);
    return () => clearTimeout(handle);
  }, [users, tenant?.id, canEdit]);

  // Autosave Tasks State (snapshot + history + comments) — longer debounce because payload is bigger.
  // Any active member can update (R submits, A approves, etc.) → no canEdit gate here.
  useEffect(() => {
    if (!tsHydratedRef.current || !tenant?.id || !window.apiClient) return;
    const handle = setTimeout(() => {
      window.apiClient.saveTasksState(tenant.id, {
        tasks,
        task_history: taskHistory,
        comments,
      }).catch(e => reportSaveError("สถานะรายวัน", e));
    }, 2000);
    return () => clearTimeout(handle);
  }, [tasks, taskHistory, comments, tenant?.id]);

  const pageMeta = {
    dashboard: { title:"Management Dashboard", subtitle:"มอนิเตอร์การปฏิบัติงานตาม RACI Matrix แบบ Real-time" },
    matrix:    { title:"RACI Matrix", subtitle:"ตารางหลักของการมอบหมายความรับผิดชอบและสถานะรายวัน" },
    process:   { title:"Process Master", subtitle:"กำหนด Main Process → Process → Sub-process และผูก RACI" },
    org:       { title:"Organization Chart", subtitle:"จัดการ Division → Department → Position" },
    mapping:   { title:"Employee Mapping", subtitle:"ผูกพนักงานกับตำแหน่งในผังองค์กร" },
    users:     { title:"User Management", subtitle:"จัดการผู้ใช้งานและสิทธิ์ในบริษัท" },
    audit:     { title:"Audit Logs", subtitle:"ติดตามการเปลี่ยนแปลงในระบบทั้งหมด" },
    settings:  { title:"Settings", subtitle:"การตั้งค่าทั่วไป" },
  };

  if (matrixFullscreen) {
    // Full-bleed matrix
    return (
      <RaciMatrixPage tenant={tenant} period={period} setPeriod={setPeriod}
        currentRole={currentRole} currentUser={currentUser}
        tasks={tasks} setTasks={setTasks}
        taskHistory={taskHistory} setTaskHistory={setTaskHistory}
        comments={comments} setComments={setComments}
        auditLog={auditLog} setAuditLog={setAuditLogPersist}
        subprocesses={subprocesses}
        positions={positions} divisions={divisions} departments={departments} users={users}
        mainProcesses={mainProcesses} processes={processes}
        tweaks={tweaks}
        fullscreen={true} onExitFullscreen={()=>setMatrixFullscreen(false)}/>
    );
  }

  return (
    <div className="min-h-screen flex bg-ink-50">
      {/* Sidebar */}
      <aside className={`relative shrink-0 ${collapsed?"w-[68px]":"w-[232px]"} transition-all border-r border-ink-200 bg-white flex flex-col`}>
        <div className="px-3 py-4 flex items-center gap-2.5">
          <div className={`w-9 h-9 rounded-xl bg-gradient-to-br ${accentClass} text-white flex items-center justify-center shadow-sm`}>
            <Icon name="layers" size={17}/>
          </div>
          {!collapsed && (
            <div className="min-w-0">
              <div className="text-[13.5px] font-bold tracking-tight text-ink-900 truncate">RACI Workspace</div>
              <div className="text-[10px] tracking-[.2em] uppercase text-ink-400">Client Workspace</div>
            </div>
          )}
        </div>

        {!collapsed && (
          <div className="px-3 py-2.5 mx-3 rounded-xl bg-gradient-to-br from-ink-50 to-ink-100 border border-ink-200 mb-2">
            <div className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold flex items-center gap-1.5"><Icon name="building" size={10}/>Tenant</div>
            <div className="text-[12.5px] font-semibold text-ink-900 mt-0.5 truncate">{tenant.company_short}</div>
            <div className="text-[10.5px] font-mono text-ink-500">{tenant.tenant_code} · {tenant.plan}</div>
          </div>
        )}

        <div className="px-2 flex-1 space-y-0.5">
          {WS_NAV.map(n => (
            <SidebarItem key={n.id} icon={n.icon} label={n.label}
              active={page===n.id} onClick={()=>setPage(n.id)} collapsed={collapsed}/>
          ))}
        </div>

        <div className="px-2 py-2 border-t border-ink-100">
          <button onClick={()=>setCollapsed(v=>!v)} className="w-full flex items-center justify-center gap-2 h-9 rounded-lg text-ink-500 hover:bg-ink-100 hover:text-ink-800 text-[12px]">
            <Icon name={collapsed?"chevronRight":"chevronLeft"} size={14}/>
            {!collapsed && "ย่อแถบ"}
          </button>
        </div>
      </aside>

      {/* Main */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* Support mode banner */}
        {supportMode && (
          <div className="bg-indigo-600 text-white text-[12px] py-2 px-5 flex items-center gap-3">
            <Icon name="shield" size={14}/>
            <div className="flex-1"><strong className="font-semibold">SUPPORT MODE:</strong> คุณกำลังเข้าถึงข้อมูลของ {tenant.company_short} ในฐานะ Super Admin · การกระทำทุกอย่างจะถูกบันทึก</div>
            <button onClick={onReturnSuperAdmin} className="px-3 h-7 bg-white/20 hover:bg-white/30 rounded-md font-medium">กลับไป Super Admin</button>
          </div>
        )}

        {/* Top bar */}
        <header className="h-14 px-5 flex items-center gap-3 border-b border-ink-200 bg-white">
          {/* Breadcrumb */}
          <div className="flex items-center gap-2 text-[12.5px] text-ink-500 min-w-0">
            <Icon name="building" size={13} className="text-ink-400 shrink-0"/>
            <span className="hidden md:inline truncate">{tenant.company_name}</span>
            <Icon name="chevronRight" size={12} className="text-ink-300 shrink-0"/>
            <span className="text-ink-900 font-medium truncate">{pageMeta[page]?.title}</span>
          </div>

          <div className="ml-auto flex items-center gap-2">
            {/* Period selector */}
            <div className="hidden md:flex items-center gap-1.5 h-8 px-2.5 bg-ink-50 border border-ink-200 rounded-lg text-[12px]">
              <Icon name="calendar" size={12} className="text-ink-500"/>
              <select value={period.month} onChange={e=>setPeriod(p=>({...p, month:+e.target.value}))} className="bg-transparent font-medium focus:outline-none">
                {["ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."].map((m,i)=><option key={i} value={i+1}>{m}</option>)}
              </select>
              <select value={period.year} onChange={e=>setPeriod(p=>({...p, year:+e.target.value}))} className="bg-transparent font-mono font-medium focus:outline-none">
                {(() => { const cy = new Date().getFullYear(); return [cy-2, cy-1, cy, cy+1]; })().map(y=><option key={y} value={y}>{y}</option>)}
              </select>
            </div>

            {/* Search */}
            <div className="relative hidden lg:block">
              <Icon name="search" size={13} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-400"/>
              <input placeholder="ค้นหากระบวนการ / งาน / ผู้ใช้…" className="w-[280px] h-8 pl-8 pr-3 text-[12.5px] bg-ink-50 border border-ink-200 rounded-lg focus:border-brand-500 ring-focus"/>
            </div>

            {/* Notifications */}
            <NotificationBell tasks={tasks} taskHistory={taskHistory} subprocesses={subprocesses} users={users} positions={positions} currentUser={currentUser} currentRole={currentRole} onGoMatrix={()=>setPage("matrix")}/>

            {/* Dark mode toggle */}
            <Tip tip={tweaks.darkMode?"สลับเป็น Light mode":"สลับเป็น Dark mode"}>
              <button onClick={()=>setTweak("darkMode", !tweaks.darkMode)}
                className="w-8 h-8 rounded-lg border border-ink-200 bg-white hover:bg-ink-50 flex items-center justify-center text-ink-600">
                <Icon name={tweaks.darkMode?"sun":"moon"} size={14}/>
              </button>
            </Tip>

            {/* Profile */}
            <ProfileMenu currentRole={currentRole} currentUser={currentUser} setUsers={setUsers} onLogout={onLogout} tenantId={tenant?.id}/>
          </div>
        </header>

        {/* Page content */}
        <main className="flex-1 overflow-y-auto thin-scroll">
          {page === "dashboard" && (
            <DashboardPage tenant={tenant} period={period} setPeriod={setPeriod}
              tasks={tasks} taskHistory={taskHistory} subprocesses={subprocesses}
              users={users} positions={positions} departments={departments} divisions={divisions}
              mainProcesses={mainProcesses} processes={processes}
              onGoMatrix={(date)=>{ if (date) setPendingMatrixDate(date); setPage("matrix"); }}
              tweaks={tweaks}/>
          )}
          {page === "matrix" && (
            <RaciMatrixPage tenant={tenant} period={period} setPeriod={setPeriod}
              currentRole={currentRole} currentUser={currentUser}
              tasks={tasks} setTasks={setTasks}
              taskHistory={taskHistory} setTaskHistory={setTaskHistory}
              comments={comments} setComments={setComments}
              auditLog={auditLog} setAuditLog={setAuditLogPersist}
              subprocesses={subprocesses}
              positions={positions} divisions={divisions} departments={departments} users={users}
              mainProcesses={mainProcesses} processes={processes}
              tweaks={tweaks}
              initialDate={pendingMatrixDate} onConsumedInitialDate={()=>setPendingMatrixDate(null)}
              onFullscreen={()=>setMatrixFullscreen(true)} fullscreen={false}/>
          )}
          {page === "process" && (
            <ProcessMasterPage mainProcesses={mainProcesses} setMainProcesses={setMainProcesses}
              processes={processes} setProcesses={setProcesses}
              subprocesses={subprocesses} setSubprocesses={setSubprocesses}
              positions={positions} departments={departments} divisions={divisions}
              auditLog={auditLog} setAuditLog={setAuditLogPersist} tenant={tenant} canEdit={canEdit}/>
          )}
          {page === "org" && (
            <OrgChartPage divisions={divisions} setDivisions={setDivisions}
              departments={departments} setDepartments={setDepartments}
              positions={positions} setPositions={setPositions}
              users={users} auditLog={auditLog} setAuditLog={setAuditLogPersist} tenant={tenant} canEdit={canEdit}/>
          )}
          {page === "mapping" && (
            <EmployeeMappingPage users={users} setUsers={setUsers}
              positions={positions} departments={departments} divisions={divisions}
              auditLog={auditLog} setAuditLog={setAuditLogPersist} tenant={tenant} canEdit={canEdit}/>
          )}
          {page === "users" && <UserManagementPage users={users} setUsers={setUsers} tenant={tenant} canEdit={canEdit}/>}
          {page === "audit" && <TenantAuditPage auditLog={auditLog} tenant={tenant}/>}
          {page === "settings" && <SettingsPage tenant={tenant}/>}
        </main>
      </div>
    </div>
  );
};

// ----- role switcher -----
const RoleSwitcher = ({ value, onChange, userId, onUserChange, users }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const close = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);
  const roles = [
    { v:"admin", l:"Company Admin", i:"shield" },
    { v:"manager", l:"Manager / Approver", i:"checkCircle" },
    { v:"employee", l:"Employee / Preparer", i:"user" },
    { v:"viewer", l:"Viewer / Executive", i:"eye" },
  ];
  const m = ROLE_META[value];
  return (
    <div className="relative" ref={ref}>
      <button onClick={()=>setOpen(v=>!v)} className="flex items-center gap-2 h-8 px-2.5 rounded-lg border border-dashed border-ink-300 bg-amber-50/50 hover:bg-amber-50 text-[11.5px]">
        <Icon name="sparkles" size={12} className="text-amber-500"/>
        <span className="text-ink-500">Demo role:</span>
        <span className="font-semibold text-ink-800">{m.label}</span>
        <Icon name="chevronDown" size={12} className="text-ink-400"/>
      </button>
      {open && (
        <div className="absolute right-0 top-full mt-2 w-[280px] bg-white border border-ink-200 rounded-xl shadow-xl z-50 p-2 pop">
          <div className="text-[10px] uppercase tracking-wider text-ink-400 font-semibold px-2 py-1.5">Switch demo role</div>
          {roles.map(r => (
            <button key={r.v} onClick={()=>{
              onChange(r.v);
              // auto-select a sensible default user when switching to manager/employee
              if (r.v === "manager" || r.v === "employee") {
                const matchingUser = users.find(u => u.system_role === r.v && u.status === "active");
                if (matchingUser && (!userId || users.find(u=>u.id===userId)?.system_role !== r.v)) {
                  onUserChange(matchingUser.id);
                }
              } else {
                onUserChange(null);
              }
              setOpen(false);
            }} className={`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-left transition ${value===r.v?"bg-brand-50":"hover:bg-ink-50"}`}>
              <Icon name={r.i} size={14} className={value===r.v?"text-brand-600":"text-ink-500"}/>
              <span className={`text-[12.5px] flex-1 ${value===r.v?"text-brand-700 font-semibold":"text-ink-700"}`}>{r.l}</span>
              {value===r.v && <Icon name="check" size={12} className="text-brand-600"/>}
            </button>
          ))}
          {(value === "employee" || value === "manager") && (
            <>
              <div className="text-[10px] uppercase tracking-wider text-ink-400 font-semibold px-2 py-1.5 mt-1 border-t border-ink-100 pt-2">เป็นผู้ใช้:</div>
              <div className="max-h-[180px] overflow-y-auto thin-scroll">
                {users.filter(u => u.system_role === value && u.status==="active").map(u => (
                  <button key={u.id} onClick={()=>{ onUserChange(u.id); setOpen(false); }} className={`w-full flex items-center gap-2 px-2.5 py-1.5 rounded-md text-left transition ${userId===u.id?"bg-brand-50 text-brand-700":"hover:bg-ink-50 text-ink-700"}`}>
                    <Avatar name={u.full_name} size={20}/>
                    <span className="text-[11.5px] flex-1 truncate">{u.full_name}</span>
                    {userId===u.id && <Icon name="check" size={11} className="text-brand-600"/>}
                  </button>
                ))}
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
};

const ProfileMenu = ({ currentRole, currentUser, setUsers, onLogout, tenantId }) => {
  const [open, setOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const ref = useRef(null);
  const toast = useToast();
  useEffect(() => {
    const close = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);
  const name = currentUser?.full_name || (currentRole==="admin" ? "ธนพร อัศวิน" : currentRole==="viewer" ? "ผู้บริหาร (Demo)" : "ทีมงาน Demo");
  const meta = ROLE_META[currentRole];
  // Resolve actual position names from currentUser's position IDs (set via Employee Mapping)
  const positionLabels = (currentUser?.positions || [])
    .map(pid => POSITIONS.find(p => p.id === pid)?.name)
    .filter(Boolean)
    .join(" · ");
  return (
    <div className="relative" ref={ref}>
      <button onClick={()=>setOpen(v=>!v)} className="flex items-center gap-2 h-8 pl-1 pr-2 rounded-lg hover:bg-ink-50 transition">
        <Avatar name={name} size={26}/>
        <div className="hidden md:block text-left">
          <div className="text-[12px] font-semibold text-ink-900 leading-tight">{name}</div>
          <div className="text-[10.5px] text-ink-500 leading-tight max-w-[180px] truncate">{positionLabels || meta.label}</div>
        </div>
        <Icon name="chevronDown" size={12} className="text-ink-400"/>
      </button>
      {open && (
        <div className="absolute right-0 top-full mt-2 w-64 bg-white border border-ink-200 rounded-xl shadow-xl z-50 p-2 pop">
          <div className="flex items-center gap-2.5 px-2 py-2 border-b border-ink-100 mb-1">
            <Avatar name={name} size={36}/>
            <div className="min-w-0">
              <div className="text-[13px] font-semibold text-ink-900 truncate">{name}</div>
              <div className="text-[11px] text-ink-500 truncate">{currentUser?.email || "user@example.com"}</div>
              {positionLabels && <div className="text-[11px] text-ink-700 mt-0.5 truncate" title={positionLabels}>{positionLabels}</div>}
            </div>
          </div>
          <button onClick={()=>{ setOpen(false); if (currentUser) setEditOpen(true); else toast({kind:"info", msg:"ไม่พบข้อมูลผู้ใช้ปัจจุบัน"}); }} className="w-full flex items-center gap-2 px-2 py-1.5 text-[12px] rounded-md hover:bg-ink-50 text-ink-700"><Icon name="user" size={13}/>โปรไฟล์</button>
          <button onClick={onLogout} className="w-full flex items-center gap-2 px-2 py-1.5 text-[12px] rounded-md hover:bg-rose-50 text-rose-600 mt-1 border-t border-ink-100 pt-2"><Icon name="logout" size={13}/>ออกจากระบบ</button>
        </div>
      )}
      <ProfileEditModal open={editOpen} onClose={()=>setEditOpen(false)} user={currentUser} onSave={async (patch)=>{
        try {
          if (window.apiClient) {
            const fullName = (patch.full_name || "").trim();
            const firstName = fullName.split(" ")[0] || fullName;
            const lastName = fullName.split(" ").slice(1).join(" ") || "";
            // Update user identity (name + phone) via /auth/me — works for both tenant users and super admin
            await window.apiClient.updateMyProfile({
              first_name: firstName,
              last_name: lastName,
              phone: patch.phone || "",
            });
            // Also sync name to tenant_users membership row so list shows new name
            if (currentUser?.membership_id && tenantId) {
              await window.apiClient.updateMember(tenantId, currentUser.membership_id, {
                first_name: firstName,
                last_name: lastName,
              }).catch(() => {});
            }
          }
          setUsers(prev => prev.map(u => u.id === currentUser.id ? { ...u, ...patch } : u));
          toast({ kind: "success", msg: "บันทึกข้อมูลโปรไฟล์เรียบร้อย" });
          setEditOpen(false);
        } catch (e) {
          toast({ kind: "error", msg: e.message || "บันทึกไม่สำเร็จ" });
        }
      }}/>
    </div>
  );
};

// Edit current-user profile modal
const ProfileEditModal = ({ open, onClose, user, onSave }) => {
  const [f, setF] = useState({});
  // Hydrate from API when modal opens — covers phone which isn't in tenant_users list
  useEffect(() => {
    if (!open || !user) return;
    setF({
      full_name: user.full_name || "",
      email: user.email || "",
      phone: user.phone || "",
      employee_code: user.employee_code || "",
    });
    if (window.apiClient) {
      window.apiClient.getMyProfile().then(p => {
        setF(prev => ({ ...prev, phone: p.phone || "" }));
      }).catch(() => {});
    }
  }, [open, user]);
  if (!user) return null;
  const set = (k,v) => setF(p=>({ ...p, [k]:v }));
  const positions = (user.positions || []).map(pid => POSITIONS.find(p=>p.id===pid)?.name).filter(Boolean);
  const submit = () => {
    onSave(f);
  };
  return (
    <Modal open={open} onClose={onClose} title="แก้ไขโปรไฟล์ของฉัน" subtitle="ข้อมูลส่วนตัวและรหัสผ่านของผู้ใช้" width={560}
      footer={<>
        <Button variant="secondary" onClick={onClose}>ยกเลิก</Button>
        <Button onClick={submit} icon="check">บันทึกการแก้ไข</Button>
      </>}>
      <div className="flex items-center gap-3 pb-4 mb-4 border-b border-ink-100">
        <Avatar name={f.full_name} size={56}/>
        <div className="min-w-0 flex-1">
          <div className="text-[15px] font-bold text-ink-900 truncate">{f.full_name}</div>
          <div className="text-[11.5px] text-ink-500 font-mono truncate">{user.employee_code} · {user.email}</div>
          {positions.length > 0 && <div className="text-[11.5px] text-ink-700 mt-0.5 truncate">{positions.join(" · ")}</div>}
        </div>
      </div>

      <div className="grid grid-cols-2 gap-3">
        <Field label="ชื่อ-นามสกุล" required className="col-span-2">
          <Input value={f.full_name||""} onChange={e=>set("full_name", e.target.value)}/>
        </Field>
        <Field label="อีเมล" hint="ไม่สามารถแก้ไขได้ · ติดต่อ Super Admin หากต้องการเปลี่ยน">
          <Input type="email" value={f.email||""} disabled className="font-mono"/>
        </Field>
        <Field label="โทรศัพท์">
          <Input value={f.phone||""} onChange={e=>set("phone", e.target.value)} placeholder="08x-xxx-xxxx"/>
        </Field>
        <Field label="รหัสพนักงาน" hint="แก้ไขได้โดย Admin เท่านั้น">
          <Input value={f.employee_code||""} disabled className="font-mono"/>
        </Field>
        <Field label="ตำแหน่ง" hint="ผูกจาก Employee Mapping — แก้ไขได้โดย Admin">
          <Input value={positions.join(", ") || "—"} disabled/>
        </Field>
      </div>

      <div className="mt-4 pt-4 border-t border-ink-100">
        <div className="flex items-start gap-2 text-[11.5px] text-ink-500">
          <Icon name="info" size={12} className="mt-0.5 shrink-0"/>
          <span>หากต้องการเปลี่ยนรหัสผ่าน · กรุณาออกจากระบบและเปลี่ยนรหัสผ่านที่หน้าเข้าสู่ระบบ</span>
        </div>
      </div>

      <div className="mt-3 text-[11px] text-ink-500 flex items-center gap-1.5">
        <Icon name="info" size={11}/><span>การแก้ไขโปรไฟล์จะถูกบันทึกลง Audit Log ของบริษัท</span>
      </div>
    </Modal>
  );
};

// Notification bell with mock dropdown
const NotificationBell = ({ tasks, taskHistory, subprocesses, users, positions, currentUser, currentRole, onGoMatrix }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const close = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);
  const myPosIds = currentUser?.positions || [];

  // Build today's snapshot from taskHistory (authoritative source) instead of static tasks
  const TODAY = (typeof window !== "undefined" && window.TODAY) || new Date().toISOString().slice(0,10);
  const todaySnapshot = useMemo(() => {
    const out = [];
    subprocesses.forEach(sp => {
      const hist = taskHistory?.[sp.id] || [];
      let match;
      if (sp.frequency === "daily") match = hist.find(h => h.date === TODAY);
      else if (sp.frequency === "weekly") match = hist.find(h => Math.abs((new Date(h.date) - new Date(TODAY))/86400000) <= 6);
      else if (sp.frequency === "monthly" || sp.frequency === "quarterly") match = hist.find(h => h.date.slice(0,7) === TODAY.slice(0,7));
      // ad-hoc — fall back to current snapshot only when nothing in history
      if (!match && sp.frequency === "ad-hoc") {
        const cur = tasks.find(t => t.sub_process_id === sp.id);
        if (cur) match = { date: cur.due_date, status: cur.status, updated: cur.updated, overdue: cur.overdue };
      }
      if (match) out.push({ sp, ...match });
    });
    return out;
  }, [subprocesses, taskHistory, tasks]);

  // Build a list of relevant notifications for the current user from today's snapshot
  const notes = useMemo(() => {
    const list = [];
    todaySnapshot.forEach(({ sp, status, date, overdue }) => {
      const isR = myPosIds.includes(sp.R);
      const isA = myPosIds.includes(sp.A);
      if (status === "A" && isA) list.push({ k:"approve", sp, msg:`รอตรวจสอบ: ${sp.name}`, sub:`ครบกำหนด ${date}`, color:"violet", icon:"checkCircle" });
      if (status === "C" && isR) list.push({ k:"correct", sp, msg:`มี Comment ให้แก้ไข: ${sp.name}`, sub:`ครบกำหนด ${date}`, color:"amber", icon:"message" });
      if (status === "P" && isR) list.push({ k:"prep", sp, msg:`รอจัดทำ: ${sp.name}`, sub:`ครบกำหนด ${date}`, color:"blue", icon:"arrowUp" });
      if (overdue && status !== "S" && (isR || isA)) list.push({ k:"overdue", sp, msg:`⚠ เลยกำหนด: ${sp.name}`, sub:`ครบกำหนด ${date}`, color:"rose", icon:"alert" });
    });
    return list.slice(0, 12);
  }, [todaySnapshot, myPosIds]);

  // Notification bell shows ONLY items where the current user is responsible (R) or accountable (A).
  // If the user has no position mapped (e.g. brand-new admin), there are no personal tasks.
  const finalNotes = notes;

  return (
    <div className="relative" ref={ref}>
      <button onClick={()=>setOpen(v=>!v)} className="relative w-8 h-8 rounded-lg border border-ink-200 bg-white hover:bg-ink-50 flex items-center justify-center text-ink-600">
        <Icon name="bell" size={14}/>
        {finalNotes.length > 0 && <span className="absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-rose-500"/>}
      </button>
      {open && (
        <div className="absolute right-0 top-full mt-2 w-[340px] bg-white border border-ink-200 rounded-xl shadow-xl z-50 pop overflow-hidden">
          <div className="px-4 py-3 border-b border-ink-100 flex items-center justify-between">
            <div className="text-[13px] font-semibold text-ink-900">การแจ้งเตือน</div>
            <Badge color="rose">{finalNotes.length}</Badge>
          </div>
          <div className="max-h-[360px] overflow-y-auto thin-scroll">
            {finalNotes.length === 0 ? (
              <div className="px-6 py-8 text-center">
                <Icon name="checkCircle" size={24} className="text-emerald-500 mx-auto mb-1"/>
                <div className="text-[12.5px] text-ink-700 font-semibold">ไม่มีงานค้าง</div>
                <div className="text-[11px] text-ink-500">
                  {myPosIds.length === 0
                    ? "บัญชีนี้ยังไม่ได้ผูกกับตำแหน่งในองค์กร · ขอให้ Company Admin ผูกตำแหน่งจากหน้า Employee Mapping"
                    : "ไม่มีงานที่ต้องดำเนินการของคุณในขณะนี้"}
                </div>
              </div>
            ) : (
              <div className="divide-y divide-ink-100">
                {finalNotes.map((n,i) => (
                  <button key={i} onClick={()=>{ setOpen(false); onGoMatrix(); }}
                    className="w-full text-left px-4 py-2.5 hover:bg-ink-50 flex items-start gap-2.5 transition">
                    <Icon name={n.icon} size={14} className={
                      n.color==="violet"?"text-violet-600":
                      n.color==="amber"?"text-amber-600":
                      n.color==="blue"?"text-blue-600":
                      n.color==="rose"?"text-rose-600":"text-ink-500"}/>
                    <div className="flex-1 min-w-0">
                      <div className="text-[12.5px] font-medium text-ink-900 truncate">{n.msg}</div>
                      <div className="text-[10.5px] text-ink-500 truncate">{n.sub}</div>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
          <div className="px-4 py-2 border-t border-ink-100 bg-ink-50/60 text-[11px] text-ink-500 flex items-center justify-between">
            <span>ระบบแจ้งอัตโนมัติตามสิทธิ์ R/A ของคุณ</span>
            <button onClick={()=>{ setOpen(false); onGoMatrix(); }} className="text-brand-600 hover:underline">เปิด Matrix</button>
          </div>
        </div>
      )}
    </div>
  );
};

// ----- User Management placeholder page (uses real users list) -----
const UserManagementPage = ({ users, setUsers, tenant, canEdit }) => {
  const [q, setQ] = useState("");
  const [editFor, setEditFor] = useState(null); // user being edited
  const [deleteFor, setDeleteFor] = useState(null);
  const [adding, setAdding] = useState(false);
  const [busy, setBusy] = useState(false);
  const toast = useToast();
  const filtered = users.filter(u => !q || (u.full_name+u.email+(u.employee_code||"")).toLowerCase().includes(q.toLowerCase()));

  // Users are loaded centrally in ClientWorkspace on tenant change — no duplicate fetch here.

  const saveUser = async (u) => {
    // Editing existing user
    if (u.id) {
      // If it's an API-backed user with membership_id, sync to API
      if (u.from_api && u.membership_id && window.apiClient) {
        try {
          const fullName = (u.full_name || "").trim();
          const firstName = fullName.split(' ')[0] || fullName;
          const lastName = fullName.split(' ').slice(1).join(' ') || '';
          await window.apiClient.updateMember(tenant.id, u.membership_id, {
            role: u.system_role,
            status: u.status,
            employee_code: u.employee_code || "",
            first_name: firstName,
            last_name: lastName,
          });
        } catch (e) {
          toast({ kind: "error", msg: e.message || "บันทึกการแก้ไขล้มเหลว" });
          return;
        }
      }
      setUsers(prev => prev.map(x => x.id === u.id ? u : x));
      toast({ kind:"success", msg:"บันทึกข้อมูลผู้ใช้แล้ว" });
      setEditFor(null); setAdding(false);
      return;
    }

    // Adding a new user — call API
    if (!window.apiClient) {
      // No API → local-only fallback
      const newU = { ...u, id:"u"+Date.now(), positions:[], status:u.status||"active", system_role:u.system_role||"employee" };
      setUsers(prev => [...prev, newU]);
      toast({ kind:"success", msg:`เพิ่ม ${newU.full_name} แล้ว (local เท่านั้น)` });
      setEditFor(null); setAdding(false);
      return;
    }

    setBusy(true);
    try {
      const res = await window.apiClient.addMember(tenant.id, {
        email: u.email,
        full_name: u.full_name,
        role: u.system_role || "employee",
        employee_code: u.employee_code || "",
        password: u.password || undefined, // optional — only when creating new user identity
      });
      const newU = {
        id: res.user_id,
        membership_id: res.membership_id,
        api_user_id: res.user_id,
        full_name: u.full_name,
        email: u.email,
        employee_code: u.employee_code || "",
        system_role: u.system_role || "employee",
        status: "active",
        positions: [],
        from_api: true,
      };
      setUsers(prev => [newU, ...prev]);
      toast({
        kind: "success",
        msg: res.created_user
          ? `สร้างบัญชีใหม่ + เพิ่ม ${u.full_name} เป็นพนักงานของบริษัท`
          : `เพิ่ม ${u.full_name} (บัญชีที่มีอยู่) เป็นพนักงานของบริษัท`,
      });
      setEditFor(null); setAdding(false);
    } catch (e) {
      if (e.status === 404) {
        toast({
          kind: "error",
          msg: `${u.email} ยังไม่มีบัญชีในระบบ · กรุณาให้กรอกรหัสผ่านเริ่มต้นเพื่อสร้างบัญชีพร้อมเพิ่มเป็นสมาชิก`,
        });
      } else if (e.status === 409) {
        toast({ kind: "error", msg: "ผู้ใช้นี้เป็นสมาชิกของบริษัทอยู่แล้ว" });
      } else {
        toast({ kind: "error", msg: e.message || "เพิ่มผู้ใช้ไม่สำเร็จ" });
      }
    } finally {
      setBusy(false);
    }
  };
  const exportUsers = () => {
    downloadCsv(`${tenant.tenant_code}_users.csv`,
      ["Employee Code","Full Name","Email","System Role","Status","Positions"],
      users.map(u => [u.employee_code, u.full_name, u.email, u.system_role, u.status,
        u.positions.map(pid => POSITIONS.find(p=>p.id===pid)?.name).filter(Boolean).join(" / ")])
    );
    toast({ kind:"success", msg:"ส่งออกไฟล์ผู้ใช้เรียบร้อย" });
  };

  return (
    <div className="p-6">
      <PageHeader title="User Management" subtitle={`ผู้ใช้งานในบริษัท ${tenant.company_short}`}
        right={<>
          <Button icon="download" variant="secondary" onClick={exportUsers}>Export CSV</Button>
          {canEdit ? <Button icon="plus" onClick={()=>setAdding(true)}>เพิ่มผู้ใช้ใหม่</Button> : <Badge color="slate" icon="eye">อ่านอย่างเดียว</Badge>}
        </>}/>

      {!canEdit && (
        <div className="mb-4 px-4 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-700 text-[12.5px] flex items-center gap-2.5">
          <Icon name="shield" size={14} className="text-slate-500"/>
          <span>คุณกำลังดูรายชื่อผู้ใช้แบบ <strong>อ่านอย่างเดียว</strong> · ติดต่อ Company Admin เพื่อขอสิทธิ์จัดการผู้ใช้</span>
        </div>
      )}
      <div className="bg-white rounded-2xl border border-ink-100 overflow-hidden">
        <div className="px-4 py-3 border-b border-ink-100 flex items-center gap-2">
          <div className="relative flex-1 max-w-md">
            <Icon name="search" size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-400"/>
            <input value={q} onChange={e=>setQ(e.target.value)} placeholder="ค้นหาผู้ใช้…"
              className="w-full h-9 pl-9 pr-3 text-[13px] border border-ink-200 rounded-lg bg-white focus:border-brand-500 ring-focus"/>
          </div>
          <div className="text-[11.5px] text-ink-500">{filtered.length} รายการ</div>
        </div>
        <table className="w-full text-[12.5px]">
          <thead>
            <tr className="bg-ink-50/60 text-ink-500 text-[11px] uppercase tracking-wider">
              {["ผู้ใช้","Employee Code","อีเมล","ตำแหน่ง","System Role","สถานะ","Action"].map(h => (
                <th key={h} className="text-left font-semibold px-3 py-2.5 border-b border-ink-100">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.map(u => {
              const positions = u.positions.map(pid => POSITIONS.find(p=>p.id===pid)?.name).filter(Boolean);
              return (
                <tr key={u.id} className="border-b border-ink-100 hover:bg-ink-50/40 last:border-0">
                  <td className="px-3 py-3"><div className="flex items-center gap-2"><Avatar name={u.full_name} size={28}/><span className="font-medium text-ink-900">{u.full_name}</span></div></td>
                  <td className="px-3 py-3 font-mono text-ink-700">{u.employee_code}</td>
                  <td className="px-3 py-3 font-mono text-ink-600">{u.email}</td>
                  <td className="px-3 py-3 text-ink-700">{positions.length ? positions.join(", ") : <span className="text-ink-400 italic">ยังไม่ผูกตำแหน่ง</span>}</td>
                  <td className="px-3 py-3"><Badge color={u.system_role==="admin"?"indigo":u.system_role==="manager"?"violet":u.system_role==="viewer"?"slate":"blue"}>{u.system_role}</Badge></td>
                  <td className="px-3 py-3"><Badge color={u.status==="active"?"emerald":"slate"}>{u.status}</Badge></td>
                  <td className="px-3 py-3">
                    <div className="flex items-center gap-1">
                      {canEdit ? <>
                        <Tip tip="แก้ไข"><button onClick={()=>setEditFor(u)} className="w-7 h-7 rounded-md text-ink-500 hover:bg-ink-100"><Icon name="edit" size={12}/></button></Tip>
                        <Tip tip="ลบ"><button onClick={()=>setDeleteFor(u)} className="w-7 h-7 rounded-md text-rose-500 hover:bg-rose-50"><Icon name="trash" size={12}/></button></Tip>
                      </> : <Tip tip="ไม่มีสิทธิ์ — ติดต่อ Company Admin"><span className="text-[10.5px] text-ink-400 italic px-2">view only</span></Tip>}
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Edit / Add modal */}
      <UserEditModal open={!!editFor || adding} user={editFor} onClose={()=>{ setEditFor(null); setAdding(false); }} onSave={saveUser}/>
      {/* Delete with reason */}
      <ReasonModal open={!!deleteFor} onClose={()=>setDeleteFor(null)}
        onConfirm={async (reason) => {
          const target = deleteFor;
          if (target.from_api && target.membership_id && window.apiClient) {
            try {
              await window.apiClient.removeMember(tenant.id, target.membership_id);
            } catch (e) {
              toast({ kind: "error", msg: e.message || "ลบไม่สำเร็จ" });
              return;
            }
          }
          setUsers(prev => prev.filter(x => x.id !== target.id));
          toast({ kind: "success", msg: `ลบ ${target.full_name} แล้ว · บันทึก Audit Log` });
          setDeleteFor(null);
        }}
        title={`ลบผู้ใช้ ${deleteFor?.full_name}`} subtitle="ผู้ใช้จะถูกถอนออกจากบริษัทนี้ (account identity ยังอยู่)"
        confirmLabel="ลบผู้ใช้"/>
    </div>
  );
};

const UserEditModal = ({ open, user, onClose, onSave }) => {
  const [f, setF] = useState({ full_name:"", email:"", employee_code:"", phone:"", system_role:"employee", status:"active" });
  useEffect(() => {
    if (open) setF(user ? { ...user } : { full_name:"", email:"", employee_code:"", phone:"", system_role:"employee", status:"active" });
  }, [open, user]);
  const set = (k,v) => setF(p => ({ ...p, [k]:v }));
  const valid = f.full_name && f.email && f.employee_code;
  return (
    <Modal open={open} onClose={onClose} title={user ? "แก้ไขผู้ใช้" : "เพิ่มผู้ใช้ใหม่"} subtitle={user?.email}
      width={560}
      footer={<>
        <Button variant="secondary" onClick={onClose}>ยกเลิก</Button>
        <Button disabled={!valid} onClick={()=>onSave(f)} icon="check">บันทึก</Button>
      </>}
    >
      <div className="grid grid-cols-2 gap-3">
        <Field label="ชื่อ-นามสกุล" required><Input value={f.full_name} onChange={e=>set("full_name", e.target.value)} placeholder="เช่น สมชาย ใจดี"/></Field>
        <Field label="รหัสพนักงาน" required><Input value={f.employee_code} onChange={e=>set("employee_code", e.target.value.toUpperCase())} className="font-mono uppercase"/></Field>
        <Field label="อีเมล" required className="col-span-2"><Input type="email" value={f.email} onChange={e=>set("email", e.target.value)}/></Field>
        <Field label="โทรศัพท์"><Input value={f.phone||""} onChange={e=>set("phone", e.target.value)} placeholder="08x-xxx-xxxx"/></Field>
        <Field label="System Role">
          <Select value={f.system_role} onChange={e=>set("system_role", e.target.value)}>
            <option value="admin">Admin</option>
            <option value="manager">Manager</option>
            <option value="employee">Employee</option>
            <option value="viewer">Viewer</option>
          </Select>
        </Field>
        <Field label="สถานะ" className="col-span-2">
          <Select value={f.status} onChange={e=>set("status", e.target.value)}>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
          </Select>
        </Field>
      </div>
    </Modal>
  );
};

const SettingsPage = ({ tenant }) => {
  const toast = useToast();
  return (
  <div className="p-6 max-w-3xl">
    <PageHeader title="Settings" subtitle="ตั้งค่าทั่วไปของบริษัท"
      right={<Button icon="check" onClick={()=>toast({kind:"success", msg:"บันทึกการตั้งค่าเรียบร้อย"})}>บันทึกการตั้งค่า</Button>}/>
    <div className="bg-white rounded-2xl border border-ink-100 p-5 space-y-4">
      {[
        { t:"ชื่อบริษัท", v:tenant.company_name },
        { t:"Tenant Code", v:<span className="font-mono">{tenant.tenant_code}</span> },
        { t:"Plan", v:`${tenant.plan} · ${tenant.seats} seats` },
        { t:"การแยกข้อมูล", v:<span className="font-mono">{tenant.database_type}</span> },
        { t:"Database / Schema", v:<span className="font-mono">{tenant.database_name} / {tenant.schema_name}</span> },
        { t:"วันสิ้นสุดบริการ", v:<span className="font-mono">{tenant.service_expiry_date}</span> },
        { t:"Time zone", v:"Asia/Bangkok (GMT+7)" },
        { t:"Default language", v:"ภาษาไทย" },
      ].map((c,i) => (
        <div key={i} className="flex items-center justify-between gap-4 pb-3 border-b border-ink-100 last:border-0 last:pb-0">
          <div className="text-[13px] font-medium text-ink-700">{c.t}</div>
          <div className="text-[13px] text-ink-900 text-right">{c.v}</div>
        </div>
      ))}
    </div>
  </div>
  );
};

Object.assign(window, { ClientWorkspace, ROLE_META });
