import { For, Show, createEffect, createMemo, createSignal, onMount } from "solid-js";
import { useNavigate, useSearchParams } from "@solidjs/router";
import type { CrudRecord } from "~/lib/admin/types";

const API = "";

type EmployeeRecord = CrudRecord & {
  firstName?: string;
  lastName?: string;
  employeeId?: string;
  email: string;
  phone?: string;
  department?: string;
  departmentId?: string;
  designation?: string;
  designationId?: string;
  internalRole?: string;
  joiningDate?: string;
  employmentType?: string;
  gender?: string;
  address?: string;
  city?: string;
  state?: string;
  country?: string;
  zipCode?: string;
  reportingManager?: string;
  workLocation?: string;
  employeeCategory?: string;
  shiftType?: string;
  status: "ACTIVE" | "INACTIVE" | "ON_LEAVE" | "PROBATION" | "SUSPENDED";
};
type RoleOption = { id: string; name: string; key?: string };
type DepartmentOption = { id: string; name: string };
type DesignationOption = { id: string; name: string };

function normalizeEmployee(item: any, idx: number): EmployeeRecord {
  const status = String(item.status ?? "").toUpperCase();
  const firstName = String(item.first_name ?? item.firstName ?? "");
  const lastName = String(item.last_name ?? item.lastName ?? "");
  return {
    id: String(item.id ?? `emp-${idx + 1}`),
    firstName,
    lastName,
    name: `${firstName} ${lastName}`.trim(),
    employeeId: String(item.employeeId ?? item.employee_id ?? item.employee_code ?? ""),
    email: String(item.email ?? ""),
    phone: String(item.phone ?? ""),
    department: String(item.department ?? item.department_name ?? ""),
    departmentId: String(item.department_id ?? ""),
    designation: String(item.designation ?? item.designation_name ?? ""),
    designationId: String(item.designation_id ?? ""),
    internalRole: String(item.internalRole ?? item.role_name ?? ""),
    joiningDate: String(item.joiningDate ?? item.joining_date ?? ""),
    employmentType: String(item.employmentType ?? item.employment_type ?? "FULL_TIME"),
    status: (["ACTIVE", "INACTIVE", "ON_LEAVE", "PROBATION", "SUSPENDED"].includes(status)
      ? status
      : "ACTIVE") as any,
    updatedAt: String(item.updatedAt ?? item.updated_at ?? ""),
  };
}

function parseEmployeeCodeNumber(code: string): number | null {
  const normalized = String(code || "")
    .trim()
    .toUpperCase();
  if (!normalized) return null;
  const explicit = normalized.match(/^EMP[-_]?0*(\d+)$/);
  if (explicit) return Number(explicit[1]);
  const trailing = normalized.match(/(\d+)$/);
  if (trailing) return Number(trailing[1]);
  return null;
}

function formatEmployeeCode(value: number): string {
  return `EMP-${String(Math.max(1, value)).padStart(4, "0")}`;
}

function StatusBadge(props: { status: string }) {
  const getColors = () => {
    switch (props.status) {
      case "ACTIVE":
        return { border: "#B7E4C7", bg: "#DEF7E8", text: "#0B8A4A", dot: "#0B8A4A" };
      case "PROBATION":
        return { border: "#F6D78F", bg: "#FFF3D6", text: "#B7791F", dot: "#B7791F" };
      case "ON_LEAVE":
        return { border: "#FDE68A", bg: "#FEF3C7", text: "#D97706", dot: "#D97706" };
      case "SUSPENDED":
        return { border: "#FECACA", bg: "#FEF2F2", text: "#DC2626", dot: "#DC2626" };
      default:
        return { border: "#D1D5DB", bg: "#F3F4F6", text: "#4B5563", dot: "#9CA3AF" };
    }
  };
  const colors = getColors();
  const label = props.status
    .split("_")
    .map((w) => w.charAt(0) + w.slice(1).toLowerCase())
    .join(" ");

  return (
    <span
      style={`display:inline-flex;align-items:center;border-radius:9999px;border:1px solid ${colors.border};background:${colors.bg};color:${colors.text};padding:2px 10px;font-size:12px;font-weight:500`}
    >
      <span
        style={`display:inline-block;width:6px;height:6px;border-radius:50%;background:${colors.dot};margin-right:5px;flex-shrink:0`}
      />
      {label}
    </span>
  );
}

function FormInput(props: {
  label: string;
  required?: boolean;
  value: string;
  onInput: (v: string) => void;
  placeholder?: string;
  type?: string;
}) {
  return (
    <label style="display:block">
      <span style="font-size:13px;font-weight:600;color:#374151">
        {props.label}
        {props.required && <span style="margin-left:2px;color:#FF5E13">*</span>}
      </span>
      <input
        type={props.type ?? "text"}
        value={props.value}
        onInput={(e) => props.onInput(e.currentTarget.value)}
        placeholder={props.placeholder}
        style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;color:#111827;outline:none;box-sizing:border-box"
      />
    </label>
  );
}

export default function EmployeeManagementPage() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [view, setView] = createSignal<"list" | "form" | "detail">("list");
  const [listTab, setListTab] = createSignal<"all" | "create" | "view">("all");
  const [formTab, setFormTab] = createSignal<"basic" | "work" | "access">("basic");
  const [detailTab, setDetailTab] = createSignal<"profile" | "activity" | "access">("profile");

  const [search, setSearch] = createSignal("");
  const [rows, setRows] = createSignal<EmployeeRecord[]>([]);
  const [openMenuId, setOpenMenuId] = createSignal<string | null>(null);
  const [editingId, setEditingId] = createSignal<string | null>(null);
  const [viewingEmp, setViewingEmp] = createSignal<EmployeeRecord | null>(null);
  const [statusFilter, setStatusFilter] = createSignal<"all" | EmployeeRecord["status"]>("all");
  const [sortBy, setSortBy] = createSignal<"name_asc" | "name_desc" | "joined_desc" | "joined_asc">(
    "joined_desc"
  );
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);

  // Form Signals
  const [firstName, setFirstName] = createSignal("");
  const [lastName, setLastName] = createSignal("");
  const [empId, setEmpId] = createSignal("");
  const [email, setEmail] = createSignal("");
  const [phone, setPhone] = createSignal("");
  const [dept, setDept] = createSignal("");
  const [desig, setDesig] = createSignal("");
  const [role, setRole] = createSignal("");
  const [status, setStatus] = createSignal<EmployeeRecord["status"]>("ACTIVE");
  const [employmentType, setEmploymentType] = createSignal("FULL_TIME");
  const [joiningDate, setJoiningDate] = createSignal("");
  const [createLoginCreds, setCreateLoginCreds] = createSignal(true);
  const [loginPassword, setLoginPassword] = createSignal("");
  const [confirmLoginPassword, setConfirmLoginPassword] = createSignal("");
  const [showLoginPassword, setShowLoginPassword] = createSignal(false);
  const [showConfirmPassword, setShowConfirmPassword] = createSignal(false);

  const [isLoading, setIsLoading] = createSignal(false);
  const [isSaving, setIsSaving] = createSignal(false);
  const [isGeneratingEmployeeCode, setIsGeneratingEmployeeCode] = createSignal(false);
  const [error, setError] = createSignal("");
  const [rolesOptions, setRolesOptions] = createSignal<RoleOption[]>([]);
  const [departmentOptions, setDepartmentOptions] = createSignal<DepartmentOption[]>([]);
  const [designationOptions, setDesignationOptions] = createSignal<DesignationOption[]>([]);

  const load = async () => {
    setIsLoading(true);
    setError("");
    try {
      const accessToken =
        typeof sessionStorage !== "undefined"
          ? sessionStorage.getItem("nxtgauge_admin_access_token") || ""
          : "";
      const params = new URLSearchParams();
      const q = search().trim();
      if (q) params.set("q", q);
      if (statusFilter() !== "all") params.set("status", statusFilter() as string);
      params.set("sort", sortBy());
      params.set("page", "1");
      params.set("per_page", "100");
      const res = await fetch(`${API}/api/admin/employees?${params.toString()}`, {
        headers: {
          Accept: "application/json",
          ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
        },
        credentials: "include",
      });
      if (!res.ok) throw new Error();
      const data = await res.json();
      const list = Array.isArray(data) ? data : (data.employees ?? data.users ?? []);
      setRows(
        (Array.isArray(list) ? list : []).map(normalizeEmployee).map((r) => {
          const dept = departmentOptions().find((d) => d.id === r.departmentId);
          const desig = designationOptions().find((d) => d.id === r.designationId);
          return {
            ...r,
            department: dept?.name ?? r.department,
            designation: desig?.name ?? r.designation,
          };
        })
      );
    } catch (e: any) {
      setRows([]);
      setError(e?.message || "Could not reach employees API.");
    } finally {
      setIsLoading(false);
    }
  };

  const loadMeta = async () => {
    try {
      const accessToken =
        typeof sessionStorage !== "undefined"
          ? (sessionStorage.getItem("nxtgauge_admin_access_token") || "").trim()
          : "";
      const common = {
        headers: {
          Accept: "application/json",
          ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
        },
        credentials: "include" as const,
      };
      const [rolesRes, deptRes, desigRes] = await Promise.all([
        fetch(`${API}/api/admin/roles?audience=INTERNAL&per_page=100`, common).catch(() => null),
        fetch(`${API}/api/admin/departments?per_page=100`, common).catch(() => null),
        fetch(`${API}/api/admin/designations?per_page=100`, common).catch(() => null),
      ]);
      const rolesJson = await rolesRes?.json().catch(() => null);
      const deptJson = await deptRes?.json().catch(() => null);
      const desigJson = await desigRes?.json().catch(() => null);
      const roles = Array.isArray(rolesJson) ? rolesJson : (rolesJson?.roles ?? []);
      const depts = Array.isArray(deptJson) ? deptJson : (deptJson?.departments ?? []);
      const desigs = Array.isArray(desigJson) ? desigJson : (desigJson?.designations ?? []);
      setRolesOptions(
        (Array.isArray(roles) ? roles : [])
          .map((r: any) => ({
            id: String(r.id || ""),
            name: String(r.name || ""),
            key: r.key ? String(r.key) : undefined,
          }))
          .filter((r: RoleOption) => r.id && r.name)
      );
      setDepartmentOptions(
        (Array.isArray(depts) ? depts : [])
          .map((d: any) => ({ id: String(d.id || ""), name: String(d.name || "") }))
          .filter((d: DepartmentOption) => d.id && d.name)
      );
      setDesignationOptions(
        (Array.isArray(desigs) ? desigs : [])
          .map((d: any) => ({ id: String(d.id || ""), name: String(d.name || "") }))
          .filter((d: DesignationOption) => d.id && d.name)
      );
      setRows((prev) =>
        prev.map((r) => {
          const dept = departmentOptions().find((d) => d.id === r.departmentId);
          const desig = designationOptions().find((d) => d.id === r.designationId);
          return {
            ...r,
            department: dept?.name ?? r.department,
            designation: desig?.name ?? r.designation,
          };
        })
      );
    } catch {
      // keep dropdowns empty; user can still view list
    }
  };

  onMount(() => {
    void load();
    void loadMeta();
  });

  createEffect(() => {
    const depts = departmentOptions();
    const desigs = designationOptions();
    if (depts.length === 0 && desigs.length === 0) return;
    setRows((prev) =>
      prev.map((r) => {
        const dept = depts.find((d) => d.id === r.departmentId);
        const desig = desigs.find((d) => d.id === r.designationId);
        return {
          ...r,
          department: dept?.name ?? r.department,
          designation: desig?.name ?? r.designation,
        };
      })
    );
  });

  const fetchNextEmployeeCode = async (): Promise<string> => {
    const accessToken =
      typeof sessionStorage !== "undefined"
        ? (sessionStorage.getItem("nxtgauge_admin_access_token") || "").trim()
        : "";
    let page = 1;
    let maxNum = 0;
    while (page <= 100) {
      const res = await fetch(
        `${API}/api/admin/employees?page=${page}&per_page=100&sort=joined_desc`,
        {
          headers: {
            Accept: "application/json",
            ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
          },
          credentials: "include",
        }
      ).catch(() => null);
      if (!res?.ok) break;
      const payload = await res.json().catch(() => null);
      const list: any[] = Array.isArray(payload)
        ? payload
        : Array.isArray(payload?.employees)
          ? payload.employees
          : Array.isArray(payload?.items)
            ? payload.items
            : [];
      if (!Array.isArray(list) || list.length === 0) break;
      for (const item of list) {
        const raw = String(item?.employee_id ?? item?.employeeId ?? item?.employee_code ?? "");
        const parsed = parseEmployeeCodeNumber(raw);
        if (parsed && parsed > maxNum) maxNum = parsed;
      }
      if (list.length < 100) break;
      page += 1;
    }
    return formatEmployeeCode(maxNum + 1);
  };

  const filteredRows = createMemo(() => {
    let list = rows();
    const f = statusFilter();
    if (f !== "all") list = list.filter((r) => r.status === f);
    const q = search().trim().toLowerCase();
    if (q) {
      list = list.filter(
        (r) =>
          r.name.toLowerCase().includes(q) ||
          r.email.toLowerCase().includes(q) ||
          String(r.employeeId || "")
            .toLowerCase()
            .includes(q) ||
          String(r.department || "")
            .toLowerCase()
            .includes(q) ||
          String(r.designation || "")
            .toLowerCase()
            .includes(q)
      );
    }
    const sorted = [...list];
    const mode = sortBy();
    const jd = (v?: string) => Date.parse(String(v || "")) || 0;
    sorted.sort((a, b) => {
      if (mode === "name_asc") return a.name.localeCompare(b.name);
      if (mode === "name_desc") return b.name.localeCompare(a.name);
      if (mode === "joined_asc") return jd(a.joiningDate) - jd(b.joiningDate);
      return jd(b.joiningDate) - jd(a.joiningDate);
    });
    return sorted;
  });

  const resetForm = () => {
    setEditingId(null);
    setFirstName("");
    setLastName("");
    setEmpId("");
    setEmail("");
    setPhone("");
    setDept("");
    setDesig("");
    setRole("");
    setStatus("ACTIVE");
    setEmploymentType("FULL_TIME");
    setJoiningDate("");
    setFormTab("basic");
    setError("");
    setCreateLoginCreds(true);
    setLoginPassword("");
    setConfirmLoginPassword("");
  };

  const openCreate = () => {
    resetForm();
    setView("form");
  };

  const backToEmployeesList = async () => {
    setView("list");
    setListTab("all");
    setOpenMenuId(null);
    setSortMenuOpen(false);
    setFilterMenuOpen(false);
    await load();
  };

  const openEdit = (row: EmployeeRecord) => {
    const roleMatch = rolesOptions().find(
      (r) =>
        r.name.trim().toLowerCase() ===
        String(row.internalRole || "")
          .trim()
          .toLowerCase()
    );
    const deptMatch = departmentOptions().find(
      (d) =>
        d.name.trim().toLowerCase() ===
        String(row.department || "")
          .trim()
          .toLowerCase()
    );
    const desigMatch = designationOptions().find(
      (d) =>
        d.name.trim().toLowerCase() ===
        String(row.designation || "")
          .trim()
          .toLowerCase()
    );
    const nameParts = (row.name || "").split(" ");
    setEditingId(row.id);
    setFirstName(nameParts[0] || "");
    setLastName(nameParts.slice(1).join(" ") || "");
    setEmpId(row.employeeId || "");
    setEmail(row.email);
    setPhone(row.phone || "");
    setDept(deptMatch?.id || "");
    setDesig(desigMatch?.id || "");
    setRole(roleMatch?.id || "");
    setStatus(row.status);
    setEmploymentType(row.employmentType || "FULL_TIME");
    setJoiningDate(row.joiningDate || "");
    setFormTab("basic");
    setView("form");
    setOpenMenuId(null);
  };

  const openDetail = (row: EmployeeRecord) => {
    setViewingEmp(row);
    setDetailTab("profile");
    setView("detail");
    setListTab("view");
    setOpenMenuId(null);
  };

  const save = async () => {
    if (!editingId() && (!firstName().trim() || !lastName().trim() || !email().trim())) {
      setError("First name, last name, and email are required.");
      return;
    }
    setIsSaving(true);
    setError("");
    try {
      const accessToken =
        typeof sessionStorage !== "undefined"
          ? (sessionStorage.getItem("nxtgauge_admin_access_token") || "").trim()
          : "";
      const isEdit = Boolean(editingId());
      if (!isEdit) {
        const checkRes = await fetch(
          `${API}/api/admin/employees?q=${encodeURIComponent(email().trim())}`,
          {
            headers: {
              Accept: "application/json",
              ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
            },
            credentials: "include",
          }
        );
        if (checkRes.ok) {
          const checkData = await checkRes.json().catch(() => null);
          const existingEmployees = Array.isArray(checkData)
            ? checkData
            : (checkData?.employees ?? []);
          const emailExists = existingEmployees.some(
            (e: any) => String(e.email || "").toLowerCase() === email().trim().toLowerCase()
          );
          if (emailExists) {
            setError("An employee with this email already exists.");
            setIsSaving(false);
            return;
          }
        }
      }
      let employeeCodeForCreate = empId().trim();
      if (!isEdit && !employeeCodeForCreate) {
        employeeCodeForCreate = await fetchNextEmployeeCode();
        setEmpId(employeeCodeForCreate);
      }
      const body: Record<string, unknown> = {};
      if (isEdit && empId().trim()) body.employee_code = empId().trim();
      if (!isEdit && employeeCodeForCreate) body.employee_code = employeeCodeForCreate;
      if (dept().trim()) body.department_id = dept().trim();
      if (desig().trim()) body.designation_id = desig().trim();
      if (role().trim()) body.role_code = role().trim();
      if (firstName().trim()) body.first_name = firstName().trim();
      if (lastName().trim()) body.last_name = lastName().trim();
      if (email().trim()) body.email = email().trim().toLowerCase();
      if (phone().trim()) body.phone = phone().trim();
      if (!isEdit && createLoginCreds()) {
        if (loginPassword().trim().length < 8) {
          throw new Error("Password must be at least 8 characters.");
        }
        if (loginPassword().trim() !== confirmLoginPassword().trim()) {
          throw new Error("Password and confirm password do not match.");
        }
        body.password = loginPassword().trim();
      }
      const endpoint = isEdit
        ? `${API}/api/admin/employees/${editingId()}`
        : `${API}/api/admin/employees/provision`;
      const res = await fetch(endpoint, {
        method: isEdit ? "PATCH" : "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
        },
        credentials: "include",
        body: JSON.stringify(body),
      });
      const raw = await res.text();
      let message = "";
      if (raw) {
        try {
          const parsed = JSON.parse(raw) as { message?: string; error?: string };
          message = parsed?.message || parsed?.error || "";
        } catch {
          message = raw;
        }
      }
      if (!res.ok) throw new Error(message || `Request failed (${res.status})`);
      setView("list");
      await load();
    } catch (e: any) {
      setError(e?.message || "Failed to save employee");
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div class="w-full space-y-6 pb-8">
      {/* Page header */}
      <div style="margin-bottom: 1.5rem">
        <h1 class="text-[28px] font-bold leading-tight text-[#111827]">Employee Management</h1>
        <p class="mt-1 text-[14px] text-[#6B7280]">
          Manage all internal employees and their organizational roles
        </p>
      </div>

      {/* ── LIST VIEW ── */}
      <Show when={view() === "list"}>
        {/* Tabs */}
        <div style="margin-top:24px;display:flex;align-items:center;gap:24px;border-bottom:1px solid #E5E7EB">
          <For
            each={[
              {
                key: "all",
                label: "All Employees",
                action: () => {
                  void backToEmployeesList();
                },
              },
              {
                key: "create",
                label: "Create Employee",
                action: () => {
                  setListTab("create");
                  void openCreate();
                },
              },
              {
                key: "view",
                label: "View Employee",
                action: () => {
                  setListTab("view");
                  if (viewingEmp()) setView("detail");
                },
              },
            ] as const}
          >
            {(tab) => (
              <button
                type="button"
                onClick={tab.action}
                style={`padding-bottom:12px;font-size:14px;font-weight:500;background:none;border:none;cursor:pointer;${listTab() === tab.key ? "color:#FF5E13;border-bottom:2px solid #FF5E13;margin-bottom:-1px" : "color:#6B7280"}`}
              >
                {tab.label}
              </button>
            )}
          </For>
        </div>

        <div style="margin-top:1.5rem;margin-left:-24px;margin-right:-24px;border-radius:0;border-left:none;border-right:none;overflow:hidden;border-top:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
          {/* Filter bar */}
          <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6">
            <input
              value={search()}
              onInput={(e) => setSearch(e.currentTarget.value)}
              placeholder="Search employees..."
              style="height:34px;flex:1;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none"
            />
            <div style="position:relative">
              <button
                type="button"
                onClick={() => {
                  setSortMenuOpen((v) => !v);
                  setFilterMenuOpen(false);
                }}
                style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer"
              >
                <svg
                  width="13"
                  height="13"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <path d="M7 4v13" />
                  <path d="m3 13 4 4 4-4" />
                  <path d="M17 20V7" />
                  <path d="m21 11-4-4-4 4" />
                </svg>
                Sort
              </button>
              <Show when={sortMenuOpen()}>
                <div style="position:absolute;left:0;top:38px;z-index:30;min-width:220px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                  <For each={["joined_desc", "joined_asc", "name_asc", "name_desc"] as const}>
                    {(s, getI) => {
                      const i = getI();
                      return (
                        <button
                          type="button"
                          onClick={() => {
                            setSortBy(s);
                            setSortMenuOpen(false);
                          }}
                          style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${sortBy() === s ? "#FF5E13" : "#374151"};background:${sortBy() === s ? "#FFF1EB" : "transparent"}`}
                        >
                          {["Joining (Newest)", "Joining (Oldest)", "Name (A→Z)", "Name (Z→A)"][i]}
                        </button>
                      );
                    }}
                  </For>
                </div>
              </Show>
            </div>
            <div style="position:relative">
              <button
                type="button"
                onClick={() => {
                  setFilterMenuOpen((v) => !v);
                  setSortMenuOpen(false);
                }}
                style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer"
              >
                <svg
                  width="13"
                  height="13"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <path d="M3 5h18M6 12h12M10 19h4" />
                </svg>
                Filters
              </button>
              <Show when={filterMenuOpen()}>
                <div style="position:absolute;left:0;top:38px;z-index:30;min-width:220px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                  <For
                    each={
                      ["all", "ACTIVE", "PROBATION", "ON_LEAVE", "SUSPENDED", "INACTIVE"] as const
                    }
                  >
                    {(s) => (
                      <button
                        type="button"
                        onClick={() => {
                          setStatusFilter(s as any);
                          setFilterMenuOpen(false);
                        }}
                        style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${statusFilter() === s ? "#FF5E13" : "#374151"};background:${statusFilter() === s ? "#FFF1EB" : "transparent"}`}
                      >
                        {s === "all" ? "All Statuses" : s.replace("_", " ").toUpperCase()}
                      </button>
                    )}
                  </For>
                </div>
              </Show>
            </div>
            <button
              type="button"
              style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer"
            >
              Export
            </button>
          </div>

          {/* Table */}
          <div class="overflow-x-auto">
            <table class="min-w-full">
              <thead>
                <tr style="background:#0D0D2A;text-align:left">
                  <th style="padding:10px 16px;font-size:11px;font-weight:600;letter-spacing:0.05em;color:#FFFFFF;text-transform:uppercase;white-space:nowrap">
                    Employee ID
                  </th>
                  <th style="padding:10px 16px;font-size:11px;font-weight:600;letter-spacing:0.05em;color:#FFFFFF;text-transform:uppercase;white-space:nowrap">
                    First Name
                  </th>
                  <th style="padding:10px 16px;font-size:11px;font-weight:600;letter-spacing:0.05em;color:#FFFFFF;text-transform:uppercase;white-space:nowrap">
                    Last Name
                  </th>
                  <th style="padding:10px 16px;font-size:11px;font-weight:600;letter-spacing:0.05em;color:#FFFFFF;text-transform:uppercase;white-space:nowrap">
                    Email
                  </th>
                  <th style="padding:10px 16px;font-size:11px;font-weight:600;letter-spacing:0.05em;color:#FFFFFF;text-transform:uppercase;white-space:nowrap">
                    Phone
                  </th>
                  <th style="padding:10px 16px;font-size:11px;font-weight:600;letter-spacing:0.05em;color:#FFFFFF;text-transform:uppercase;white-space:nowrap">
                    Department
                  </th>
                  <th style="padding:10px 16px;font-size:11px;font-weight:600;letter-spacing:0.05em;color:#FFFFFF;text-transform:uppercase;white-space:nowrap">
                    Designation
                  </th>
                  <th style="padding:10px 16px;font-size:11px;font-weight:600;letter-spacing:0.05em;color:#FFFFFF;text-transform:uppercase;white-space:nowrap">
                    Status
                  </th>
                  <th style="padding:10px 16px;font-size:11px;font-weight:600;letter-spacing:0.05em;color:#FFFFFF;text-transform:uppercase;white-space:nowrap;text-align:center">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody>
                <For each={filteredRows()}>
                  {(row) => (
                    <tr
                      style="border-bottom:1px solid #F3F4F6"
                      class="hover:bg-[#FAFAFA] transition-colors"
                    >
                      <td style="padding:12px 16px;font-size:12px;font-family:monospace;color:#6B7280">
                        {row.employeeId || "—"}
                      </td>
                      <td style="padding:12px 16px;font-size:14px;font-weight:600;color:#111827">
                        {row.firstName || "—"}
                      </td>
                      <td style="padding:12px 16px;font-size:14px;font-weight:600;color:#111827">
                        {row.lastName || "—"}
                      </td>
                      <td style="padding:12px 16px;font-size:13px;color:#6B7280">{row.email}</td>
                      <td style="padding:12px 16px;font-size:13px;color:#6B7280">
                        {row.phone || "—"}
                      </td>
                      <td style="padding:12px 16px;font-size:13px;color:#6B7280">
                        {row.department || "—"}
                      </td>
                      <td style="padding:12px 16px;font-size:13px;color:#6B7280">
                        {row.designation || "—"}
                      </td>
                      <td style="padding:12px 16px">
                        <StatusBadge status={row.status} />
                      </td>
                      <td style="padding:12px 16px;position:relative;text-align:center">
                        <button
                          type="button"
                          onClick={() => setOpenMenuId(openMenuId() === row.id ? null : row.id)}
                          style="display:inline-flex;height:32px;width:32px;align-items:center;justify-content:center;border-radius:8px;color:#9CA3AF;background:none;border:none;cursor:pointer"
                        >
                          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                            <circle cx="12" cy="5" r="1.5" />
                            <circle cx="12" cy="12" r="1.5" />
                            <circle cx="12" cy="19" r="1.5" />
                          </svg>
                        </button>
                        <Show when={openMenuId() === row.id}>
                          <div style="position:absolute;right:20px;top:44px;z-index:20;width:180px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 20px rgba(0,0,0,0.12)">
                            <button
                              type="button"
                              onClick={() => openDetail(row)}
                              style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:8px 12px;font-size:13px;color:#374151;background:none;border:none;cursor:pointer;text-align:left"
                            >
                              View Employee
                            </button>
                            <button
                              type="button"
                              onClick={() => openEdit(row)}
                              style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:8px 12px;font-size:13px;color:#374151;background:none;border:none;cursor:pointer;text-align:left"
                            >
                              Edit Employee
                            </button>
                            <button
                              type="button"
                              onClick={() => {
                                setOpenMenuId(null);
                              }}
                              style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:8px 12px;font-size:13px;color:#D97706;background:none;border:none;cursor:pointer;text-align:left"
                            >
                              {row.status === "SUSPENDED" ? "Unsuspend" : "Suspend"}
                            </button>
                            <button
                              type="button"
                              onClick={() => {
                                setOpenMenuId(null);
                              }}
                              style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:8px 12px;font-size:13px;color:#DC2626;background:none;border:none;cursor:pointer;text-align:left"
                            >
                              {row.status === "INACTIVE" ? "Enable" : "Disable"}
                            </button>
                            <button
                              type="button"
                              onClick={() => {
                                const newPassword = prompt(
                                  "Enter new password for " + row.name + ":"
                                );
                                if (newPassword && newPassword.length >= 8) {
                                  setOpenMenuId(null);
                                } else if (newPassword && newPassword.length < 8) {
                                  alert("Password must be at least 8 characters");
                                }
                              }}
                              style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:8px 12px;font-size:13px;color:#374151;background:none;border:none;cursor:pointer;text-align:left"
                            >
                              Change Password
                            </button>
                            <button
                              type="button"
                              onClick={async () => {
                                if (!confirm(`Are you sure you want to delete ${row.name}?`))
                                  {return;}
                                setOpenMenuId(null);
                                try {
                                  const accessToken =
                                    typeof sessionStorage !== "undefined"
                                      ? (
                                          sessionStorage.getItem("nxtgauge_admin_access_token") ||
                                          ""
                                        ).trim()
                                      : "";
                                  const res = await fetch(`${API}/api/admin/employees/${row.id}`, {
                                    method: "DELETE",
                                    headers: {
                                      "Content-Type": "application/json",
                                      Accept: "application/json",
                                      ...(accessToken
                                        ? { Authorization: `Bearer ${accessToken}` }
                                        : {}),
                                    },
                                    credentials: "include",
                                  });
                                  if (!res.ok) throw new Error("Failed to delete employee");
                                  await load();
                                } catch {
                                  alert("Failed to delete employee");
                                }
                              }}
                              style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:8px 12px;font-size:13px;color:#DC2626;background:none;border:none;cursor:pointer;text-align:left"
                            >
                              Delete Employee
                            </button>
                          </div>
                        </Show>
                      </td>
                    </tr>
                  )}
                </For>
              </tbody>
            </table>
          </div>
        </div>
      </Show>

      {/* ── FORM VIEW ── */}
      <Show when={view() === "form"}>
        <div style="margin-top:24px;display:flex;align-items:center;gap:24px;border-bottom:1px solid #E5E7EB">
          <button
            type="button"
            onClick={() => {
              void backToEmployeesList();
            }}
            style="padding-bottom:12px;font-size:14px;font-weight:500;color:#6B7280;background:none;border:none;cursor:pointer"
          >
            All Employees
          </button>
          <button
            type="button"
            style="padding-bottom:12px;font-size:14px;font-weight:500;color:#FF5E13;border-bottom:2px solid #FF5E13;background:none;cursor:pointer;margin-bottom:-1px"
          >
            {editingId() ? "Edit Employee" : "Create Employee"}
          </button>
        </div>

        <div style="margin-top:24px;border-radius:16px;border:1px solid #E5E7EB;background:white;box-shadow:0 1px 4px rgba(0,0,0,0.06);overflow:hidden">
          <div style="display:flex;align-items:center;gap:4px;border-bottom:1px solid #E5E7EB;padding:0 24px">
            <For each={["basic", "work", "access"] as const}>
              {(tab, getI) => {
                const labels = ["Basic Information", "Work Information", "Access & Permissions"];
                const i = getI();
                const active = () => formTab() === tab;
                return (
                  <button
                    type="button"
                    onClick={() => setFormTab(tab)}
                    style={`position:relative;padding:14px 8px;font-size:13px;font-weight:500;background:none;border:none;cursor:pointer;color:${active() ? "#FF5E13" : "#6B7280"}`}
                  >
                    {labels[i]}
                    <Show when={active()}>
                      <span style="position:absolute;left:0;right:0;bottom:0;height:2px;background:#FF5E13;border-radius:2px 2px 0 0" />
                    </Show>
                  </button>
                );
              }}
            </For>
          </div>

          <div style="padding:24px">
            <Show when={formTab() === "basic"}>
              <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
                <FormInput label="First Name" required value={firstName()} onInput={setFirstName} />
                <FormInput label="Last Name" required value={lastName()} onInput={setLastName} />
                <FormInput
                  label="Email Address"
                  required
                  value={email()}
                  onInput={setEmail}
                  type="email"
                />
                <FormInput label="Phone Number" value={phone()} onInput={setPhone} />
                <Show when={!editingId()}>
                  <>
                    <label style="display:block;grid-column:1 / span 2">
                      <span style="font-size:13px;font-weight:600;color:#374151">
                        Create Login Credentials
                      </span>
                      <div style="margin-top:8px;display:flex;align-items:center;gap:10px">
                        <input
                          type="checkbox"
                          checked={createLoginCreds()}
                          onChange={(e) => setCreateLoginCreds(e.currentTarget.checked)}
                          style="width:16px;height:16px;accent-color:#FF5E13;cursor:pointer"
                        />
                        <span style="font-size:12px;color:#6B7280">
                          Create a new login account if this email does not exist.
                        </span>
                      </div>
                    </label>
                    <Show when={createLoginCreds()}>
                      <>
                        <div>
                          <label style="display:block">
                            <span style="font-size:13px;font-weight:600;color:#374151">
                              Login Password <span style="color:#FF5E13">*</span>
                            </span>
                            <div style="position:relative;margin-top:6px">
                              <input
                                type={showLoginPassword() ? "text" : "password"}
                                value={loginPassword()}
                                onInput={(e) => setLoginPassword(e.currentTarget.value)}
                                placeholder="Minimum 8 characters"
                                style="height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 40px 0 14px;font-size:13px;color:#111827;outline:none;box-sizing:border-box"
                              />
                              <button
                                type="button"
                                onClick={() => setShowLoginPassword((v) => !v)}
                                style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:#6B7280;padding:4px"
                              >
                                <Show
                                  when={showLoginPassword()}
                                  fallback={
                                    <svg
                                      width="18"
                                      height="18"
                                      viewBox="0 0 24 24"
                                      fill="none"
                                      stroke="currentColor"
                                      stroke-width="2"
                                    >
                                      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                                      <circle cx="12" cy="12" r="3" />
                                    </svg>
                                  }
                                >
                                  <svg
                                    width="18"
                                    height="18"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="2"
                                  >
                                    <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
                                    <line x1="1" y1="1" x2="23" y2="23" />
                                  </svg>
                                </Show>
                              </button>
                            </div>
                          </label>
                        </div>
                        <div>
                          <label style="display:block">
                            <span style="font-size:13px;font-weight:600;color:#374151">
                              Confirm Password <span style="color:#FF5E13">*</span>
                            </span>
                            <div style="position:relative;margin-top:6px">
                              <input
                                type={showConfirmPassword() ? "text" : "password"}
                                value={confirmLoginPassword()}
                                onInput={(e) => setConfirmLoginPassword(e.currentTarget.value)}
                                placeholder="Repeat password"
                                style="height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 40px 0 14px;font-size:13px;color:#111827;outline:none;box-sizing:border-box"
                              />
                              <button
                                type="button"
                                onClick={() => setShowConfirmPassword((v) => !v)}
                                style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:#6B7280;padding:4px"
                              >
                                <Show
                                  when={showConfirmPassword()}
                                  fallback={
                                    <svg
                                      width="18"
                                      height="18"
                                      viewBox="0 0 24 24"
                                      fill="none"
                                      stroke="currentColor"
                                      stroke-width="2"
                                    >
                                      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                                      <circle cx="12" cy="12" r="3" />
                                    </svg>
                                  }
                                >
                                  <svg
                                    width="18"
                                    height="18"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="2"
                                  >
                                    <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
                                    <line x1="1" y1="1" x2="23" y2="23" />
                                  </svg>
                                </Show>
                              </button>
                            </div>
                          </label>
                        </div>
                      </>
                    </Show>
                  </>
                </Show>
              </div>
            </Show>

            <Show when={formTab() === "work"}>
              <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
                <label style="display:block">
                  <span style="font-size:13px;font-weight:600;color:#374151">Department</span>
                  <select
                    value={dept()}
                    onChange={(e) => setDept(e.currentTarget.value)}
                    style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;color:#111827;outline:none;box-sizing:border-box"
                  >
                    <option value="">Select department</option>
                    <For each={departmentOptions()}>
                      {(d) => <option value={d.id}>{d.name}</option>}
                    </For>
                  </select>
                </label>
                <label style="display:block">
                  <span style="font-size:13px;font-weight:600;color:#374151">Designation</span>
                  <select
                    value={desig()}
                    onChange={(e) => setDesig(e.currentTarget.value)}
                    style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;color:#111827;outline:none;box-sizing:border-box"
                  >
                    <option value="">Select designation</option>
                    <For each={designationOptions()}>
                      {(d) => <option value={d.id}>{d.name}</option>}
                    </For>
                  </select>
                </label>
                <label style="display:block">
                  <span style="font-size:13px;font-weight:600;color:#374151">
                    Internal Role <span style="color:#FF5E13">*</span>
                  </span>
                  <select
                    value={role()}
                    onChange={(e) => setRole(e.currentTarget.value)}
                    style="display:block;margin-top:6px;height:40px;width:100%;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 14px;font-size:13px;color:#111827;outline:none;box-sizing:border-box"
                  >
                    <option value="">Select role</option>
                    <For each={rolesOptions()}>{(r) => <option value={r.key}>{r.name}</option>}</For>
                  </select>
                </label>
                <FormInput
                  label="Joining Date"
                  value={joiningDate()}
                  onInput={setJoiningDate}
                  type="date"
                />
              </div>
            </Show>

            <Show when={formTab() === "access"}>
              <div style="display:flex;flex-direction:column;gap:20px">
                <p style="font-size:13px;color:#6B7280">
                  Manage login access and security settings for this employee.
                </p>
                <div style="display:flex;align-items:center;justify-content:space-between;padding:12px;border-radius:8px;background:#F9FAFB;border:1px solid #E5E7EB">
                  <div>
                    <p style="font-size:13px;font-weight:600;color:#111827">
                      Allow Admin Panel Login
                    </p>
                    <p style="font-size:12px;color:#6B7280">
                      Enable this employee to access the administration dashboard.
                    </p>
                  </div>
                  <div style="width:40px;height:20px;background:#FF5E13;border-radius:10px;position:relative;cursor:pointer">
                    <div style="width:16px;height:16px;background:white;border-radius:50%;position:absolute;top:2px;right:2px" />
                  </div>
                </div>
              </div>
            </Show>
          </div>

          <div style="display:flex;align-items:center;justify-content:flex-end;gap:10px;border-top:1px solid #E5E7EB;padding:14px 24px">
            <button
              type="button"
              onClick={() => {
                void backToEmployeesList();
              }}
              style="height:38px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 20px;font-size:13px;font-weight:600;color:#374151;cursor:pointer"
            >
              Cancel
            </button>
            <button
              type="button"
              onClick={() => {
                void save();
              }}
              style="height:38px;border-radius:10px;background:#0D0D2A;padding:0 24px;font-size:13px;font-weight:600;color:white;border:none;cursor:pointer"
            >
              {isSaving() ? "Saving..." : editingId() ? "Update Employee" : "Create Employee"}
            </button>
          </div>
        </div>
      </Show>

      {/* ── DETAIL VIEW ── */}
      <Show when={view() === "detail" && viewingEmp()}>
        <div style="margin-top:24px;border-radius:16px;border:1px solid #E5E7EB;background:white;box-shadow:0 1px 4px rgba(0,0,0,0.06);overflow:hidden">
          {/* Header / Profile Summary */}
          <div style="padding:24px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:24px">
            <div style="width:80px;height:80px;border-radius:50%;background:#F3F4F6;display:flex;align-items:center;justify-content:center;font-size:24px;font-weight:700;color:#9CA3AF;border:2px solid #E5E7EB">
              {viewingEmp()!.name.charAt(0)}
            </div>
            <div style="flex:1">
              <div style="display:flex;align-items:center;gap:12px">
                <h2 style="font-size:20px;font-weight:700;color:#111827">{viewingEmp()!.name}</h2>
                <StatusBadge status={viewingEmp()!.status} />
              </div>
              <p style="font-size:14px;color:#6B7280;margin-top:2px">
                {viewingEmp()!.designation} • {viewingEmp()!.department}
              </p>
              <div style="display:flex;gap:16px;margin-top:8px">
                <span style="font-size:12px;color:#6B7280;display:flex;align-items:center;gap:4px">
                  <svg
                    width="14"
                    height="14"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                  >
                    <path d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                  </svg>
                  {viewingEmp()!.email}
                </span>
                <span style="font-size:12px;color:#6B7280;display:flex;align-items:center;gap:4px">
                  <svg
                    width="14"
                    height="14"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                  >
                    <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
                    <line x1="16" y1="2" x2="16" y2="6" />
                    <line x1="8" y1="2" x2="8" y2="6" />
                    <line x1="3" y1="10" x2="21" y2="10" />
                  </svg>
                  Joined {viewingEmp()!.joiningDate || "—"}
                </span>
              </div>
            </div>
            <button
              type="button"
              onClick={() => openEdit(viewingEmp()!)}
              style="height:36px;border-radius:8px;background:#0D0D2A;padding:0 16px;font-size:13px;font-weight:600;color:white;border:none;cursor:pointer"
            >
              Edit Profile
            </button>
          </div>

          {/* Sub-tabs */}
          <div style="display:flex;align-items:center;gap:4px;border-bottom:1px solid #E5E7EB;padding:0 24px;background:#FAFAFA">
            <For each={["profile", "activity", "access"] as const}>
              {(tab, getI) => {
                const labels = ["Profile", "Activity Logs", "Access History"];
                const i = getI();
                const active = () => detailTab() === tab;
                return (
                  <button
                    type="button"
                    onClick={() => setDetailTab(tab)}
                    style={`position:relative;padding:14px 12px;font-size:13px;font-weight:600;background:none;border:none;cursor:pointer;color:${active() ? "#FF5E13" : "#6B7280"}`}
                  >
                    {labels[i]}
                    <Show when={active()}>
                      <span style="position:absolute;left:0;right:0;bottom:0;height:2px;background:#FF5E13;border-radius:2px 2px 0 0" />
                    </Show>
                  </button>
                );
              }}
            </For>
          </div>

          <div style="padding:24px">
            <Show when={detailTab() === "profile"}>
              <div style="display:grid;grid-template-columns:1fr 1fr;gap:32px">
                <div>
                  <h3 style="font-size:12px;font-weight:700;text-transform:uppercase;color:#9CA3AF;letter-spacing:0.05em;margin-bottom:16px">
                    Personal Information
                  </h3>
                  <div style="display:flex;flex-direction:column;gap:12px">
                    <For
                      each={[
                        { l: "Full Name", v: viewingEmp()!.name },
                        { l: "Email", v: viewingEmp()!.email },
                        { l: "Phone", v: viewingEmp()!.phone || "—" },
                        { l: "Gender", v: viewingEmp()!.gender || "—" },
                      ]}
                    >
                      {(item) => (
                        <div>
                          <p style="font-size:11px;color:#9CA3AF">{item.l}</p>
                          <p style="font-size:14px;font-weight:600;color:#111827">{item.v}</p>
                        </div>
                      )}
                    </For>
                  </div>
                </div>
                <div>
                  <h3 style="font-size:12px;font-weight:700;text-transform:uppercase;color:#9CA3AF;letter-spacing:0.05em;margin-bottom:16px">
                    Work Details
                  </h3>
                  <div style="display:flex;flex-direction:column;gap:12px">
                    <For
                      each={[
                        { l: "Department", v: viewingEmp()!.department || "—" },
                        { l: "Designation", v: viewingEmp()!.designation || "—" },
                        { l: "Internal Role", v: viewingEmp()!.internalRole || "—" },
                        { l: "Employment Type", v: viewingEmp()!.employmentType || "—" },
                      ]}
                    >
                      {(item) => (
                        <div>
                          <p style="font-size:11px;color:#9CA3AF">{item.l}</p>
                          <p style="font-size:14px;font-weight:600;color:#111827">{item.v}</p>
                        </div>
                      )}
                    </For>
                  </div>
                </div>
              </div>
            </Show>

            <Show when={detailTab() === "activity"}>
              <div style="display:flex;flex-direction:column;gap:16px">
                <div style="display:flex;gap:12px">
                  <div style="width:8px;height:8px;border-radius:50%;background:#FF5E13;margin-top:4px" />
                  <div>
                    <p style="font-size:13px;font-weight:600;color:#111827">Profile Updated</p>
                    <p style="font-size:12px;color:#6B7280">
                      Admin updated work information • 2 hours ago
                    </p>
                  </div>
                </div>
                <div style="display:flex;gap:12px">
                  <div style="width:8px;height:8px;border-radius:50%;background:#E5E7EB;margin-top:4px" />
                  <div>
                    <p style="font-size:13px;font-weight:600;color:#111827">Employee Created</p>
                    <p style="font-size:12px;color:#6B7280">
                      Arjun Sharma was added to the system • 2 days ago
                    </p>
                  </div>
                </div>
              </div>
            </Show>

            <Show when={detailTab() === "access"}>
              <div style="border:1px solid #E5E7EB;border-radius:12px;padding:16px">
                <div style="display:flex;justify-content:space-between;margin-bottom:16px">
                  <p style="font-size:13px;font-weight:600;color:#111827">Login Status</p>
                  <StatusBadge status="ACTIVE" />
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
                  <div>
                    <p style="font-size:11px;color:#9CA3AF">Last Login</p>
                    <p style="font-size:13px;font-weight:600;color:#111827">
                      27 Mar 2026, 10:45 AM
                    </p>
                  </div>
                  <div>
                    <p style="font-size:11px;color:#9CA3AF">IP Address</p>
                    <p style="font-size:13px;font-weight:600;color:#111827">192.168.1.45</p>
                  </div>
                </div>
              </div>
            </Show>
          </div>

          <div style="padding:16px 24px;border-top:1px solid #E5E7EB;display:flex;justify-content:flex-end">
            <button
              type="button"
              onClick={() => {
                setView("list");
                setListTab("all");
              }}
              style="height:36px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 16px;font-size:13px;font-weight:600;color:#374151;cursor:pointer"
            >
              Back to List
            </button>
          </div>
        </div>
      </Show>
    </div>
  );
}
