"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Button } from "@open-mercato/ui/primitives/button";
import { apiCall, apiCallOrThrow, readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { LoadingMessage } from "@open-mercato/ui/backend/detail";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { ChevronLeft, ChevronRight, X } from "lucide-react";
import Link from "next/link";
import { ViewSwitcher } from "../../../lib/timesheets-ui/ViewSwitcher.js";
import { CalendarPicker } from "../../../lib/timesheets-ui/CalendarPicker.js";
import { ListView } from "../../../lib/timesheets-ui/ListView.js";
import { TimerBar } from "../../../lib/timesheets-ui/TimerBar.js";
import { AddRowDropdown } from "../../../lib/timesheets-ui/AddRowDropdown.js";
import { CreateProjectDialog } from "../../../lib/timesheets-ui/CreateProjectDialog.js";
import { ProjectColorDot } from "../../../lib/timesheets-ui/ProjectColorDot.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("staff");
function getMonday(date) {
  const d = new Date(date);
  const day = d.getDay();
  const diff = day === 0 ? -6 : 1 - day;
  d.setDate(d.getDate() + diff);
  d.setHours(0, 0, 0, 0);
  return d;
}
function getSunday(monday) {
  const d = new Date(monday);
  d.setDate(d.getDate() + 6);
  return d;
}
function getWeekNumber(date) {
  const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
  d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
  const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
  return Math.ceil(((d.getTime() - yearStart.getTime()) / 864e5 + 1) / 7);
}
function formatDateKey(date) {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}
function formatDateKeyFromParts(year, month, day) {
  const m = String(month + 1).padStart(2, "0");
  const d = String(day).padStart(2, "0");
  return `${year}-${m}-${d}`;
}
function getDaysInMonth(year, month) {
  return new Date(year, month + 1, 0).getDate();
}
function isWeekendDay(date) {
  const d = date.getDay();
  return d === 0 || d === 6;
}
function minutesToDecimal(minutes) {
  if (minutes === 0) return "";
  const hours = minutes / 60;
  return hours % 1 === 0 ? String(hours) : hours.toFixed(2).replace(/0+$/, "").replace(/\.$/, "");
}
function decimalToMinutes(value) {
  const trimmed = value.trim();
  if (!trimmed) return 0;
  const num = parseFloat(trimmed.replace(",", "."));
  if (isNaN(num) || num < 0) return 0;
  return Math.min(Math.round(num * 60), 1440);
}
function getLocalizedDayName(date) {
  return date.toLocaleDateString(void 0, { weekday: "short" });
}
function getWeekDays(weekStart) {
  return Array.from({ length: 7 }, (_, i) => {
    const d = new Date(weekStart);
    d.setDate(d.getDate() + i);
    return d;
  });
}
function getMonthDays(year, month) {
  const count = getDaysInMonth(year, month);
  return Array.from({ length: count }, (_, i) => new Date(year, month, i + 1));
}
function formatWeekLabel(weekStart) {
  const weekEnd = getSunday(weekStart);
  const weekNum = getWeekNumber(weekStart);
  const startDay = weekStart.getDate();
  const endDay = weekEnd.getDate();
  const startMonth = weekStart.toLocaleString(void 0, { month: "short" });
  const endMonth = weekEnd.toLocaleString(void 0, { month: "short" });
  const year = weekStart.getFullYear();
  const dateRange = weekStart.getMonth() === weekEnd.getMonth() ? `${startDay} - ${endDay} ${startMonth} ${year}` : `${startDay} ${startMonth} - ${endDay} ${endMonth} ${year}`;
  return `${dateRange} \xB7 W${weekNum}`;
}
function formatMonthLabel(year, month) {
  const date = new Date(year, month, 1);
  return date.toLocaleString(void 0, { month: "long", year: "numeric" });
}
function MyTimesheetsPage() {
  const t = useT();
  const scopeVersion = useOrganizationScopeVersion();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const now = /* @__PURE__ */ new Date();
  const [viewMode, setViewMode] = React.useState("weekly");
  const [viewType, setViewType] = React.useState("timesheet");
  const [weekStart, setWeekStart] = React.useState(() => getMonday(now));
  const [monthYear, setMonthYear] = React.useState(now.getFullYear());
  const [monthIndex, setMonthIndex] = React.useState(now.getMonth());
  const [projects, setProjects] = React.useState([]);
  const [entries, setEntries] = React.useState({});
  const [rawEntries, setRawEntries] = React.useState([]);
  const [dirty, setDirty] = React.useState({});
  const [rawText, setRawText] = React.useState({});
  const [staffMemberId, setStaffMemberId] = React.useState(null);
  const [staffMemberMissing, setStaffMemberMissing] = React.useState(false);
  const [isInitialLoad, setIsInitialLoad] = React.useState(true);
  const [isRefreshing, setIsRefreshing] = React.useState(false);
  const [isSaving, setIsSaving] = React.useState(false);
  const [canManageProjects, setCanManageProjects] = React.useState(false);
  const [createDialogOpen, setCreateDialogOpen] = React.useState(false);
  const [allAssignedProjects, setAllAssignedProjects] = React.useState([]);
  const mutationContextId = React.useMemo(
    () => staffMemberId ? `staff-timesheets:${staffMemberId}` : "staff-timesheets:pending",
    [staffMemberId]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  React.useEffect(() => {
    let cancelled = false;
    void (async () => {
      try {
        const res = await apiCall("/api/auth/feature-check", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ features: ["staff.timesheets.projects.manage"] })
        });
        if (!cancelled) {
          setCanManageProjects(new Set(res.result?.granted ?? []).has("staff.timesheets.projects.manage"));
        }
      } catch {
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);
  const visibleDays = React.useMemo(() => {
    if (viewMode === "weekly") return getWeekDays(weekStart);
    return getMonthDays(monthYear, monthIndex);
  }, [viewMode, weekStart, monthYear, monthIndex]);
  const dateRange = React.useMemo(() => {
    if (viewMode === "weekly") {
      return { from: formatDateKey(weekStart), to: formatDateKey(getSunday(weekStart)) };
    }
    const daysInMonth = getDaysInMonth(monthYear, monthIndex);
    return {
      from: formatDateKeyFromParts(monthYear, monthIndex, 1),
      to: formatDateKeyFromParts(monthYear, monthIndex, daysInMonth)
    };
  }, [viewMode, weekStart, monthYear, monthIndex]);
  const goToPrev = React.useCallback(() => {
    if (viewMode === "weekly") {
      setWeekStart((prev) => {
        const d = new Date(prev);
        d.setDate(d.getDate() - 7);
        return d;
      });
    } else {
      setMonthIndex((prev) => {
        if (prev === 0) {
          setMonthYear((y) => y - 1);
          return 11;
        }
        return prev - 1;
      });
    }
  }, [viewMode]);
  const goToNext = React.useCallback(() => {
    if (viewMode === "weekly") {
      setWeekStart((prev) => {
        const d = new Date(prev);
        d.setDate(d.getDate() + 7);
        return d;
      });
    } else {
      setMonthIndex((prev) => {
        if (prev === 11) {
          setMonthYear((y) => y + 1);
          return 0;
        }
        return prev + 1;
      });
    }
  }, [viewMode]);
  const navigationLabel = React.useMemo(() => {
    if (viewMode === "weekly") return formatWeekLabel(weekStart);
    return formatMonthLabel(monthYear, monthIndex);
  }, [viewMode, weekStart, monthYear, monthIndex]);
  const isInitialLoadRef = React.useRef(true);
  const loadData = React.useCallback(async () => {
    if (!isInitialLoadRef.current) setIsRefreshing(true);
    try {
      const selfRes = await readApiResultOrThrow(
        "/api/staff/team-members/self",
        void 0,
        { errorMessage: t("staff.timesheets.my.errors.load", "Failed to load timesheets."), fallback: { member: null } }
      );
      const memberId = selfRes.member?.id ?? null;
      setStaffMemberId(memberId);
      if (!memberId) {
        setStaffMemberMissing(true);
        setProjects([]);
        setEntries({});
        setRawEntries([]);
        setIsInitialLoad(false);
        setIsRefreshing(false);
        return;
      }
      setStaffMemberMissing(false);
      const assignmentsRes = await readApiResultOrThrow(
        "/api/staff/timesheets/my-projects?pageSize=100",
        void 0,
        { errorMessage: t("staff.timesheets.my.errors.load", "Failed to load timesheets."), fallback: { items: [] } }
      );
      const assignmentItems = Array.isArray(assignmentsRes.items) ? assignmentsRes.items : [];
      const assignedProjectIds = assignmentItems.map((item) => String(item.time_project_id ?? item.timeProjectId ?? "")).filter((id) => id.length > 0);
      const visibleProjectIdSet = new Set(
        assignmentItems.filter((item) => item.show_in_grid === true || item.showInGrid === true).map((item) => String(item.time_project_id ?? item.timeProjectId ?? "")).filter((id) => id.length > 0)
      );
      const entriesParams = new URLSearchParams({ pageSize: "100", staffMemberId: memberId });
      if (dateRange.from) entriesParams.set("from", dateRange.from);
      if (dateRange.to) entriesParams.set("to", dateRange.to);
      const [projectsRes, entriesRes] = await Promise.all([
        assignedProjectIds.length > 0 ? readApiResultOrThrow(
          `/api/staff/timesheets/time-projects?ids=${assignedProjectIds.join(",")}&pageSize=100`,
          void 0,
          { errorMessage: t("staff.timesheets.my.errors.load", "Failed to load timesheets."), fallback: { items: [] } }
        ) : Promise.resolve({ items: [] }),
        readApiResultOrThrow(
          `/api/staff/timesheets/time-entries?${entriesParams.toString()}`,
          void 0,
          { errorMessage: t("staff.timesheets.my.errors.load", "Failed to load timesheets."), fallback: { items: [] } }
        )
      ]);
      const projectItems = Array.isArray(projectsRes.items) ? projectsRes.items : [];
      const mappedProjects = projectItems.map((item) => ({
        id: String(item.id ?? ""),
        name: String(item.name ?? ""),
        code: typeof item.code === "string" ? item.code : null,
        color: typeof item.color === "string" ? item.color : null
      }));
      setAllAssignedProjects(mappedProjects);
      const visibleProjects = mappedProjects.filter((p) => visibleProjectIdSet.has(p.id));
      setProjects(visibleProjects);
      const entryItems = Array.isArray(entriesRes.items) ? entriesRes.items : [];
      setRawEntries(entryItems);
      const map = {};
      for (const item of entryItems) {
        const projectId = String(item.time_project_id ?? item.timeProjectId ?? "");
        const rawDate = String(item.date ?? "");
        const dateKey = rawDate.slice(0, 10);
        const minutes = typeof item.duration_minutes === "number" ? item.duration_minutes : typeof item.durationMinutes === "number" ? item.durationMinutes : 0;
        const entryId = String(item.id ?? "");
        if (!map[projectId]) map[projectId] = {};
        if (!map[projectId][dateKey]) map[projectId][dateKey] = [];
        map[projectId][dateKey].push({ id: entryId || void 0, minutes });
      }
      setEntries(map);
      setDirty({});
      setRawText({});
    } catch (error) {
      logger.error("staff.timesheets.my.load", { err: error });
      flash(t("staff.timesheets.my.errors.load", "Failed to load timesheets."), "error");
    } finally {
      isInitialLoadRef.current = false;
      setIsInitialLoad(false);
      setIsRefreshing(false);
    }
  }, [dateRange.from, dateRange.to, t]);
  React.useEffect(() => {
    void loadData();
  }, [loadData, scopeVersion]);
  const handleCellChange = React.useCallback((projectId, dateKey, value) => {
    const sanitized = value.replace(/[^0-9.,]/g, "");
    setRawText((prev) => {
      const projectTexts = { ...prev[projectId] ?? {} };
      projectTexts[dateKey] = sanitized;
      return { ...prev, [projectId]: projectTexts };
    });
  }, []);
  const handleCellBlur = React.useCallback((projectId, dateKey, currentValue) => {
    const editedText = rawText[projectId]?.[dateKey];
    const text = editedText ?? currentValue;
    if (text === void 0) return;
    const minutes = decimalToMinutes(text);
    const cellEntries = entries[projectId]?.[dateKey] ?? [];
    const existingMinutes = cellEntries.reduce((sum, e) => sum + e.minutes, 0);
    if (minutes !== existingMinutes || editedText !== void 0 && cellEntries.length > 0) {
      setDirty((prev) => {
        const projectEntries = { ...prev[projectId] ?? {} };
        const firstId = cellEntries[0]?.id;
        projectEntries[dateKey] = { id: firstId, minutes };
        return { ...prev, [projectId]: projectEntries };
      });
    }
    setRawText((prev) => {
      const projectTexts = { ...prev[projectId] ?? {} };
      delete projectTexts[dateKey];
      const hasKeys = Object.keys(projectTexts).length > 0;
      if (!hasKeys) {
        const next = { ...prev };
        delete next[projectId];
        return next;
      }
      return { ...prev, [projectId]: projectTexts };
    });
  }, [rawText, entries]);
  const getCellValue = React.useCallback((projectId, dateKey) => {
    const dirtyCell = dirty[projectId]?.[dateKey];
    if (dirtyCell !== void 0) return dirtyCell.minutes;
    const cellEntries = entries[projectId]?.[dateKey] ?? [];
    return cellEntries.reduce((sum, e) => sum + e.minutes, 0);
  }, [dirty, entries]);
  const hasChanges = Object.keys(dirty).length > 0 || Object.keys(rawText).length > 0;
  const handleSave = React.useCallback(async () => {
    if (!hasChanges) return;
    const confirmed = await confirm({
      title: t("staff.timesheets.my.confirm_save.title", "Save changes?"),
      text: t("staff.timesheets.my.confirm_save.body", "Your timesheet entries will be saved.")
    });
    if (!confirmed) return;
    setIsSaving(true);
    try {
      const bulkEntries = [];
      for (const [projectId, dateMap] of Object.entries(dirty)) {
        for (const [dateKey, cellValue] of Object.entries(dateMap)) {
          const cell = cellValue;
          const cellEntries = entries[projectId]?.[dateKey] ?? [];
          const firstId = cell.id ?? cellEntries[0]?.id;
          bulkEntries.push({ id: firstId, date: dateKey, timeProjectId: projectId, durationMinutes: cell.minutes });
        }
      }
      if (bulkEntries.length === 0) return;
      const payload = { entries: bulkEntries };
      await runMutation({
        operation: () => apiCallOrThrow("/api/staff/timesheets/time-entries/bulk", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload)
        }),
        context: {
          formId: mutationContextId,
          resourceKind: "staff.timesheets.time_entry",
          resourceId: staffMemberId ?? void 0,
          staffMemberId,
          retryLastMutation
        },
        mutationPayload: payload
      });
      flash(t("staff.timesheets.my.saved", "Timesheet saved."), "success");
      await loadData();
    } catch (error) {
      logger.error("staff.timesheets.my.save", { err: error });
      flash(t("staff.timesheets.my.errors.save", "Failed to save timesheets."), "error");
    } finally {
      setIsSaving(false);
    }
  }, [dirty, entries, hasChanges, confirm, t, loadData, runMutation, mutationContextId, staffMemberId, retryLastMutation]);
  const getRowTotal = React.useCallback((projectId) => {
    let total = 0;
    for (const day of visibleDays) {
      total += getCellValue(projectId, formatDateKey(day));
    }
    return total;
  }, [visibleDays, getCellValue]);
  const getDayTotal = React.useCallback((date) => {
    const dateKey = formatDateKey(date);
    let total = 0;
    for (const project of projects) {
      total += getCellValue(project.id, dateKey);
    }
    return total;
  }, [projects, getCellValue]);
  const grandTotal = React.useMemo(() => {
    let total = 0;
    for (const project of projects) {
      total += getRowTotal(project.id);
    }
    return total;
  }, [projects, getRowTotal]);
  const workingDays = React.useMemo(() => {
    let count = 0;
    for (const day of visibleDays) {
      if (!isWeekendDay(day)) {
        const dateKey = formatDateKey(day);
        for (const project of projects) {
          if (getCellValue(project.id, dateKey) > 0) {
            count++;
            break;
          }
        }
      }
    }
    return count;
  }, [visibleDays, projects, getCellValue]);
  const dailyAverage = React.useMemo(() => {
    if (workingDays === 0) return 0;
    return grandTotal / workingDays;
  }, [grandTotal, workingDays]);
  const listViewEntries = React.useMemo(() => {
    return rawEntries.map((item) => ({
      id: String(item.id ?? ""),
      date: String(item.date ?? "").slice(0, 10),
      durationMinutes: typeof item.duration_minutes === "number" ? item.duration_minutes : typeof item.durationMinutes === "number" ? item.durationMinutes : 0,
      projectId: String(item.time_project_id ?? item.timeProjectId ?? ""),
      projectName: projects.find((p) => p.id === String(item.time_project_id ?? item.timeProjectId ?? ""))?.name ?? "",
      projectCode: projects.find((p) => p.id === String(item.time_project_id ?? item.timeProjectId ?? ""))?.code ?? null,
      projectColor: projects.find((p) => p.id === String(item.time_project_id ?? item.timeProjectId ?? ""))?.color ?? null,
      notes: typeof item.notes === "string" ? item.notes : null,
      source: typeof item.source === "string" ? item.source : "manual",
      startedAt: typeof item.started_at === "string" ? item.started_at : typeof item.startedAt === "string" ? item.startedAt : null,
      endedAt: typeof item.ended_at === "string" ? item.ended_at : typeof item.endedAt === "string" ? item.endedAt : null
    }));
  }, [rawEntries, projects]);
  const handleViewModeChange = React.useCallback((mode) => {
    setViewMode(mode);
    if (mode === "monthly") {
      const thursday = new Date(weekStart);
      thursday.setDate(thursday.getDate() + 3);
      setMonthYear(thursday.getFullYear());
      setMonthIndex(thursday.getMonth());
    } else {
      const midMonth = new Date(monthYear, monthIndex, 15);
      setWeekStart(getMonday(midMonth));
    }
  }, [weekStart, monthYear, monthIndex]);
  const visibleProjectIds = React.useMemo(() => new Set(projects.map((p) => p.id)), [projects]);
  const handleAddProject = React.useCallback(async (project) => {
    try {
      const payload = { showInGrid: true };
      await runMutation({
        operation: () => apiCallOrThrow(`/api/staff/timesheets/my-projects/${project.id}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload)
        }),
        context: {
          formId: mutationContextId,
          resourceKind: "staff.timesheets.time_project_member",
          resourceId: project.id,
          staffMemberId,
          retryLastMutation
        },
        mutationPayload: payload
      });
      setProjects((prev) => {
        if (prev.some((p) => p.id === project.id)) return prev;
        return [...prev, project];
      });
    } catch (error) {
      logger.error("staff.timesheets.my.addRow", { err: error });
      flash(t("staff.timesheets.my.addRow.error", "Could not add the project. Please try again."), "error");
    }
  }, [t, runMutation, mutationContextId, staffMemberId, retryLastMutation]);
  const handleRemoveProject = React.useCallback(async (project) => {
    const confirmed = await confirm({
      title: t("staff.timesheets.my.removeRow", "Remove from grid"),
      text: t(
        "staff.timesheets.my.removeRow.confirm",
        'Remove {projectName} from your timesheet grid? You can re-add it anytime via "+ Add row".'
      ).replace("{projectName}", project.name)
    });
    if (!confirmed) return;
    try {
      const payload = { showInGrid: false };
      await runMutation({
        operation: () => apiCallOrThrow(`/api/staff/timesheets/my-projects/${project.id}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload)
        }),
        context: {
          formId: mutationContextId,
          resourceKind: "staff.timesheets.time_project_member",
          resourceId: project.id,
          staffMemberId,
          retryLastMutation
        },
        mutationPayload: payload
      });
      setProjects((prev) => prev.filter((p) => p.id !== project.id));
      setDirty((prev) => {
        if (!prev[project.id]) return prev;
        const next = { ...prev };
        delete next[project.id];
        return next;
      });
      setRawText((prev) => {
        if (!prev[project.id]) return prev;
        const next = { ...prev };
        delete next[project.id];
        return next;
      });
    } catch (error) {
      logger.error("staff.timesheets.my.removeRow", { err: error });
      flash(t("staff.timesheets.my.removeRow.error", "Could not remove the project. Please try again."), "error");
    }
  }, [confirm, t, runMutation, mutationContextId, staffMemberId, retryLastMutation]);
  const handleProjectCreated = React.useCallback(async (project) => {
    setAllAssignedProjects((prev) => [...prev, project]);
    try {
      const payload = { showInGrid: true };
      await runMutation({
        operation: () => apiCallOrThrow(`/api/staff/timesheets/my-projects/${project.id}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload)
        }),
        context: {
          formId: mutationContextId,
          resourceKind: "staff.timesheets.time_project_member",
          resourceId: project.id,
          staffMemberId,
          retryLastMutation
        },
        mutationPayload: payload
      });
    } catch (error) {
      logger.error("staff.timesheets.my.createProject.visibility", { err: error });
    }
    setProjects((prev) => [...prev, project]);
    setCreateDialogOpen(false);
  }, [runMutation, mutationContextId, staffMemberId, retryLastMutation]);
  if (isInitialLoad) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(LoadingMessage, { label: t("staff.timesheets.my.loading", "Loading timesheets...") }) }) });
  }
  if (staffMemberMissing) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "py-12 text-center", children: [
      /* @__PURE__ */ jsx("p", { className: "text-lg font-semibold mb-2", children: t("staff.timesheets.my.noProfile.title", "Set up your profile to start tracking time") }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground mb-6", children: t("staff.timesheets.my.noProfile", "You need a Team Member profile to track time.") }),
      /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/staff/profile/create", children: t("staff.timesheets.my.createProfile", "Create My Profile") }) })
    ] }) }) });
  }
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsxs(PageBody, { children: [
      /* @__PURE__ */ jsx(
        TimerBar,
        {
          projects: allAssignedProjects,
          staffMemberId,
          onTimerStopped: loadData
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "mb-4 grid grid-cols-1 gap-4 sm:grid-cols-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: viewMode === "weekly" ? t("staff.timesheets.my.weekTotal", "Week Total") : t("staff.timesheets.my.total_hours", "Total Hours") }),
          /* @__PURE__ */ jsx("p", { className: "text-2xl font-semibold", children: minutesToDecimal(grandTotal) || "0" })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("staff.timesheets.my.working_days", "Working Days") }),
          /* @__PURE__ */ jsx("p", { className: "text-2xl font-semibold", children: workingDays })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("staff.timesheets.my.daily_average", "Daily Average") }),
          /* @__PURE__ */ jsx("p", { className: "text-2xl font-semibold", children: minutesToDecimal(Math.round(dailyAverage)) || "0" })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("staff.timesheets.my.status", "Status") }),
          /* @__PURE__ */ jsx("p", { className: "text-2xl font-semibold", children: /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-800", children: t("staff.timesheets.my.status_open", "Open") }) })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "mb-4 flex flex-wrap items-center justify-between gap-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(Button, { variant: "outline", size: "icon", type: "button", onClick: goToPrev, children: /* @__PURE__ */ jsx(ChevronLeft, { className: "size-4" }) }),
          /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold min-w-[220px] text-center", children: navigationLabel }),
          /* @__PURE__ */ jsx(Button, { variant: "outline", size: "icon", type: "button", onClick: goToNext, children: /* @__PURE__ */ jsx(ChevronRight, { className: "size-4" }) }),
          viewMode === "weekly" && /* @__PURE__ */ jsx(CalendarPicker, { selectedWeekStart: weekStart, onWeekSelect: setWeekStart })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsx(
            ViewSwitcher,
            {
              viewMode,
              onViewModeChange: handleViewModeChange,
              viewType,
              onViewTypeChange: setViewType
            }
          ),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            hasChanges && /* @__PURE__ */ jsx("span", { className: "text-xs text-amber-600 font-medium", children: t("staff.timesheets.my.unsaved", "Unsaved changes") }),
            /* @__PURE__ */ jsx(Button, { size: "sm", type: "button", onClick: handleSave, disabled: !hasChanges || isSaving, children: isSaving ? t("staff.timesheets.my.saving", "Saving...") : t("staff.timesheets.my.save_changes", "Save Changes") })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { className: isRefreshing ? "opacity-50 pointer-events-none transition-opacity" : "transition-opacity", children: allAssignedProjects.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "py-12 text-center", children: [
        /* @__PURE__ */ jsx("p", { className: "text-lg font-semibold mb-2", children: t("staff.timesheets.my.noProjects.title", "No projects assigned yet") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground mb-6", children: canManageProjects ? t("staff.timesheets.my.noProjects.admin", "Create a project and assign yourself to start tracking time.") : t("staff.timesheets.my.noProjects.employee", "Ask your manager to assign you to a project.") }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center gap-3", children: [
          canManageProjects && /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/staff/timesheets/projects/create", children: t("staff.timesheets.my.noProjects.createProject", "Create Project") }) }),
          /* @__PURE__ */ jsx(Button, { variant: "outline", asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/staff/timesheets/projects", children: t("staff.timesheets.my.noProjects.viewProjects", "View Projects") }) })
        ] })
      ] }) : viewType === "list" ? /* @__PURE__ */ jsx(ListView, { entries: listViewEntries, onEntryUpdated: loadData }) : /* @__PURE__ */ jsx("div", { className: "overflow-x-auto rounded-lg border", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-sm table-fixed", children: [
        /* @__PURE__ */ jsxs("colgroup", { children: [
          /* @__PURE__ */ jsx("col", { className: viewMode === "weekly" ? "w-[35%]" : "w-[140px] min-w-[140px]" }),
          visibleDays.map((date) => /* @__PURE__ */ jsx("col", { className: viewMode === "weekly" ? "" : "w-[36px] min-w-[36px]" }, formatDateKey(date))),
          /* @__PURE__ */ jsx("col", { className: viewMode === "weekly" ? "w-[72px]" : "w-[56px] min-w-[56px]" })
        ] }),
        /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "border-b bg-muted/50", children: [
          /* @__PURE__ */ jsx("th", { className: "sticky left-0 z-10 bg-muted px-3 py-2 text-left font-medium", children: t("staff.timesheets.my.project", "Project") }),
          visibleDays.map((date) => {
            const dayName = getLocalizedDayName(date);
            const weekend = isWeekendDay(date);
            return /* @__PURE__ */ jsxs(
              "th",
              {
                className: `py-2 text-center font-medium px-1 ${weekend ? "bg-muted/80 text-muted-foreground" : ""}`,
                children: [
                  /* @__PURE__ */ jsx("div", { className: "text-[10px] uppercase text-muted-foreground", children: dayName }),
                  /* @__PURE__ */ jsx("div", { className: "text-xs", children: date.getDate() })
                ]
              },
              formatDateKey(date)
            );
          }),
          /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium", children: t("staff.timesheets.my.total", "Total") })
        ] }) }),
        /* @__PURE__ */ jsxs("tbody", { children: [
          projects.map((project) => /* @__PURE__ */ jsxs("tr", { className: "group border-b hover:bg-muted/30", children: [
            /* @__PURE__ */ jsx("td", { className: "sticky left-0 z-10 bg-background px-3 py-1.5 font-medium text-foreground", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
              /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 truncate", title: project.name, children: [
                  /* @__PURE__ */ jsx(ProjectColorDot, { colorKey: project.color, projectName: project.name, size: "sm" }),
                  /* @__PURE__ */ jsx("span", { className: "truncate", children: project.name })
                ] }),
                project.code && /* @__PURE__ */ jsx("div", { className: "text-[10px] text-muted-foreground", children: project.code })
              ] }),
              /* @__PURE__ */ jsx(
                "button",
                {
                  type: "button",
                  onClick: () => {
                    void handleRemoveProject(project);
                  },
                  "aria-label": t("staff.timesheets.my.removeRow", "Remove from grid"),
                  title: t("staff.timesheets.my.removeRow", "Remove from grid"),
                  className: "opacity-0 group-hover:opacity-100 focus:opacity-100 inline-flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-opacity",
                  children: /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5" })
                }
              )
            ] }) }),
            visibleDays.map((date) => {
              const dateKey = formatDateKey(date);
              const weekend = isWeekendDay(date);
              const cellMinutes = getCellValue(project.id, dateKey);
              const isDirty = dirty[project.id]?.[dateKey] !== void 0;
              return /* @__PURE__ */ jsx("td", { className: `px-0.5 py-0.5 ${weekend ? "bg-muted/40" : ""}`, children: weekend ? /* @__PURE__ */ jsx("div", { className: "rounded px-1 py-1 text-center text-xs text-muted-foreground/50", children: "-" }) : /* @__PURE__ */ jsx(
                "input",
                {
                  type: "text",
                  inputMode: "decimal",
                  className: `mx-auto block rounded border text-center tabular-nums transition-colors
                                ${viewMode === "weekly" ? "w-12 px-1 py-0.5 text-xs" : "w-8 px-0 py-1 text-[10px]"}
                                ${isDirty ? "border-amber-400 bg-amber-50" : "border-muted-foreground/20 bg-transparent"}
                                ${cellMinutes > 0 ? "font-semibold" : "text-muted-foreground"}
                                hover:border-muted-foreground/40 focus:border-primary focus:bg-background focus:outline-none`,
                  value: rawText[project.id]?.[dateKey] ?? minutesToDecimal(cellMinutes),
                  onChange: (e) => handleCellChange(project.id, dateKey, e.target.value),
                  onBlur: (event) => handleCellBlur(project.id, dateKey, event.currentTarget.value),
                  placeholder: t("staff.timesheets.my.durationPlaceholder", "0")
                }
              ) }, dateKey);
            }),
            /* @__PURE__ */ jsx("td", { className: "px-3 py-1.5 text-right font-semibold text-xs tabular-nums", children: minutesToDecimal(getRowTotal(project.id)) || "0" })
          ] }, project.id)),
          /* @__PURE__ */ jsx("tr", { className: "border-b", children: /* @__PURE__ */ jsx("td", { colSpan: visibleDays.length + 2, className: "sticky left-0 bg-background px-1 py-0.5", children: /* @__PURE__ */ jsx(
            AddRowDropdown,
            {
              assignedProjects: allAssignedProjects,
              visibleProjectIds,
              canCreateProject: canManageProjects,
              onAddProject: handleAddProject,
              onCreateProject: () => setCreateDialogOpen(true)
            }
          ) }) })
        ] }),
        /* @__PURE__ */ jsx("tfoot", { children: /* @__PURE__ */ jsxs("tr", { className: "border-t bg-muted/50 font-semibold", children: [
          /* @__PURE__ */ jsx("td", { className: "sticky left-0 z-10 bg-muted px-3 py-2", children: t("staff.timesheets.my.daily_total", "Daily Total") }),
          visibleDays.map((date) => {
            const weekend = isWeekendDay(date);
            const dayMinutes = getDayTotal(date);
            return /* @__PURE__ */ jsx("td", { className: `py-2 text-center text-xs tabular-nums ${weekend ? "text-muted-foreground/50" : ""}`, children: weekend ? "-" : minutesToDecimal(dayMinutes) || "-" }, formatDateKey(date));
          }),
          /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right tabular-nums font-semibold", children: minutesToDecimal(grandTotal) || "0" })
        ] }) })
      ] }) }) })
    ] }),
    ConfirmDialogElement,
    /* @__PURE__ */ jsx(
      CreateProjectDialog,
      {
        open: createDialogOpen,
        onOpenChange: setCreateDialogOpen,
        onProjectCreated: handleProjectCreated
      }
    )
  ] });
}
export {
  MyTimesheetsPage as default
};
//# sourceMappingURL=page.js.map
