import React from 'react';
import { Navigate, Outlet, Route, Routes, useNavigate } from 'react-router-dom';
import { authApi } from './api/endpoints';
import { useAuthStore } from './store/authStore';
import { landingPathFor } from './lib/roleTrack';
import { LoginPage } from './screens/login/LoginPage';
import { OtpSetupPage } from './screens/login/OtpSetupPage';
import { BoothLayoutEditorPage } from './screens/floorplan/BoothLayoutEditorPage';
import { LayoutComparisonPage } from './screens/floorplan/LayoutComparisonPage';
import { OrganizerDashboardPage } from './screens/dashboard/OrganizerDashboardPage';
import { ExhibitorHomePage } from './screens/exhibitor/ExhibitorHomePage';
import { ExhibitorsPage } from './screens/exhibitors/ExhibitorsPage';
import { BoothDesignStudioPage } from './screens/design/BoothDesignStudioPage';
import { UtilityWiringPage } from './screens/utility/UtilityWiringPage';
import { UtilityOrderSummaryPage } from './screens/utility/UtilityOrderSummaryPage';
import { ComplianceReportPage } from './screens/compliance/ComplianceReportPage';
import { ManagerApprovalQueuePage } from './screens/approval/ManagerApprovalQueuePage';
import { ReviewDetailsPage } from './screens/approval/ReviewDetailsPage';
import { HomePage } from './screens/home/HomePage';
import { BoothSalesPage } from './screens/boothsales/BoothSalesPage';
import { AppQrCodePage } from './screens/appqr/AppQrCodePage';
import { DeptAdminPage } from './screens/admin/DeptAdminPage';
import { CompanyAdminPage } from './screens/admin/CompanyAdminPage';
import { ProgramAdminPage } from './screens/admin/ProgramAdminPage';
import { RoleMenuAdminPage } from './screens/admin/RoleMenuAdminPage';
import { AuthPolicyPage } from './screens/admin/AuthPolicyPage';
import { LoginHistoryPage } from './screens/admin/LoginHistoryPage';
import { ErrorLogPage } from './screens/admin/ErrorLogPage';
import { SystemHealthPage } from './screens/admin/SystemHealthPage';
import { MailConfigPage, NotifyConfigPage } from './screens/admin/InfraConfigPage';
import { HolidayAdminPage } from './screens/admin/HolidayAdminPage';
import { VisualizationGalleryPage } from './screens/gallery/VisualizationGalleryPage';
import { AnalyticsDashboardPage } from './screens/analytics/AnalyticsDashboardPage';
import { HallOperationsPage } from './screens/ops/HallOperationsPage';
import { ExhibitionSchedulePage } from './screens/schedule/ExhibitionSchedulePage';
import { AdminDashboardPage } from './screens/admin/AdminDashboardPage';
import { LoginSlideAdminPage } from './screens/admin/LoginSlideAdminPage';
import { ComponentGuidePage } from './screens/styleguide/ComponentGuidePage';
import { ContractorOnsiteChecklistPage } from './screens/mobile/ContractorOnsiteChecklistPage';
import { ManagerFieldInspectionPage } from './screens/mobile/ManagerFieldInspectionPage';
import { WorklogPage } from './screens/work/WorklogPage';
import { WorkSchedulePage } from './screens/work/WorkSchedulePage';
import { MessagePage } from './screens/work/MessagePage';
import { NoticePage } from './screens/work/NoticePage';
import { OpinionPage } from './screens/work/OpinionPage';
import { SearchPage } from './screens/work/SearchPage';
import { MeetingPage } from './screens/work/MeetingPage';
import { ReportPage } from './screens/work/ReportPage';
import { NotificationCenterPage } from './screens/work/NotificationCenterPage';
import { MyPage } from './screens/work/MyPage';
import { DocsMilestonePage } from './screens/docs/DocsMilestonePage';
import { ReportAuthoringPage } from './screens/docs/ReportAuthoringPage';
import { DockReservationPage } from './screens/movein/DockReservationPage';
import { AuctionListPage } from './screens/auction/AuctionListPage';
import { AuctionDetailPage } from './screens/auction/AuctionDetailPage';
import { AwardComparePage } from './screens/auction/AwardComparePage';
import { ContractorBoothDashboardPage } from './screens/contractor/ContractorBoothDashboardPage';
import { VisitorRegistrationDashboardPage } from './screens/visitor/VisitorRegistrationDashboardPage';
import { LeadScoringPage } from './screens/visitor/LeadScoringPage';
import { CheckinDeskPage } from './screens/visitor/CheckinDeskPage';
import { EdmCampaignPage } from './screens/marketing/EdmCampaignPage';
import { SponsorshipPage } from './screens/marketing/SponsorshipPage';
import { CmsWorkflowPage } from './screens/cms/CmsWorkflowPage';
import { MicrositeBuilderPage } from './screens/cms/MicrositeBuilderPage';
import { MultilingualCmsPage } from './screens/cms/MultilingualCmsPage';
import { AuditLogPage } from './screens/admin/AuditLogPage';
import { SystemSettingsPage } from './screens/admin/SystemSettingsPage';
import { RulesetVersionsPage } from './screens/admin/RulesetVersionsPage';
import { TenantAdminPage } from './screens/admin/TenantAdminPage';
import { AdminGuard } from './screens/admin/AdminGuard';
import { SettlementDashboardPage } from './screens/settlement/SettlementDashboardPage';
import { HallAssignmentPage } from './screens/hallassign/HallAssignmentPage';
import { SysUserAdminPage } from './screens/admin/SysUserAdminPage';
import { RoleAdminPage } from './screens/admin/RoleAdminPage';
import { CommonCodeAdminPage } from './screens/admin/CommonCodeAdminPage';
import { MenuAdminPage } from './screens/admin/MenuAdminPage';
import { MessageAdminPage } from './screens/admin/MessageAdminPage';
import {
  PublicGatewayPage,
  VisitorTrackPage,
  BusinessTrackPage,
  AgencyTrackPage,
  PublicHomePage,
  PublicEventDetailPage,
  PublicFloorplanPage,
  PublicRegistrationPage,
  PublicMicrositePage,
  PublicInquiryPage,
  PublicTicketPage,
} from './screens/public';
import { NotFoundPage } from './screens/common/NotFoundPage';
import { AppShell } from './components/layout/AppShell';

/** SCR-22 → SCR-23 작성 화면 진입 배선. */
function DocsMilestoneRoute() {
  const navigate = useNavigate();
  return <DocsMilestonePage onOpenAuthoring={() => navigate('/docs/authoring')} />;
}

/**
 * 인증 가드 — 미인증 시 로그인으로. (역할별 라우팅은 화면 추가 시 확장)
 * 새로고침 재수화: 토큰(sessionStorage)은 살아있는데 스토어가 빈 상태(user=null·workspaces=[])면
 * /api/auth/me + /api/auth/workspaces 로 복원한다 — 없으면 행사스코프 화면 전체가
 * "행사를 선택해 주세요"로 깨진다(2026-07-14 소유자 제보). 401이면 토큰 무효 → 로그아웃.
 */
function RequireAuth({ children }: { children: React.ReactNode }) {
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const user = useAuthStore((s) => s.user);
  const applySession = useAuthStore((s) => s.applySession);
  const logout = useAuthStore((s) => s.logout);
  const needsHydration = isAuthenticated && user == null;

  React.useEffect(() => {
    if (!needsHydration) return;
    let cancelled = false;
    void Promise.all([authApi.me(), authApi.workspaces()])
      .then(([me, workspaces]) => {
        if (cancelled) return;
        applySession(
          {
            userId: me.userId,
            displayName: me.displayName,
            hallManager: me.hallManager,
            roleCode: me.roleCode ?? null,
          },
          workspaces,
        );
      })
      .catch(() => {
        if (!cancelled) logout();
      });
    return () => {
      cancelled = true;
    };
  }, [needsHydration, applySession, logout]);

  if (!isAuthenticated) return <Navigate to="/login" replace />;
  if (needsHydration) return null; // 복원 완료까지 렌더 보류(빈 workspaces로 화면 오판 방지)
  return <>{children}</>;
}

/**
 * 루트/미매칭 분기 — 인증=역할별 랜딩 리다이렉트, 미인증=SCR-T0 3-트랙 공개 관문 직접 렌더
 * (design.md §3C-0: 미인증 `/`는 대외 유입 관문. 2026-07-12 소유자 지적 반영).
 * 인증 시 랜딩은 completeLogin 과 동일 규칙(plan_role_routing §2-1) — ops·business=/home(회귀 0),
 * admin→/admin, agency→/contractor/dashboard, visitor→/visitor. 로그인 직후·`/`·catch-all 일관.
 */
function RootGate() {
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const user = useAuthStore((s) => s.user);
  const workspaces = useAuthStore((s) => s.workspaces);
  if (isAuthenticated) return <Navigate to={landingPathFor(user, workspaces)} replace />;
  return <PublicGatewayPage />;
}

export function App() {
  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      {/* 2차 인증(OTP) 관리 — 인증 필요, 셸 없이 단독 카드. */}
      <Route
        path="/otp-setup"
        element={
          <RequireAuth>
            <OtpSetupPage />
          </RequireAuth>
        }
      />

      {/* 인증 필요 — 사이드바 셸 안 (데스크톱 1440) */}
      <Route
        element={
          <RequireAuth>
            <AppShell />
          </RequireAuth>
        }
      >
        {/* SCR-02 주최자 대시보드 */}
        <Route path="/events/:eventId/dashboard" element={<OrganizerDashboardPage />} />
        {/* SCR-05 참가업체 홈 */}
        <Route path="/events/:eventId/booths/:boothId/home" element={<ExhibitorHomePage />} />
        {/* #41 주최자용 참가업체 관리(전용 화면 — 대시보드 폴백 해소) */}
        <Route path="/exhibitors" element={<ExhibitorsPage />} />
        {/* SCR-03 부스 배치 에디터 (M2) */}
        <Route
          path="/events/:eventId/halls/:hallId/layout"
          element={<BoothLayoutEditorPage />}
        />
        {/* SCR-04 AI 배치안 비교 */}
        <Route
          path="/events/:eventId/halls/:hallId/comparison"
          element={<LayoutComparisonPage />}
        />
        {/* SCR-06 부스 설계 스튜디오 (M3+M5) */}
        <Route path="/events/:eventId/booths/:boothId/design" element={<BoothDesignStudioPage />} />
        {/* SCR-07 유틸리티 배선 뷰 (M4a+M4b) */}
        <Route path="/events/:eventId/booths/:boothId/utility" element={<UtilityWiringPage />} />
        {/* SCR-08 유틸리티 신청 요약 */}
        <Route
          path="/events/:eventId/booths/:boothId/utility/order"
          element={<UtilityOrderSummaryPage />}
        />
        {/* SCR-09 규정 검증 결과 */}
        <Route
          path="/events/:eventId/booths/:boothId/compliance"
          element={<ComplianceReportPage />}
        />
        {/* SCR-10 검수 대기열 (홀매니저) */}
        <Route
          path="/events/:eventId/halls/:hallId/approvals"
          element={<ManagerApprovalQueuePage />}
        />
        {/* SCR-11 검수 상세 */}
        <Route
          path="/events/:eventId/halls/:hallId/booths/:booth/review"
          element={<ReviewDetailsPage />}
        />
        {/* SCR-12 시각화 갤러리 (M5) */}
        <Route
          path="/events/:eventId/booths/:boothId/gallery"
          element={<VisualizationGalleryPage />}
        />
        {/* SCR-13 경영분석 대시보드 (M16 BI · 테넌트 전역) */}
        <Route path="/analytics" element={<AnalyticsDashboardPage />} />
        {/* SCR-14 홀 현장운영 대시보드 (M14) */}
        <Route path="/ops/operations" element={<HallOperationsPage />} />
        {/* SCR-HOME 메인 홈(로그인 후 랜딩) — design.md v2.1.2 확정판 */}
        <Route path="/home" element={<HomePage />} />
        {/* F005/F006 부스 판매(셀프 선택) */}
        <Route path="/booth-sales" element={<BoothSalesPage />} />
        {/* 모바일 앱 설치 QR (WISE AppQrCode 패턴) */}
        <Route path="/app-qr" element={<AppQrCodePage />} />
        {/* §5B 전자결재 결재함(F028) — 홈 내 할 일 route 정합(/work/approval) */}
        <Route path="/work/approval" element={<ManagerApprovalQueuePage />} />
        {/* SCR-15 전시 일정 관리 (M1·M6) */}
        <Route path="/schedule" element={<ExhibitionSchedulePage />} />
        {/* M9 정산 대시보드 · M1 홀 배정+자동견적 */}
        <Route path="/settlement" element={<SettlementDashboardPage />} />
        <Route path="/halls" element={<HallAssignmentPage />} />
        {/* SCR-16 관리자 대시보드 (M18 랜딩) */}
        <Route path="/admin" element={<AdminGuard><AdminDashboardPage /></AdminGuard>} />
        {/* 관리자 — 로그인 슬라이드 관리 (M18) */}
        <Route path="/admin/login-slides" element={<AdminGuard><LoginSlideAdminPage /></AdminGuard>} />
        {/* SCR-17 컴포넌트 가이드 (내부 전용 · 네비 비노출) */}
        {import.meta.env.DEV && <Route path="/_styleguide" element={<ComponentGuidePage />} />}

        {/* §5B 공통 업무 기능 (SCR-39~48) — 역할 공통 영역 */}
        <Route path="/work/worklog" element={<WorklogPage />} />
        <Route path="/work/schedule" element={<WorkSchedulePage />} />
        <Route path="/work/message" element={<MessagePage />} />
        <Route path="/work/notice" element={<NoticePage />} />
        <Route path="/work/opinion" element={<OpinionPage />} />
        <Route path="/work/search" element={<SearchPage />} />
        <Route path="/work/meeting" element={<MeetingPage />} />
        <Route path="/work/report" element={<ReportPage />} />
        {/* SCR-47 알림센터 · SCR-48 마이페이지 */}
        <Route path="/notifications" element={<NotificationCenterPage />} />
        <Route path="/me" element={<MyPage />} />

        {/* SCR-22·23 서류·마일스톤 / 신고서류 작성 (M6 — 샘플) */}
        <Route path="/docs" element={<DocsMilestoneRoute />} />
        <Route path="/docs/authoring" element={<ReportAuthoringPage />} />
        {/* SCR-25 반입/반출 도크 슬롯 예약 (M8 — 샘플) */}
        <Route path="/logistics" element={<DockReservationPage />} />
        {/* SCR-26·27·29 공사/장치 옥션 (M15 — 샘플) · SCR-38 수주 부스 대시보드 */}
        <Route path="/auctions" element={<AuctionListPage />} />
        <Route path="/auctions/:auctionId" element={<AuctionDetailPage />} />
        <Route path="/auctions/:auctionId/award" element={<AwardComparePage />} />
        <Route path="/contractor/dashboard" element={<ContractorBoothDashboardPage />} />
        {/* SCR-30·32 관람객·리드 (M10 — 샘플) · SCR-33·34 마케팅 (M12 — 샘플) */}
        <Route path="/visitors" element={<VisitorRegistrationDashboardPage />} />
        <Route path="/visitors/checkin" element={<CheckinDeskPage />} />
        <Route path="/leads" element={<LeadScoringPage />} />
        <Route path="/campaigns" element={<EdmCampaignPage />} />
        <Route path="/sponsorship" element={<SponsorshipPage />} />
        {/* SCR-35~37 CMS (M17 — 샘플) */}
        <Route path="/cms" element={<CmsWorkflowPage />} />
        <Route path="/cms/microsite" element={<MicrositeBuilderPage />} />
        <Route path="/cms/i18n" element={<MultilingualCmsPage />} />
        {/* SCR-A5~A9 관리자 모듈 (감사로그·설정·룰셋=실배선, 테넌트=샘플) — AdminGuard 가드 */}
        <Route path="/admin/audit" element={<AdminGuard><AuditLogPage /></AdminGuard>} />
        <Route path="/admin/settings" element={<AdminGuard><SystemSettingsPage /></AdminGuard>} />
        <Route path="/admin/masterdata/rulesets" element={<AdminGuard><RulesetVersionsPage /></AdminGuard>} />
        <Route path="/admin/tenants" element={<AdminGuard><TenantAdminPage /></AdminGuard>} />
        {/* M18 시스템관리 CRUD (백엔드 system 패키지 라이브) — AdminGuard 가드 */}
        <Route path="/admin/users" element={<AdminGuard><SysUserAdminPage /></AdminGuard>} />
        <Route path="/admin/roles" element={<AdminGuard><RoleAdminPage /></AdminGuard>} />
        <Route path="/admin/codes" element={<AdminGuard><CommonCodeAdminPage /></AdminGuard>} />
        <Route path="/admin/menus" element={<AdminGuard><MenuAdminPage /></AdminGuard>} />
        {/* W12 WISE 시스템관리 기본기 8종 (V37) */}
        <Route path="/admin/depts" element={<AdminGuard><DeptAdminPage /></AdminGuard>} />
        <Route path="/admin/companies" element={<AdminGuard><CompanyAdminPage /></AdminGuard>} />
        <Route path="/admin/programs" element={<AdminGuard><ProgramAdminPage /></AdminGuard>} />
        <Route path="/admin/role-menus" element={<AdminGuard><RoleMenuAdminPage /></AdminGuard>} />
        <Route path="/admin/auth-policy" element={<AdminGuard><AuthPolicyPage /></AdminGuard>} />
        <Route path="/admin/login-history" element={<AdminGuard><LoginHistoryPage /></AdminGuard>} />
        <Route path="/admin/error-log" element={<AdminGuard><ErrorLogPage /></AdminGuard>} />
        <Route path="/admin/system-health" element={<AdminGuard><SystemHealthPage /></AdminGuard>} />
        <Route path="/admin/mail-config" element={<AdminGuard><MailConfigPage /></AdminGuard>} />
        <Route path="/admin/notify-config" element={<AdminGuard><NotifyConfigPage /></AdminGuard>} />
        <Route path="/admin/messages" element={<AdminGuard><MessageAdminPage /></AdminGuard>} />
        <Route path="/admin/holidays" element={<AdminGuard><HolidayAdminPage /></AdminGuard>} />
      </Route>

      {/* SCR-T1~T3 트랙 서브홈 — 비로그인 공개, PublicShell+TrackSwitcher */}
      <Route path="/visitor" element={<VisitorTrackPage />} />
      <Route path="/business" element={<BusinessTrackPage />} />
      <Route path="/agency" element={<AgencyTrackPage />} />

      {/* SCR-P1~P7 공개 홍보 사이트 — 비로그인, 자체 PublicShell */}
      <Route path="/public" element={<PublicHomePage />} />
      <Route path="/public/events/:eventId" element={<PublicEventDetailPage />} />
      <Route path="/public/events/:eventId/floorplan" element={<PublicFloorplanPage />} />
      <Route path="/public/events/:eventId/register" element={<PublicRegistrationPage />} />
      <Route path="/public/exhibitors/:exhibitorId" element={<PublicMicrositePage />} />
      <Route path="/public/exhibit-inquiry" element={<PublicInquiryPage />} />
      <Route path="/tickets/:eventId/purchase" element={<PublicTicketPage />} />
      <Route path="/tickets/lookup" element={<PublicTicketPage />} />

      {/* 모바일 전용 (390) — 셸 없이 전폭, 조회·현장 */}
      <Route
        element={
          <RequireAuth>
            <Outlet />
          </RequireAuth>
        }
      >
        {/* SCR-M1 장치업체 현장 체크리스트 */}
        <Route path="/m/booths/:boothId/checklist" element={<ContractorOnsiteChecklistPage />} />
        {/* SCR-M2 홀매니저 현장 검수 */}
        <Route path="/m/booths/:boothId/inspection" element={<ManagerFieldInspectionPage />} />
      </Route>

      <Route path="/" element={<RootGate />} />
      {/* 404 — 미매칭 경로(공개·인증 공통, 셸 비의존 전폭 카드 · 4.4) */}
      <Route path="*" element={<NotFoundPage />} />
    </Routes>
  );
}
