'use client'; import React, { useEffect, useMemo, useState } from 'react'; import Link from 'next/link'; import { usePathname, useRouter } from 'next/navigation'; import { BRAND_NAME, ROUTES, WORKSPACE_TABS, } from '@/shared/constants'; import { normalizePath } from '@/shared/lib/format'; import { useToast } from '@/shared/hooks/useToast'; import { BrandLogoMark, EmptyZoneGlyph } from '@/shared/components/BrandGlyphs'; import { Button } from '@/shared/components/Button'; import { Input, Select } from '@/shared/components/Input'; import { ConfirmModal, Modal } from '@/shared/components/Modal'; import { ThemeSelector } from '@/shared/components/ThemeSelector'; import { AuthDialog, useAuthSession } from '@/features/auth'; import { FileCode, Folder, Layers, LogOut, Menu, Plus, Radio, Search, Shield, Terminal, Trash2, X, } from 'lucide-react'; import { validateZoneInput } from '../schemas/workspaceSchema'; import { workspaceService } from '../services/workspaceService'; import { useWorkspaceStore } from '../hooks/useWorkspaceStore'; import { WorkspaceOwnerOption, Zone } from '../types/workspaceTypes'; const TAB_ICONS = { files: Folder, editor: FileCode, terminal: Terminal, ports: Radio, } as const; export function WorkspaceShell({ children }: { children: React.ReactNode }) { const pathname = usePathname() || ROUTES.PANEL_FILES; const activePath = normalizePath(pathname); const router = useRouter(); const { pushToast } = useToast(); const { user, authLoading, publicConfig, motdDismissed, dismissMotd, logout } = useAuthSession(); const { zones, activeZone, selectZone, createZone, deleteZone, sidebarOpen, setSidebarOpen, editorTabs, openPalette, } = useWorkspaceStore(); const [zoneSearch, setZoneSearch] = useState(''); const [createOpen, setCreateOpen] = useState(false); const [newName, setNewName] = useState(''); const [newDesc, setNewDesc] = useState(''); const [ownerId, setOwnerId] = useState(''); const [owners, setOwners] = useState([]); const [createError, setCreateError] = useState(''); const [creating, setCreating] = useState(false); const [deleteTarget, setDeleteTarget] = useState(null); const [deleting, setDeleting] = useState(false); const isAdmin = user?.role === 'admin'; const isAdminRoute = activePath.startsWith('/panel/admin'); const maxZones = publicConfig.max_zones || 0; useEffect(() => { if (!createOpen || !isAdmin) return; workspaceService .listOwnerOptions() .then((list) => setOwners(list || [])) .catch(() => {}); }, [createOpen, isAdmin]); const filteredZones = useMemo(() => { const q = zoneSearch.trim().toLowerCase(); if (!q) return zones; return zones.filter( (z) => z.name.toLowerCase().includes(q) || (z.description && z.description.toLowerCase().includes(q)) || (z.owner_name && z.owner_name.toLowerCase().includes(q)), ); }, [zones, zoneSearch]); const groupedZones = useMemo(() => { const map = new Map(); for (const z of filteredZones) { const key = z.owner_id || 'self'; const label = z.owner_name || user?.username || 'Cá nhân'; const existing = map.get(key); if (existing) existing.items.push(z); else map.set(key, { label, items: [z] }); } return Array.from(map.values()); }, [filteredZones, user?.username]); const openCreateModal = () => { setNewName(''); setNewDesc(''); setOwnerId(user?.id || ''); setCreateError(''); setCreateOpen(true); }; const handleCreateSubmit = async (e: React.FormEvent) => { e.preventDefault(); setCreateError(''); const check = validateZoneInput(newName, newDesc); if (!check.ok || !check.data) { setCreateError(check.error || 'Tên zone không hợp lệ.'); return; } setCreating(true); try { await createZone(check.data.name, check.data.description, isAdmin ? ownerId : undefined); setCreateOpen(false); pushToast(`Đã tạo zone "${check.data.name}"`, 'success'); if (isAdminRoute) router.push(ROUTES.PANEL_FILES); } catch (err: unknown) { setCreateError(err instanceof Error ? err.message : 'Không thể tạo zone'); } finally { setCreating(false); } }; const handleConfirmDelete = async () => { if (!deleteTarget) return; setDeleting(true); try { await deleteZone(deleteTarget); pushToast(`Đã xoá zone "${deleteTarget}"`, 'success'); setDeleteTarget(null); } catch (err: unknown) { pushToast(err instanceof Error ? err.message : 'Không thể xoá zone', 'error'); } finally { setDeleting(false); } }; if (authLoading) { return (
); } if (!user) { return (
router.push(ROUTES.HOME)} />
); } const motdText = publicConfig.motd && !motdDismissed ? publicConfig.motd : ''; return (
{motdText && (
{motdText}
)}
{sidebarOpen && (
setSidebarOpen(false)} className="fixed inset-0 z-40 bg-black/65 backdrop-blur-sm lg:hidden" aria-hidden="true" /> )}
{activeZone ? (
{activeZone}
) : ( Chưa chọn zone )}
{(activeZone || isAdmin) && ( )}
{!activeZone && !isAdminRoute ? (

Chưa có Zone nào được chọn

Tạo một Zone mới để bắt đầu quản lý tệp, chỉnh sửa mã nguồn, chạy Terminal PTY và mở cổng Reverse Proxy.

) : ( children )}
setCreateOpen(false)} title="Tạo Zone làm việc mới">
{createError && (

{createError}

)} setNewName(e.target.value)} placeholder="vd: web-api, discord-bot" helperText="Chỉ gồm chữ, số, _ hoặc - (1–50 ký tự)" /> setNewDesc(e.target.value)} placeholder="Dự án Node.js / Python / Go..." /> {isAdmin && owners.length > 0 && ( )}
setDeleteTarget(null)} onConfirm={handleConfirmDelete} title="Xoá Zone" description={`Toàn bộ mã nguồn, cấu hình cổng và log trong zone "${deleteTarget}" sẽ bị xoá vĩnh viễn.`} confirmLabel="Xoá vĩnh viễn" danger loading={deleting} />
); }