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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
"use client";

import React, { useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  CloudUpload,
  UploadCloud,
  Search,
  RefreshCw,
  Folder,
  Film,
  Image as ImageIcon,
  Archive,
  FileCode2,
  Shield,
  LogOut,
  BarChart3,
  Terminal,
  Activity,
  X,
  Lock,
  ArrowRight,
  Share2,
} from "lucide-react";
import { useCloud } from "@/context/CloudContext";
import { formatBytes } from "@/lib/api";
import { GlobalModals } from "@/components/GlobalModals";

export function WorkspaceShell({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [isDraggingOver, setIsDraggingOver] = useState(false);

  const {
    token,
    currentUser,
    authLoading,
    healthOk,
    isAdmin,
    canUpload,
    files,
    loadingFiles,
    currentFolder,
    categoryFilter,
    setCategoryFilter,
    searchQuery,
    setSearchQuery,
    stats,
    loadFiles,
    setUploadModalOpen,
    setUploadTargetFolder,
    setSelectedFiles,
    uploadQueue,
    sharesMap,
    pendingRequestsCount,
    setShareTarget,
    usersList,
    handleLogout,
    notify,
  } = useCloud();

  if (authLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-grid-pattern">
        <div className="glass-panel rounded-3xl p-10 flex flex-col items-center gap-4 border border-white/10">
          <div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-indigo-500 via-purple-500 to-amber-500 p-[1px] animate-pulse">
            <div className="w-full h-full bg-slate-950 rounded-[15px] flex items-center justify-center">
              <CloudUpload className="w-7 h-7 text-indigo-400" />
            </div>
          </div>
          <div className="text-center">
            <p className="text-sm font-bold text-white tracking-wide">UPLOAD THTUANIT</p>
            <p className="text-xs text-slate-400 font-mono mt-1">Đang đồng bộ phiên làm việc bảo mật...</p>
          </div>
        </div>
      </div>
    );
  }

  if (!currentUser) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-grid-pattern p-6">
        <div className="glass-panel max-w-md w-full rounded-3xl p-8 border border-white/15 text-center space-y-4">
          <div className="w-14 h-14 mx-auto rounded-2xl bg-indigo-500/15 border border-indigo-500/30 flex items-center justify-center text-indigo-400">
            <Lock className="w-7 h-7" />
          </div>
          <h1 className="text-xl font-extrabold text-white">Yêu cầu xác thực Upload ThTuanIT</h1>
          <p className="text-xs text-slate-300 leading-relaxed">
            Vui lòng đăng nhập vào tài khoản Upload ThTuanIT của bạn để truy cập dữ liệu cá nhân hoặc bảng điều khiển Admin.
          </p>
          <div className="flex items-center justify-center gap-3 pt-2">
            <Link
              href="/"
              className="px-4 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 text-xs font-semibold text-slate-300 transition"
            >
              Về trang chủ
            </Link>
            <Link
              href="/login"
              className="px-5 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-xs font-bold text-white shadow-lg shadow-indigo-600/30 transition flex items-center gap-1.5"
            >
              <span>Đăng nhập ngay</span>
              <ArrowRight className="w-4 h-4" />
            </Link>
          </div>
        </div>
      </div>
    );
  }

  const navItems = [
    { href: "/dashboard", label: "Tổng quan hệ thống", icon: <BarChart3 className="w-4 h-4" /> },
    { href: "/explorer", label: "Trình duyệt đám mây", icon: <Folder className="w-4 h-4" />, badge: files.length },
    ...(isAdmin
      ? [
          {
            href: "/admin",
            label: "Quản trị & Phân quyền",
            icon: <Shield className="w-4 h-4 text-amber-400" />,
            badge: usersList.length || undefined,
          },
        ]
      : []),
    { href: "/developers", label: "Tích hợp API & CLI", icon: <Terminal className="w-4 h-4" /> },
    { href: "/activity", label: "Nhật ký hoạt động", icon: <Activity className="w-4 h-4" /> },
  ];

  return (
    <div
      className="min-h-screen flex bg-grid-pattern relative"
      onDragOver={(e) => {
        e.preventDefault();
        if (canUpload) setIsDraggingOver(true);
      }}
      onDragLeave={(e) => {
        if (e.currentTarget.contains(e.relatedTarget as Node)) return;
        setIsDraggingOver(false);
      }}
      onDrop={(e) => {
        e.preventDefault();
        setIsDraggingOver(false);
        if (!canUpload) {
          notify("Tài khoản của bạn không có quyền tải tệp lên", "error");
          return;
        }
        const dropped = Array.from(e.dataTransfer.files || []);
        if (dropped.length > 0) {
          setSelectedFiles(dropped);
          setUploadTargetFolder(currentFolder);
          setUploadModalOpen(true);
        }
      }}
    >
      {/* DRAG & DROP OVERLAY */}
      {isDraggingOver && (
        <div className="fixed inset-0 z-50 bg-indigo-950/80 backdrop-blur-md border-4 border-dashed border-indigo-400 m-4 rounded-3xl flex flex-col items-center justify-center pointer-events-none">
          <UploadCloud className="w-16 h-16 text-indigo-300 animate-bounce mb-3" />
          <h3 className="text-2xl font-extrabold text-white">Thả tệp vào đây để tải lên Upload ThTuanIT</h3>
          <p className="text-sm text-indigo-200 font-mono mt-1">
            Thư mục đích: {currentFolder ? `/${currentFolder}` : "/ (Root)"}
          </p>
        </div>
      )}

      {/* LEFT SIDEBAR NAVIGATION */}
      <aside
        className={`${
          sidebarCollapsed ? "w-20" : "w-72"
        } glass border-r border-white/10 flex flex-col justify-between shrink-0 sticky top-0 h-screen z-30 transition-all duration-200`}
      >
        <div className="p-4 space-y-6 overflow-y-auto">
          {/* Brand Logo */}
          <div className="flex items-center justify-between px-2 pt-1">
            <Link href="/" className="flex items-center gap-3 overflow-hidden">
              <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 via-purple-500 to-amber-500 p-[1px] shrink-0">
                <div className="w-full h-full bg-slate-950 rounded-[11px] flex items-center justify-center text-indigo-400">
                  <CloudUpload className="w-5 h-5" />
                </div>
              </div>
              {!sidebarCollapsed && (
                <div className="min-w-0">
                  <div className="flex items-center gap-1.5">
                    <span className="font-bold text-sm text-white truncate">Upload ThTuanIT</span>
                    <span className="text-[9px] font-mono px-1.5 py-0.5 rounded bg-indigo-500/20 text-indigo-300 border border-indigo-500/30">
                      PRO
                    </span>
                  </div>
                  <p className="text-[11px] text-slate-400 font-mono truncate">ThTuanIT Cloud Storage</p>
                </div>
              )}
            </Link>
            <button
              onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
              className="p-1.5 rounded-lg bg-white/5 hover:bg-white/10 text-slate-400 hover:text-white"
              title="Thu gọn / Mở rộng thanh bên"
            >
              <BarChart3 className="w-4 h-4 rotate-90" />
            </button>
          </div>

          {/* Primary Upload CTA */}
          <div>
            {canUpload ? (
              <button
                onClick={() => {
                  setUploadTargetFolder(currentFolder);
                  setUploadModalOpen(true);
                }}
                className="w-full py-3 px-4 rounded-2xl bg-gradient-to-r from-indigo-600 via-violet-600 to-indigo-600 hover:from-indigo-500 hover:to-violet-500 font-bold text-xs text-white shadow-lg shadow-indigo-600/30 transition flex items-center justify-center gap-2"
              >
                <UploadCloud className="w-4 h-4 shrink-0" />
                {!sidebarCollapsed && <span>Tải tệp lên Cloud</span>}
              </button>
            ) : (
              !sidebarCollapsed && (
                <div className="p-3 rounded-2xl bg-rose-500/10 border border-rose-500/20 flex items-center gap-2 text-xs text-rose-300">
                  <Lock className="w-4 h-4 shrink-0" />
                  <span>Quyền tải lên đang tắt</span>
                </div>
              )
            )}
          </div>

          {/* Primary Route Links */}
          <nav aria-label="Menu Workspace" className="space-y-1">
            {!sidebarCollapsed && (
              <p className="px-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 mb-2">
                Không gian làm việc
              </p>
            )}
            {navItems.map((item) => {
              const active = pathname === item.href || pathname.startsWith(item.href + "/");
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className={`w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-xs font-semibold transition ${
                    active
                      ? "bg-indigo-500/20 text-white border border-indigo-500/40 shadow-sm"
                      : "text-slate-400 hover:bg-white/5 hover:text-slate-200"
                  }`}
                >
                  <div className="flex items-center gap-3">
                    {item.icon}
                    {!sidebarCollapsed && <span>{item.label}</span>}
                  </div>
                  {!sidebarCollapsed && item.badge !== undefined && (
                    <span className="text-[10px] font-mono px-2 py-0.5 rounded-full bg-white/10 text-slate-300">
                      {item.badge}
                    </span>
                  )}
                </Link>
              );
            })}
          </nav>

          {/* Quick Category Filter (Redirects to /explorer) */}
          {!sidebarCollapsed && (
            <div className="space-y-1 pt-2 border-t border-white/10">
              <p className="px-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 mb-2">
                Phân loại thông minh
              </p>
              {[
                { id: "video", label: "Video & Streaming", icon: <Film className="w-4 h-4 text-rose-400" />, count: stats.counts.video },
                { id: "image", label: "Hình ảnh & Đồ họa", icon: <ImageIcon className="w-4 h-4 text-indigo-400" />, count: stats.counts.image },
                { id: "archive", label: "Gói nén & Dataset", icon: <Archive className="w-4 h-4 text-amber-400" />, count: stats.counts.archive },
                { id: "doc", label: "Tài liệu & Mã nguồn", icon: <FileCode2 className="w-4 h-4 text-emerald-400" />, count: stats.counts.doc },
              ].map((cat) => (
                <button
                  key={cat.id}
                  onClick={() => {
                    setCategoryFilter(cat.id as any);
                    if (pathname !== "/explorer") {
                      router.push("/explorer");
                    }
                  }}
                  className={`w-full flex items-center justify-between px-3 py-2 rounded-xl text-xs transition ${
                    pathname === "/explorer" && categoryFilter === cat.id
                      ? "bg-white/10 text-white font-semibold"
                      : "text-slate-400 hover:bg-white/5 hover:text-slate-200"
                  }`}
                >
                  <div className="flex items-center gap-2.5">
                    {cat.icon}
                    <span>{cat.label}</span>
                  </div>
                  <span className="text-[11px] font-mono text-slate-400">{cat.count}</span>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Bottom Storage Widget & User Card */}
        <div className="p-4 border-t border-white/10 space-y-3 bg-slate-950/50">
          {!sidebarCollapsed && (
            <div className="p-3.5 rounded-2xl bg-slate-900/90 border border-white/10">
              <div className="flex items-center justify-between text-xs mb-1.5">
                <span className="text-slate-400 font-medium">
                  {isAdmin ? "Tổng dung lượng Kho lưu trữ" : `Dung lượng của @${currentUser.username}`}
                </span>
                <span className="font-mono font-bold text-indigo-300">{formatBytes(stats.totalSize)}</span>
              </div>
              <div className="w-full h-1.5 bg-slate-800 rounded-full overflow-hidden flex">
                <div style={{ width: `${Math.min((stats.sizes.video / (stats.totalSize || 1)) * 100, 100)}%` }} className="bg-rose-500 h-full" />
                <div style={{ width: `${Math.min((stats.sizes.archive / (stats.totalSize || 1)) * 100, 100)}%` }} className="bg-amber-400 h-full" />
                <div style={{ width: `${Math.min((stats.sizes.image / (stats.totalSize || 1)) * 100, 100)}%` }} className="bg-indigo-400 h-full" />
              </div>
            </div>
          )}

          {/* Current User Profile Card */}
          <div className="flex items-center justify-between gap-2 p-2 rounded-2xl bg-white/5 border border-white/10">
            <div className="flex items-center gap-2.5 min-w-0">
              <div
                className={`w-9 h-9 rounded-xl flex items-center justify-center font-bold text-xs shrink-0 ${
                  isAdmin
                    ? "bg-amber-500/20 text-amber-300 border border-amber-500/40"
                    : "bg-indigo-500/20 text-indigo-300 border border-indigo-500/40"
                }`}
              >
                {currentUser.display_name.charAt(0).toUpperCase()}
              </div>
              {!sidebarCollapsed && (
                <div className="min-w-0">
                  <p className="text-xs font-bold text-white truncate">{currentUser.display_name}</p>
                  <p className="text-[10px] font-mono text-slate-400 truncate">
                    @{currentUser.username} • {isAdmin ? "ADMIN" : "USER"}
                  </p>
                </div>
              )}
            </div>
            <button
              onClick={handleLogout}
              title="Đăng xuất"
              className="p-2 rounded-xl bg-rose-500/10 hover:bg-rose-500/20 text-rose-300 transition shrink-0"
            >
              <LogOut className="w-4 h-4" />
            </button>
          </div>
        </div>
      </aside>

      {/* MAIN CONTENT AREA */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* TOP HEADER BAR */}
        <header className="sticky top-0 z-20 h-16 glass border-b border-white/10 px-6 flex items-center justify-between gap-4">
          <div className="flex items-center gap-3 flex-1 max-w-xl">
            <div className="relative w-full">
              <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => {
                  setSearchQuery(e.target.value);
                  if (pathname !== "/explorer") router.push("/explorer");
                }}
                placeholder="Tìm kiếm tệp tin trên Upload ThTuanIT..."
                className="w-full bg-slate-900/80 border border-white/10 focus:border-indigo-500 rounded-xl pl-10 pr-8 py-2 text-xs sm:text-sm text-slate-100 placeholder-slate-500 focus:outline-none transition"
              />
              {searchQuery && (
                <button
                  onClick={() => setSearchQuery("")}
                  className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white"
                >
                  <X className="w-4 h-4" />
                </button>
              )}
            </div>
          </div>

          <div className="flex items-center gap-3">
            {pendingRequestsCount > 0 && (
              <button
                onClick={() => {
                  const firstPendingShare = Object.values(sharesMap).find(
                    (sh) => sh.enabled && sh.requests?.some((r) => r.status === "pending")
                  );
                  if (firstPendingShare) {
                    const targetFile = files.find((f) => f.path === firstPendingShare.path);
                    if (targetFile) setShareTarget(targetFile);
                  }
                }}
                className="flex items-center gap-2 px-3.5 py-2 rounded-xl bg-amber-500/20 hover:bg-amber-500/30 border border-amber-500/40 text-xs font-bold text-amber-300 animate-pulse transition"
              >
                <Share2 className="w-3.5 h-3.5" />
                <span>{pendingRequestsCount} yêu cầu xin xem tệp</span>
              </button>
            )}

            <div className="hidden sm:flex items-center gap-2 px-3 py-1.5 rounded-xl bg-slate-900/90 border border-white/10 text-xs font-mono">
              <span className={`w-2 h-2 rounded-full ${healthOk ? "bg-emerald-400" : "bg-rose-500"}`} />
              <span className="text-slate-300">cloud://thtuanit/storage</span>
            </div>

            <button
              onClick={() => loadFiles(token, true)}
              disabled={loadingFiles}
              className="flex items-center gap-2 px-3.5 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs font-semibold text-slate-200 transition"
            >
              <RefreshCw className={`w-3.5 h-3.5 ${loadingFiles ? "animate-spin text-indigo-400" : ""}`} />
              <span className="hidden md:inline">Đồng bộ</span>
            </button>
          </div>
        </header>

        {/* TURBO UPLOAD PROGRESS HUD */}
        {uploadQueue.length > 0 && (
          <div className="mx-6 mt-4 glass-panel rounded-2xl p-4 border border-indigo-500/40 space-y-2.5">
            <div className="flex items-center justify-between text-xs">
              <span className="font-bold text-indigo-300 flex items-center gap-2">
                <UploadCloud className="w-4 h-4 animate-bounce" />
                <span>Upload ThTuanIT Turbo Parallel (4 luồng đồng thời)...</span>
              </span>
              <span className="font-mono text-slate-400">
                {uploadQueue.filter((q) => q.status === "done").length}/{uploadQueue.length} hoàn tất
              </span>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
              {uploadQueue.map((item) => (
                <div key={item.id} className="bg-slate-900/90 rounded-xl p-2.5 border border-white/10">
                  <div className="flex justify-between text-xs mb-1 gap-2">
                    <span className="font-mono text-slate-200 truncate">{item.path}</span>
                    <span className="font-mono text-indigo-300 shrink-0">
                      {item.status === "syncing"
                        ? "Đang đồng bộ Cloud..."
                        : item.status === "done"
                        ? "✓ Hoàn tất"
                        : item.status === "error"
                        ? "✕ Lỗi"
                        : `${item.progress}% • ${item.speedMBps || ""}${
                            item.etaSec ? ` (${item.etaSec}s)` : ""
                          }`}
                    </span>
                  </div>
                  <div className="w-full h-1.5 bg-slate-800 rounded-full overflow-hidden">
                    <div
                      style={{ width: `${item.progress}%` }}
                      className={`h-full transition-all ${
                        item.status === "error"
                          ? "bg-rose-500"
                          : item.status === "done"
                          ? "bg-emerald-400"
                          : "bg-indigo-500"
                      }`}
                    />
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* ROUTE PAGE CONTENT */}
        <main className="flex-1 flex flex-col">{children}</main>
      </div>

      <GlobalModals />
    </div>
  );
}