'use client';

import { useState, useCallback, useEffect, useMemo, type RefCallback } from 'react';
import { useRouter } from 'next/navigation';
import { LayoutDashboard, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { CEODashboardSkeleton } from './skeletons';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { DashboardSwitcher } from '@/components/business/DashboardSwitcher';
import {
  TodayIssueSection,
  EnhancedStatusBoardSection,
  EnhancedDailyReportSection,
  EnhancedMonthlyExpenseSection,
  CardManagementSection,
  EntertainmentSection,
  WelfareSection,
  ReceivableSection,
  DebtCollectionSection,
  VatSection,
  CalendarSection,
  SalesStatusSection,
  PurchaseStatusSection,
  DailyProductionSection,
  ShipmentSection,
  UnshippedSection,
  ConstructionSection,
  DailyAttendanceSection,
} from './sections';
import type { CEODashboardData, CalendarScheduleItem, DashboardSettings, DetailModalConfig, SectionKey } from './types';
import { DEFAULT_DASHBOARD_SETTINGS, DEFAULT_SECTION_ORDER } from './types';
import { ScheduleDetailModal, DetailModal } from './modals';
import { DashboardSettingsDialog } from './dialogs/DashboardSettingsDialog';
import { LazySection } from './LazySection';
import { SummaryNavBar } from './SummaryNavBar';
import { useSectionSummary } from './useSectionSummary';
import { useCEODashboard, useTodayIssue, useCalendar, useVat, useEntertainment, useEntertainmentDetail, useWelfare, useWelfareDetail, useVatDetail, useMonthlyExpenseDetail, type MonthlyExpenseCardId } from '@/hooks/useCEODashboard';
import { useCardManagementModals } from '@/hooks/useCardManagementModals';
import { getCardManagementModalConfigWithData } from './modalConfigs';
import { transformEntertainmentDetailResponse, transformWelfareDetailResponse, transformVatDetailResponse } from '@/lib/api/dashboard/transformers';
import { toast } from 'sonner';
import { consumeStaleSections, DASHBOARD_INVALIDATE_EVENT, type DashboardSectionKey } from '@/lib/dashboard-invalidation';
import { useModules } from '@/hooks/useModules';
import { sectionRequiresModule } from './types';

export function CEODashboard() {
  const router = useRouter();

  // 모듈 활성화 정보 (tenantIndustry 미설정 시 모든 모듈 표시)
  const { isEnabled, tenantIndustry } = useModules();
  const moduleAware = !!tenantIndustry; // industry 설정 시에만 모듈 필터링 적용

  // API 데이터 Hook (모듈 비활성 시 API 호출 스킵)
  const apiData = useCEODashboard({
    salesStatus: true,
    purchaseStatus: true,
    dailyProduction: !moduleAware || isEnabled('production'),
    unshipped: true, // 공통 (outbound/logistics)
    construction: !moduleAware || isEnabled('construction'),
    dailyAttendance: true,
  });

  // TodayIssue API Hook (Phase 2)
  const todayIssueData = useTodayIssue(30);

  // Calendar API Hook (Phase 2)
  const calendarData = useCalendar();

  // Vat API Hook (Phase 2)
  const vatData = useVat();

  // Entertainment API Hook (Phase 2)
  const entertainmentData = useEntertainment();

  // Welfare API Hook (Phase 2)
  const welfareData = useWelfare();

  // 대시보드 targeted refetch: CUD 후 stale 섹션만 갱신
  useEffect(() => {
    const refetchSection = (key: string) => {
      if (key === 'entertainment') entertainmentData.refetch();
      else if (key === 'welfare') welfareData.refetch();
      else apiData.refetchMap[key as DashboardSectionKey]?.();
    };
    const stale = consumeStaleSections();
    if (stale.length > 0) {
      for (const key of stale) refetchSection(key);
    }
    const handler = (e: Event) => {
      const sections = (e as CustomEvent).detail?.sections as string[] | undefined;
      if (sections) {
        for (const key of sections) refetchSection(key);
      }
    };
    window.addEventListener(DASHBOARD_INVALIDATE_EVENT, handler);
    return () => window.removeEventListener(DASHBOARD_INVALIDATE_EVENT, handler);
  }, [apiData.refetchMap, entertainmentData.refetch, welfareData.refetch]);

  // Card Management Modal API Hook (Phase 3)
  const cardManagementModals = useCardManagementModals();

  // 전체 로딩 상태 (하나라도 로딩 중이면 스켈레톤 표시)
  const isLoading = useMemo(() => {
    return (
      apiData.dailyReport.loading ||
      apiData.receivable.loading ||
      apiData.debtCollection.loading ||
      apiData.monthlyExpense.loading ||
      apiData.cardManagement.loading ||
      apiData.statusBoard.loading ||
      apiData.salesStatus.loading ||
      apiData.purchaseStatus.loading ||
      apiData.dailyProduction.loading ||
      apiData.unshipped.loading ||
      apiData.construction.loading ||
      apiData.dailyAttendance.loading ||
      todayIssueData.loading ||
      calendarData.loading ||
      vatData.loading ||
      entertainmentData.loading ||
      welfareData.loading
    );
  }, [apiData, todayIssueData.loading, calendarData.loading, vatData.loading, entertainmentData.loading, welfareData.loading]);

  // API 데이터만으로 구성 (mock 제거 — API 미응답 시 undefined → 빈 상태 UI)
  const data = useMemo<CEODashboardData>(() => ({
    todayIssue: apiData.statusBoard.data ?? [],
    todayIssueList: todayIssueData.data?.items ?? [],
    dailyReport: apiData.dailyReport.data ?? undefined,
    monthlyExpense: apiData.monthlyExpense.data ?? undefined,
    cardManagement: apiData.cardManagement.data ?? undefined,
    entertainment: entertainmentData.data ?? undefined,
    welfare: welfareData.data ?? undefined,
    receivable: apiData.receivable.data ?? undefined,
    debtCollection: apiData.debtCollection.data ?? undefined,
    vat: vatData.data ?? undefined,
    calendarSchedules: calendarData.data?.items ?? undefined,
    salesStatus: apiData.salesStatus.data ?? {
      cumulativeSales: 0, achievementRate: 0, yoyChange: 0, monthlySales: 0,
      monthlyTrend: [], clientSales: [], dailyItems: [], dailyTotal: 0,
    },
    purchaseStatus: apiData.purchaseStatus.data ?? {
      cumulativePurchase: 0, unpaidAmount: 0, yoyChange: 0,
      monthlyTrend: [], materialRatio: [], dailyItems: [], dailyTotal: 0,
    },
    dailyProduction: apiData.dailyProduction.data ?? {
      date: '', processes: [],
      shipment: { expectedAmount: 0, expectedCount: 0, actualAmount: 0, actualCount: 0 },
    },
    unshipped: apiData.unshipped.data ?? { items: [] },
    constructionData: apiData.construction.data ?? { thisMonth: 0, completed: 0, items: [] },
    dailyAttendance: apiData.dailyAttendance.data ?? {
      present: 0, onLeave: 0, late: 0, absent: 0, employees: [],
    },
  }), [apiData, todayIssueData.data, calendarData.data, vatData.data, entertainmentData.data, welfareData.data]);

  // 일정 상세 모달 상태
  const [isScheduleModalOpen, setIsScheduleModalOpen] = useState(false);
  const [selectedSchedule, setSelectedSchedule] = useState<CalendarScheduleItem | null>(null);

  // 항목 설정 모달 상태
  const [isSettingsModalOpen, setIsSettingsModalOpen] = useState(false);
  const [dashboardSettings, setDashboardSettings] = useState<DashboardSettings>(DEFAULT_DASHBOARD_SETTINGS);

  // EntertainmentDetail Hook (모달용 상세 API) - dashboardSettings 이후에 선언
  const entertainmentDetailData = useEntertainmentDetail();

  // WelfareDetail Hook (모달용 상세 API) - dashboardSettings 이후에 선언
  const welfareDetailData = useWelfareDetail({
    calculationType: dashboardSettings.welfare.calculationType,
  });

  // VatDetail Hook (부가세 상세 모달용 API)
  const vatDetailData = useVatDetail();

  // MonthlyExpenseDetail Hook (당월 예상 지출 모달용 상세 API)
  const monthlyExpenseDetailData = useMonthlyExpenseDetail();

  // 상세 모달 상태
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [detailModalConfig, setDetailModalConfig] = useState<DetailModalConfig | null>(null);
  const [currentModalCardId, setCurrentModalCardId] = useState<string | null>(null);

  // 클라이언트에서만 localStorage에서 설정 불러오기 (hydration 에러 방지)
  useEffect(() => {
    const saved = localStorage.getItem('ceo-dashboard-settings');
    if (saved) {
      try {
        const parsed = JSON.parse(saved);
        // 구버전 설정 마이그레이션: object → boolean 변환
        if (typeof parsed.receivable === 'object' && parsed.receivable !== null) {
          parsed.receivable = parsed.receivable.enabled ?? true;
        }
        if (typeof parsed.salesStatus === 'object' && parsed.salesStatus !== null) {
          parsed.salesStatus = parsed.salesStatus.enabled ?? true;
        }
        if (typeof parsed.purchaseStatus === 'object' && parsed.purchaseStatus !== null) {
          parsed.purchaseStatus = parsed.purchaseStatus.enabled ?? true;
        }
        // sectionOrder 마이그레이션
        if (!parsed.sectionOrder) {
          parsed.sectionOrder = DEFAULT_SECTION_ORDER;
        } else {
          const currentOrder: SectionKey[] = parsed.sectionOrder;
          // 새 섹션이 추가됐으면 끝에 추가
          for (const key of DEFAULT_SECTION_ORDER) {
            if (!currentOrder.includes(key)) {
              currentOrder.push(key);
            }
          }
          // 삭제된 섹션 필터링
          parsed.sectionOrder = currentOrder.filter((key: SectionKey) =>
            DEFAULT_SECTION_ORDER.includes(key)
          );
        }
        setDashboardSettings(parsed);
      } catch {
        // 파싱 실패 시 기본값 유지
      }
    }
  }, []);

  // 항목 설정 클릭
  const handleSettingClick = useCallback(() => {
    setIsSettingsModalOpen(true);
  }, []);

  // 항목 설정 저장
  const handleSettingsSave = useCallback((settings: DashboardSettings) => {
    setDashboardSettings(settings);
    // localStorage에 설정 저장
    if (typeof window !== 'undefined') {
      localStorage.setItem('ceo-dashboard-settings', JSON.stringify(settings));
    }
  }, []);

  // 항목 설정 모달 닫기
  const handleSettingsModalClose = useCallback(() => {
    setIsSettingsModalOpen(false);
  }, []);

  // 일일 일보 클릭 → 일일 일보 페이지로 이동
  const handleDailyReportClick = useCallback(() => {
    router.push('/ko/accounting/daily-report');
  }, [router]);

  // 상세 모달 닫기
  const handleDetailModalClose = useCallback(() => {
    setIsDetailModalOpen(false);
    setDetailModalConfig(null);
    setCurrentModalCardId(null);
  }, []);

  // 당월 예상 지출 카드 클릭 - API 데이터로 모달 열기
  const handleMonthlyExpenseCardClick = useCallback(async (cardId: string) => {
    const config = await monthlyExpenseDetailData.fetchData(cardId as MonthlyExpenseCardId);
    if (config) {
      setCurrentModalCardId(cardId);
      setDetailModalConfig(config);
      setIsDetailModalOpen(true);
    }
  }, [monthlyExpenseDetailData]);

  // 모달 날짜/검색 필터 변경 → 재조회 (당월 예상 지출 + 가지급금 + 접대비 상세)
  const handleDateFilterChange = useCallback(async (params: { startDate: string; endDate: string; search: string }) => {
    if (!currentModalCardId) return;

    // cm2: 가지급금 상세 모달 날짜 필터
    if (currentModalCardId === 'cm2') {
      try {
        const modalData = await cardManagementModals.fetchModalData('cm2', {
          start_date: params.startDate,
          end_date: params.endDate,
        });
        const config = getCardManagementModalConfigWithData('cm2', modalData);
        if (config) {
          setDetailModalConfig(config);
        }
      } catch {
        // 실패 시 기존 config 유지
      }
      return;
    }

    // 복리후생비 상세 모달 날짜 필터
    if (currentModalCardId === 'welfare_detail') {
      try {
        const response = await fetch(
          `/api/proxy/welfare/detail?calculation_type=${dashboardSettings.welfare.calculationType}&start_date=${params.startDate}&end_date=${params.endDate}`,
        );
        if (response.ok) {
          const result = await response.json();
          if (result.success) {
            const config = transformWelfareDetailResponse(result.data);
            setDetailModalConfig(config);
          }
        }
      } catch {
        // 실패 시 기존 config 유지
      }
      return;
    }

    // 접대비 상세 모달 날짜 필터
    if (currentModalCardId === 'entertainment_detail') {
      try {
        const response = await fetch(
          `/api/proxy/entertainment/detail?company_type=${dashboardSettings.entertainment.companyType}&start_date=${params.startDate}&end_date=${params.endDate}`,
        );
        if (response.ok) {
          const result = await response.json();
          if (result.success) {
            const config = transformEntertainmentDetailResponse(result.data);
            setDetailModalConfig(config);
          }
        }
      } catch {
        // 실패 시 기존 config 유지
      }
      return;
    }

    // 당월 예상 지출 모달 날짜 필터
    const config = await monthlyExpenseDetailData.fetchData(
      currentModalCardId as MonthlyExpenseCardId,
      params,
    );
    if (config) {
      setDetailModalConfig(config);
    }
  }, [currentModalCardId, monthlyExpenseDetailData, cardManagementModals, dashboardSettings.entertainment, dashboardSettings.welfare]);


  // 모달 테이블 행 클릭 → 관련 페이지 이동
  const handleModalRowClick = useCallback((_row: Record<string, unknown>) => {
    if (!currentModalCardId) return;

    const routeMap: Record<string, string> = {
      cm2: '/ko/accounting/card-transactions',   // 가지급금 → 카드거래 목록
      me1: '/ko/accounting/purchase',             // 당월 매입 → 매입관리
      me2: '/ko/accounting/card-transactions',    // 당월 카드 → 카드거래 목록
      me3: '/ko/accounting/bills',                // 당월 발행어음 → 어음관리
      me4: '/ko/accounting/expected-expenses',    // 당월 지출 예상 → 지출예상
    };

    const targetPath = routeMap[currentModalCardId];
    if (targetPath) {
      handleDetailModalClose();
      router.push(targetPath);
    }
  }, [currentModalCardId, handleDetailModalClose, router]);

  // 카드/가지급금 관리 카드 클릭 → 모두 가지급금 상세(cm2) 모달
  // 기획서 P52: 카드, 경조사, 상품권, 접대비, 총합계 모두 동일한 가지급금 상세 모달
  const handleCardManagementCardClick = useCallback(async (_cardId: string) => {
    try {
      const modalData = await cardManagementModals.fetchModalData('cm2');
      const config = getCardManagementModalConfigWithData('cm2', modalData);
      if (config) {
        setCurrentModalCardId('cm2');
        setDetailModalConfig(config);
        setIsDetailModalOpen(true);
      } else {
        toast.error('데이터를 불러올 수 없습니다');
      }
    } catch {
      toast.error('데이터를 불러올 수 없습니다');
    }
  }, [cardManagementModals]);

  // 접대비 현황 카드 클릭 - API 데이터로 모달 열기
  const handleEntertainmentCardClick = useCallback(async (_cardId: string) => {
    setCurrentModalCardId('entertainment_detail');
    const apiConfig = await entertainmentDetailData.refetch();
    if (apiConfig) {
      setDetailModalConfig(apiConfig);
      setIsDetailModalOpen(true);
    } else {
      toast.error('데이터를 불러올 수 없습니다');
    }
  }, [entertainmentDetailData]);

  // 복리후생비 현황 카드 클릭 (모든 카드가 동일한 상세 모달)
  const handleWelfareCardClick = useCallback(async () => {
    const apiConfig = await welfareDetailData.refetch();
    if (apiConfig) {
      setDetailModalConfig(apiConfig);
      setCurrentModalCardId('welfare_detail');
      setIsDetailModalOpen(true);
    } else {
      toast.error('데이터를 불러올 수 없습니다');
    }
  }, [welfareDetailData]);

  // 신고기간 변경 시 API 재호출
  const handlePeriodChange = useCallback(async (periodValue: string) => {
    // periodValue: "2026-quarter-1" → parse
    const parts = periodValue.split('-');
    if (parts.length < 3) return;
    const [year, periodType, period] = parts;
    try {
      const response = await fetch(
        `/api/proxy/vat/detail?period_type=${periodType}&year=${year}&period=${period}`,
      );
      if (response.ok) {
        const result = await response.json();
        if (result.success) {
          const config = transformVatDetailResponse(result.data);
          // 새 config에도 onPeriodChange 콜백 주입
          if (config.periodSelect) {
            config.periodSelect.onPeriodChange = handlePeriodChange;
          }
          setDetailModalConfig(config);
        }
      }
    } catch {
      // 실패 시 기존 config 유지
    }
  }, []);

  // 부가세 클릭 (모든 카드가 동일한 상세 모달) - API 데이터로 열기
  const handleVatClick = useCallback(async () => {
    setCurrentModalCardId('vat_detail');
    const apiConfig = await vatDetailData.refetch();
    if (apiConfig) {
      if (apiConfig.periodSelect) {
        apiConfig.periodSelect.onPeriodChange = handlePeriodChange;
      }
      setDetailModalConfig(apiConfig);
      setIsDetailModalOpen(true);
    } else {
      toast.error('데이터를 불러올 수 없습니다');
    }
  }, [vatDetailData, handlePeriodChange]);

  // 캘린더 일정 클릭 (기존 일정 수정)
  const handleScheduleClick = useCallback((schedule: CalendarScheduleItem) => {
    setSelectedSchedule(schedule);
    setIsScheduleModalOpen(true);
  }, []);

  // 캘린더 일정 등록 (새 일정)
  const handleScheduleEdit = useCallback((schedule: CalendarScheduleItem) => {
    setSelectedSchedule(schedule);
    setIsScheduleModalOpen(true);
  }, []);

  // 일정 모달 닫기
  const handleScheduleModalClose = useCallback(() => {
    setIsScheduleModalOpen(false);
    setSelectedSchedule(null);
  }, []);

  // 일정 저장 (optimistic update — refetch 없이 로컬 상태만 갱신)
  const handleScheduleSave = useCallback(async (formData: {
    title: string;
    department: string;
    startDate: string;
    endDate: string;
    isAllDay: boolean;
    startTime: string;
    endTime: string;
    color: string;
    content: string;
  }) => {
    try {
      // schedule_ 접두사에서 실제 ID 추출
      const rawId = selectedSchedule?.id;
      const numericId = rawId?.startsWith('schedule_') ? rawId.replace('schedule_', '') : null;

      const body = {
        title: formData.title,
        description: formData.content,
        start_date: formData.startDate,
        end_date: formData.endDate,
        start_time: formData.isAllDay ? null : (formData.startTime || null),
        end_time: formData.isAllDay ? null : (formData.endTime || null),
        is_all_day: formData.isAllDay,
        color: formData.color || null,
      };

      const url = numericId
        ? `/api/proxy/calendar/schedules/${numericId}`
        : '/api/proxy/calendar/schedules';
      const method = numericId ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });

      if (!response.ok) throw new Error('Failed to save schedule');

      // API 응답에서 실제 ID 추출 (없으면 임시 ID)
      let savedId = numericId;
      try {
        const result = await response.json();
        savedId = result.data?.id?.toString() || numericId || `temp_${Date.now()}`;
      } catch {
        savedId = numericId || `temp_${Date.now()}`;
      }

      const updatedSchedule: CalendarScheduleItem = {
        id: `schedule_${savedId}`,
        title: formData.title,
        startDate: formData.startDate,
        endDate: formData.endDate,
        startTime: formData.isAllDay ? undefined : formData.startTime,
        endTime: formData.isAllDay ? undefined : formData.endTime,
        isAllDay: formData.isAllDay,
        type: 'schedule',
        department: formData.department !== 'all' ? formData.department : undefined,
        color: formData.color,
      };

      // Optimistic update: loading 변화 없이 데이터만 갱신 → 캘린더만 리렌더
      calendarData.setData((prev) => {
        if (!prev) return { items: [updatedSchedule], totalCount: 1 };
        if (numericId) {
          // 수정: 기존 항목 교체
          return {
            ...prev,
            items: prev.items.map((item) =>
              item.id === rawId ? updatedSchedule : item
            ),
          };
        }
        // 신규: 추가
        return {
          ...prev,
          items: [...prev.items, updatedSchedule],
          totalCount: prev.totalCount + 1,
        };
      });
    } catch {
      // 에러 시 서버 데이터로 동기화
      calendarData.refetch();
    } finally {
      setIsScheduleModalOpen(false);
      setSelectedSchedule(null);
    }
  }, [selectedSchedule, calendarData]);

  // 일정 삭제 (optimistic update)
  const handleScheduleDelete = useCallback(async (id: string) => {
    try {
      // schedule_ 접두사에서 실제 ID 추출
      const numericId = id.startsWith('schedule_') ? id.replace('schedule_', '') : id;

      const response = await fetch(`/api/proxy/calendar/schedules/${numericId}`, {
        method: 'DELETE',
      });

      if (!response.ok) throw new Error('Failed to delete schedule');

      // Optimistic update: 삭제된 항목만 제거 → 캘린더만 리렌더
      calendarData.setData((prev) => {
        if (!prev) return prev;
        return {
          ...prev,
          items: prev.items.filter((item) => item.id !== id),
          totalCount: Math.max(0, prev.totalCount - 1),
        };
      });
    } catch {
      // 에러 시 서버 데이터로 동기화
      calendarData.refetch();
    } finally {
      setIsScheduleModalOpen(false);
      setSelectedSchedule(null);
    }
  }, [calendarData]);

  // 섹션 순서 (모듈 비활성 섹션 필터링)
  const sectionOrder = useMemo(() => {
    const rawOrder = dashboardSettings.sectionOrder ?? DEFAULT_SECTION_ORDER;
    if (!moduleAware) return rawOrder; // industry 미설정 시 전부 표시
    return rawOrder.filter((key) => {
      const requiredModule = sectionRequiresModule(key);
      if (!requiredModule) return true; // 공통 섹션
      return isEnabled(requiredModule);
    });
  }, [dashboardSettings.sectionOrder, moduleAware, isEnabled]);

  // 요약 네비게이션 바 훅
  const { summaries, activeSectionKey, sectionRefs, scrollToSection } = useSectionSummary({
    data,
    sectionOrder,
    dashboardSettings,
  });

  // 섹션 ref 수집 콜백
  const setSectionRef = useCallback(
    (key: SectionKey): RefCallback<HTMLDivElement> =>
      (el) => {
        if (el) {
          sectionRefs.current.set(key, el);
        } else {
          sectionRefs.current.delete(key);
        }
      },
    [sectionRefs],
  );

  // 섹션 렌더링 함수
  const renderDashboardSection = (key: SectionKey): React.ReactNode => {
    switch (key) {
      case 'todayIssueList':
        if (!dashboardSettings.todayIssueList) return null;
        return (
          <LazySection key={key}>
            <TodayIssueSection items={data.todayIssueList} />
          </LazySection>
        );

      case 'dailyReport':
        if (!dashboardSettings.dailyReport || !data.dailyReport) return null;
        return (
          <LazySection key={key}>
            <EnhancedDailyReportSection
              data={data.dailyReport}
              onClick={handleDailyReportClick}
              onExpenseDetailClick={() => handleMonthlyExpenseCardClick('me4')}
            />
          </LazySection>
        );

      case 'statusBoard':
        if (!(dashboardSettings.statusBoard?.enabled ?? dashboardSettings.todayIssue.enabled)) return null;
        return (
          <LazySection key={key}>
            <EnhancedStatusBoardSection
              items={data.todayIssue}
              itemSettings={dashboardSettings.statusBoard?.items ?? dashboardSettings.todayIssue.items}
            />
          </LazySection>
        );

      case 'monthlyExpense':
        if (!dashboardSettings.monthlyExpense || !data.monthlyExpense) return null;
        return (
          <LazySection key={key}>
            <EnhancedMonthlyExpenseSection
              data={data.monthlyExpense}
              onCardClick={handleMonthlyExpenseCardClick}
            />
          </LazySection>
        );

      case 'cardManagement':
        if (!dashboardSettings.cardManagement || !data.cardManagement) return null;
        return (
          <LazySection key={key}>
            <CardManagementSection
              data={data.cardManagement}
              onCardClick={handleCardManagementCardClick}
            />
          </LazySection>
        );

      case 'entertainment':
        if (!dashboardSettings.entertainment.enabled || !data.entertainment) return null;
        return (
          <LazySection key={key}>
            <EntertainmentSection
              data={data.entertainment}
              onCardClick={handleEntertainmentCardClick}
            />
          </LazySection>
        );

      case 'welfare':
        if (!dashboardSettings.welfare.enabled || !data.welfare) return null;
        return (
          <LazySection key={key}>
            <WelfareSection
              data={data.welfare}
              onCardClick={handleWelfareCardClick}
            />
          </LazySection>
        );

      case 'receivable':
        if (!dashboardSettings.receivable || !data.receivable) return null;
        return (
          <LazySection key={key}>
            <ReceivableSection data={data.receivable} />
          </LazySection>
        );

      case 'debtCollection':
        if (!dashboardSettings.debtCollection || !data.debtCollection) return null;
        return (
          <LazySection key={key}>
            <DebtCollectionSection data={data.debtCollection} />
          </LazySection>
        );

      case 'vat':
        if (!dashboardSettings.vat || !data.vat) return null;
        return (
          <LazySection key={key}>
            <VatSection data={data.vat} onClick={handleVatClick} />
          </LazySection>
        );

      case 'calendar':
        if (!dashboardSettings.calendar || !data.calendarSchedules) return null;
        return (
          <LazySection key={key} minHeight={500}>
            <CalendarSection
              schedules={data.calendarSchedules}
              issues={data.todayIssueList}
              onScheduleClick={handleScheduleClick}
              onScheduleEdit={handleScheduleEdit}
            />
          </LazySection>
        );

      case 'salesStatus':
        if (!(dashboardSettings.salesStatus ?? true) || !data.salesStatus) return null;
        return (
          <LazySection key={key} minHeight={600}>
            <SalesStatusSection data={data.salesStatus} />
          </LazySection>
        );

      case 'purchaseStatus':
        if (!(dashboardSettings.purchaseStatus ?? true) || !data.purchaseStatus) return null;
        return (
          <LazySection key={key} minHeight={600}>
            <PurchaseStatusSection data={data.purchaseStatus} />
          </LazySection>
        );

      case 'production':
        if (!(dashboardSettings.production ?? true) || !data.dailyProduction) return null;
        return (
          <LazySection key={key} minHeight={400}>
            <DailyProductionSection
              data={data.dailyProduction}
              showShipment={false}
            />
          </LazySection>
        );

      case 'shipment':
        if (!(dashboardSettings.shipment ?? true) || !data.dailyProduction) return null;
        return (
          <LazySection key={key}>
            <ShipmentSection data={data.dailyProduction} />
          </LazySection>
        );

      case 'unshipped':
        if (!(dashboardSettings.unshipped ?? true) || !data.unshipped) return null;
        return (
          <LazySection key={key}>
            <UnshippedSection data={data.unshipped} />
          </LazySection>
        );

      case 'construction':
        if (!(dashboardSettings.construction ?? true) || !data.constructionData) return null;
        return (
          <LazySection key={key}>
            <ConstructionSection data={data.constructionData} />
          </LazySection>
        );

      case 'attendance':
        if (!(dashboardSettings.attendance ?? true) || !data.dailyAttendance) return null;
        return (
          <LazySection key={key}>
            <DailyAttendanceSection data={data.dailyAttendance} />
          </LazySection>
        );

      default:
        return null;
    }
  };

  if (isLoading) {
    return (
      <PageLayout>
        <PageHeader
          title="대시보드"
          description="전체 현황을 조회합니다."
          icon={LayoutDashboard}
        />
        <CEODashboardSkeleton />
      </PageLayout>
    );
  }

  return (
    <PageLayout>
      <PageHeader
        title="대시보드"
        description="전체 현황을 조회합니다."
        icon={LayoutDashboard}
        actions={
          <>
            <Button
              variant="outline"
              size="sm"
              onClick={handleSettingClick}
              className="gap-2"
            >
              <Settings className="h-4 w-4" />
              항목 설정
            </Button>
            <DashboardSwitcher />
          </>
        }
      />

      <SummaryNavBar
        summaries={summaries}
        activeSectionKey={activeSectionKey}
        onChipClick={scrollToSection}
      />

      <div className="space-y-6">
        {sectionOrder.map((key) => {
          const node = renderDashboardSection(key);
          if (!node) return null;
          return (
            <div key={key} ref={setSectionRef(key)} data-section-key={key}>
              {node}
            </div>
          );
        })}
      </div>

      {/* 일정 상세 모달 — schedule_ 접두사만 수정/삭제 가능 */}
      <ScheduleDetailModal
        isOpen={isScheduleModalOpen}
        onClose={handleScheduleModalClose}
        schedule={selectedSchedule}
        onSave={handleScheduleSave}
        onDelete={handleScheduleDelete}
        isEditable={!selectedSchedule?.id || selectedSchedule.id === '' || selectedSchedule.id.startsWith('schedule_')}
      />

      {/* 항목 설정 모달 */}
      <DashboardSettingsDialog
        isOpen={isSettingsModalOpen}
        onClose={handleSettingsModalClose}
        settings={dashboardSettings}
        onSave={handleSettingsSave}
      />

      {/* 상세 모달 */}
      {detailModalConfig && (
        <DetailModal
          isOpen={isDetailModalOpen}
          onClose={handleDetailModalClose}
          config={detailModalConfig}
          onDateFilterChange={handleDateFilterChange}
          onRowClick={handleModalRowClick}
        />
      )}
    </PageLayout>
  );
}