<?php $__env->startSection('styles'); ?>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/theme/dracula.min.css">
    <style>
        /* ====== TOP TOOLBAR (cPanel style) ====== */
        .cp-toolbar {
            display: flex;
            gap: 2px;
            padding: 6px 10px;
            background: linear-gradient(to bottom, #3a4a5e, #2c3a4d);
            border: 1px solid #1e2a38;
            border-radius: 10px 10px 0 0;
            flex-wrap: wrap;
            align-items: center;
        }

        .cp-toolbar .sep {
            width: 1px;
            height: 26px;
            background: rgba(255, 255, 255, 0.15);
            margin: 0 4px;
        }

        .cp-btn {
            padding: 5px 10px;
            border: none;
            background: transparent;
            color: #c8d6e5;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 0.78rem;
            border-radius: 4px;
            transition: 0.15s;
            white-space: nowrap;
        }

        .cp-btn:hover {
            background: rgba(255, 255, 255, 0.12);
        }

        .cp-btn:disabled {
            opacity: 0.35;
            cursor: default;
        }

        .cp-btn:disabled:hover {
            background: transparent;
        }

        .cp-btn i {
            font-size: 0.85rem;
        }

        .cp-btn.blue i {
            color: #3498db;
        }

        .cp-btn.green i {
            color: #2ecc71;
        }

        .cp-btn.red i {
            color: #e74c3c;
        }

        .cp-btn.yellow i {
            color: #f1c40f;
        }

        .cp-btn.purple i {
            color: #9b59b6;
        }

        .cp-btn.orange i {
            color: #e67e22;
        }

        /* ====== NAV BAR ====== */
        .cp-nav {
            display: flex;
            gap: 2px;
            padding: 5px 10px;
            background: linear-gradient(to bottom, #ecf0f1, #dfe6e9);
            border: 1px solid #bdc3c7;
            border-top: none;
            border-radius: 0 0 10px 10px;
            align-items: center;
            flex-wrap: wrap;
            margin-bottom: 1rem;
        }

        .cp-nav .path-box {
            display: flex;
            align-items: center;
            background: white;
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            padding: 4px 8px;
            gap: 5px;
            margin-right: 6px;
        }

        .cp-nav .path-box i {
            color: #555;
            font-size: 0.85rem;
        }

        .cp-nav .path-text {
            font-size: 0.82rem;
            color: #333;
            font-weight: 500;
            min-width: 120px;
        }

        .nav-btn {
            padding: 4px 9px;
            border: none;
            background: transparent;
            color: #555;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 0.78rem;
            border-radius: 3px;
            transition: 0.15s;
        }

        .nav-btn:hover {
            background: rgba(0, 0, 0, 0.08);
        }

        .nav-btn:disabled {
            opacity: 0.35;
            cursor: default;
        }

        .nav-sep {
            width: 1px;
            height: 22px;
            background: #bdc3c7;
            margin: 0 3px;
        }

        /* ====== FILE TABLE ====== */
        .fm-table {
            width: 100%;
            border-collapse: collapse;
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 12px;
            overflow: hidden;
        }

        .fm-table thead th {
            padding: 8px 12px;
            text-align: left;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.04em;
            color: var(--text-muted);
            border-bottom: 1px solid var(--border);
            background: rgba(0, 0, 0, 0.15);
            cursor: pointer;
            user-select: none;
        }

        .fm-table tbody tr {
            border-bottom: 1px solid rgba(255, 255, 255, 0.03);
            transition: background 0.1s;
        }

        .fm-table tbody tr:hover {
            background: rgba(99, 102, 241, 0.06);
        }

        .fm-table tbody tr.selected {
            background: rgba(99, 102, 241, 0.14) !important;
        }

        .fm-table td {
            padding: 6px 12px;
            font-size: 0.85rem;
            vertical-align: middle;
        }

        .fm-table .col-cb {
            width: 36px;
            text-align: center;
        }

        .fm-table .col-cb input {
            accent-color: var(--primary);
            width: 14px;
            height: 14px;
            cursor: pointer;
        }

        .fm-table .row-name {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .fm-table .row-name i {
            font-size: 1.1rem;
            width: 18px;
            text-align: center;
        }

        .fm-table .row-name a,
        .fm-table .row-name span {
            font-weight: 500;
        }

        .fm-table .row-name a {
            color: inherit;
            text-decoration: none;
        }

        .fm-table .row-name a:hover {
            color: var(--primary);
        }

        .fm-table .row-actions {
            display: flex;
            gap: 2px;
        }

        .fm-table .row-actions button {
            padding: 3px 7px;
            border: none;
            background: transparent;
            color: var(--text-muted);
            cursor: pointer;
            border-radius: 4px;
            transition: 0.15s;
            font-size: 0.8rem;
        }

        .fm-table .row-actions button:hover {
            background: rgba(255, 255, 255, 0.1);
            color: #fff;
        }

        /* ====== OVERLAYS ====== */
        .overlay {
            display: none;
            position: fixed;
            z-index: 5000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.75);
            backdrop-filter: blur(8px);
        }

        .overlay-box {
            background: var(--bg-card);
            margin: 5% auto;
            padding: 2rem;
            border-radius: 20px;
            width: 480px;
            max-width: 95vw;
            border: 1px solid var(--border);
        }

        .overlay-box h3 {
            margin-bottom: 1.2rem;
            font-size: 1.1rem;
        }

        .overlay-box .form-input {
            width: 100%;
            padding: 10px 14px;
            background: rgba(0, 0, 0, 0.3);
            border: 1px solid var(--border);
            border-radius: 10px;
            color: white;
            font-size: 0.9rem;
            margin-bottom: 1rem;
            box-sizing: border-box;
        }

        .overlay-box .btn-row {
            display: flex;
            justify-content: flex-end;
            gap: 0.8rem;
        }

        .overlay-box .btn-cancel {
            padding: 8px 16px;
            border-radius: 8px;
            border: 1px solid var(--border);
            background: transparent;
            color: #ccc;
            cursor: pointer;
        }

        .overlay-box .btn-ok {
            padding: 8px 16px;
            border-radius: 8px;
            border: none;
            background: var(--primary);
            color: #fff;
            cursor: pointer;
            font-weight: 600;
        }

        /* ====== UPLOAD PROGRESS OVERLAY ====== */
        #uploadProgressOverlay {
            position: fixed;
            inset: 0;
            z-index: 99996;
            background: rgba(5, 10, 20, 0.85);
            backdrop-filter: blur(10px);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.25s ease;
        }
        #uploadProgressOverlay.open {
            opacity: 1;
            pointer-events: all;
        }
        #uploadProgressBox {
            background: linear-gradient(145deg, #0f172a, #1a2744);
            border: 1px solid rgba(99,179,237,0.15);
            border-radius: 24px;
            padding: 2.4rem 2.4rem 2rem;
            width: 420px;
            max-width: 92vw;
            box-shadow: 0 30px 80px rgba(0,0,0,0.55), 0 0 0 1px rgba(56,189,248,0.06);
            transform: scale(0.9) translateY(20px);
            transition: transform 0.3s cubic-bezier(.34,1.56,.64,1);
            text-align: center;
        }
        #uploadProgressOverlay.open #uploadProgressBox {
            transform: scale(1) translateY(0);
        }
        /* Cloud icon animation */
        .up-cloud-wrap {
            position: relative;
            width: 72px; height: 72px;
            margin: 0 auto 1.3rem;
        }
        .up-cloud-wrap .up-cloud-bg {
            width: 72px; height: 72px;
            border-radius: 50%;
            background: rgba(56,189,248,0.1);
            border: 1.5px solid rgba(56,189,248,0.25);
            display: flex; align-items: center; justify-content: center;
            font-size: 1.7rem;
            color: #38bdf8;
            box-shadow: 0 0 24px rgba(56,189,248,0.2);
            position: relative;
            overflow: hidden;
        }
        .up-cloud-bg::after {
            content: '';
            position: absolute;
            inset: 0;
            background: linear-gradient(135deg, transparent 40%, rgba(56,189,248,0.15));
            border-radius: 50%;
        }
        .up-cloud-wrap .up-particles {
            position: absolute;
            inset: 0;
        }
        .up-cloud-wrap .up-particles span {
            position: absolute;
            width: 5px; height: 5px;
            border-radius: 50%;
            background: #38bdf8;
            animation: particle-float 2s ease-in-out infinite;
            opacity: 0;
        }
        .up-cloud-wrap .up-particles span:nth-child(1) { top: 10%; left: 50%; animation-delay: 0s; }
        .up-cloud-wrap .up-particles span:nth-child(2) { top: 20%; left: 30%; animation-delay: 0.4s; width:4px; height:4px; background:#818cf8; }
        .up-cloud-wrap .up-particles span:nth-child(3) { top: 15%; left: 70%; animation-delay: 0.8s; width:3px; height:3px; background:#f472b6; }
        .up-cloud-wrap .up-particles span:nth-child(4) { top: 5%;  left: 45%; animation-delay: 1.2s; width:4px; height:4px; }
        @keyframes particle-float {
            0%   { opacity: 0; transform: translateY(0) scale(0.5); }
            30%  { opacity: 1; }
            100% { opacity: 0; transform: translateY(-28px) scale(1.2); }
        }
        .up-filename {
            font-size: 0.9rem;
            font-weight: 600;
            color: #e2e8f0;
            margin-bottom: 0.3rem;
            word-break: break-all;
        }
        .up-filesize {
            font-size: 0.78rem;
            color: #64748b;
            margin-bottom: 1.4rem;
        }
        /* Progress track */
        .up-track {
            width: 100%;
            height: 8px;
            background: rgba(255,255,255,0.07);
            border-radius: 999px;
            overflow: hidden;
            margin-bottom: 0.6rem;
            position: relative;
        }
        .up-track-fill {
            height: 100%;
            width: 0%;
            background: linear-gradient(90deg, #38bdf8, #818cf8);
            border-radius: 999px;
            transition: width 0.2s ease;
            position: relative;
            box-shadow: 0 0 10px #38bdf866;
        }
        .up-track-fill::after {
            content: '';
            position: absolute;
            right: 0; top: 0; bottom: 0;
            width: 30px;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4));
            border-radius: 999px;
        }
        .up-track-fill.indeterminate {
            width: 40% !important;
            animation: indeterminate-slide 1.4s ease-in-out infinite;
        }
        @keyframes indeterminate-slide {
            0%   { transform: translateX(-100%); }
            100% { transform: translateX(350%); }
        }
        .up-stats {
            display: flex;
            justify-content: space-between;
            font-size: 0.76rem;
            color: #64748b;
            margin-bottom: 1.4rem;
        }
        .up-stats .up-pct { color: #38bdf8; font-weight: 700; font-size: 0.82rem; }
        /* Status states */
        .up-status {
            font-size: 0.82rem;
            color: #64748b;
            min-height: 1.2rem;
        }
        /* Success state */
        #uploadProgressBox.done .up-cloud-bg {
            background: rgba(16,185,129,0.12);
            border-color: rgba(16,185,129,0.3);
            color: #10b981;
            box-shadow: 0 0 24px rgba(16,185,129,0.25);
        }
        #uploadProgressBox.done .up-track-fill {
            background: linear-gradient(90deg, #10b981, #059669);
            box-shadow: 0 0 10px #10b98166;
            width: 100% !important;
        }
        /* Error state */
        #uploadProgressBox.error .up-cloud-bg {
            background: rgba(239,68,68,0.12);
            border-color: rgba(239,68,68,0.3);
            color: #ef4444;
            box-shadow: 0 0 24px rgba(239,68,68,0.2);
        }
        #uploadProgressBox.error .up-track-fill {
            background: linear-gradient(90deg, #ef4444, #dc2626);
            box-shadow: 0 0 10px #ef444466;
        }
        /* Cancel btn */
        .up-cancel-btn {
            background: transparent;
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 8px;
            padding: 7px 20px;
            color: #64748b;
            font-size: 0.8rem;
            cursor: pointer;
            transition: all 0.15s;
        }
        .up-cancel-btn:hover { background: rgba(255,255,255,0.06); color: #94a3b8; }

        /* ====== CUSTOM CONFIRM MODAL ====== */
        #confirmOverlay {
            position: fixed;
            inset: 0;
            z-index: 99997;
            background: rgba(5, 10, 20, 0.78);
            backdrop-filter: blur(8px);
            -webkit-backdrop-filter: blur(8px);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.2s ease;
        }
        #confirmOverlay.open {
            opacity: 1;
            pointer-events: all;
        }
        #confirmBox {
            background: linear-gradient(145deg, #0f172a, #1e293b);
            border: 1px solid rgba(255,255,255,0.08);
            border-radius: 20px;
            padding: 2rem 2rem 1.6rem;
            width: 400px;
            max-width: 92vw;
            box-shadow: 0 24px 60px rgba(0,0,0,0.5), 0 0 0 1px rgba(56,189,248,0.08);
            transform: scale(0.88) translateY(16px);
            transition: transform 0.25s cubic-bezier(.34,1.56,.64,1);
            text-align: center;
        }
        #confirmOverlay.open #confirmBox {
            transform: scale(1) translateY(0);
        }
        #confirmIconWrap {
            width: 62px; height: 62px;
            border-radius: 50%;
            margin: 0 auto 1.1rem;
            display: flex; align-items: center; justify-content: center;
            font-size: 1.6rem;
            position: relative;
        }
        #confirmIconWrap.danger {
            background: rgba(239, 68, 68, 0.12);
            border: 1.5px solid rgba(239, 68, 68, 0.3);
            color: #ef4444;
            box-shadow: 0 0 20px rgba(239,68,68,0.18);
        }
        #confirmIconWrap.warning {
            background: rgba(245, 158, 11, 0.12);
            border: 1.5px solid rgba(245, 158, 11, 0.3);
            color: #f59e0b;
            box-shadow: 0 0 20px rgba(245,158,11,0.18);
        }
        #confirmIconWrap.info {
            background: rgba(56, 189, 248, 0.12);
            border: 1.5px solid rgba(56, 189, 248, 0.3);
            color: #38bdf8;
            box-shadow: 0 0 20px rgba(56,189,248,0.18);
        }
        #confirmIconWrap::after {
            content: '';
            position: absolute;
            inset: -6px;
            border-radius: 50%;
            border: 1px solid currentColor;
            opacity: 0.18;
        }
        #confirmTitle {
            font-size: 1.05rem;
            font-weight: 700;
            color: #f1f5f9;
            margin-bottom: 0.5rem;
        }
        #confirmMsg {
            font-size: 0.85rem;
            color: #94a3b8;
            line-height: 1.6;
            margin-bottom: 1.6rem;
        }
        .confirm-btns {
            display: flex;
            gap: 10px;
            justify-content: center;
        }
        .confirm-btns button {
            flex: 1;
            padding: 10px 18px;
            border-radius: 10px;
            border: none;
            font-size: 0.85rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.15s ease;
            letter-spacing: 0.02em;
        }
        .confirm-btns .cb-cancel {
            background: rgba(255,255,255,0.06);
            border: 1px solid rgba(255,255,255,0.1);
            color: #94a3b8;
        }
        .confirm-btns .cb-cancel:hover {
            background: rgba(255,255,255,0.1);
            color: #e2e8f0;
        }
        .confirm-btns .cb-ok {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: #fff;
            box-shadow: 0 4px 14px rgba(239,68,68,0.35);
        }
        .confirm-btns .cb-ok:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 20px rgba(239,68,68,0.45);
        }
        .confirm-btns .cb-ok.info {
            background: linear-gradient(135deg, #38bdf8, #0ea5e9);
            box-shadow: 0 4px 14px rgba(56,189,248,0.35);
        }
        .confirm-btns .cb-ok.info:hover {
            box-shadow: 0 6px 20px rgba(56,189,248,0.45);
        }
        .confirm-btns .cb-ok.warning {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            box-shadow: 0 4px 14px rgba(245,158,11,0.35);
        }

        .overlay-box .btn-ok:hover {
            opacity: 0.9;
        }

        /* ====== EDITOR ====== */
        .editor-overlay {
            display: none;
            position: fixed;
            z-index: 6000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
        }

        .editor-box {
            background: var(--bg-card);
            margin: 2% auto;
            border-radius: 16px;
            width: 92%;
            max-width: 1200px;
            border: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            height: 90vh;
            overflow: hidden;
        }

        .editor-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.8rem 1.2rem;
            border-bottom: 1px solid var(--border);
            background: rgba(0, 0, 0, 0.25);
        }

        .editor-body {
            flex: 1;
            overflow: hidden;
        }

        .CodeMirror {
            height: 100% !important;
            font-size: 14px;
        }

        /* ====== UPLOAD ====== */
        .drop-zone {
            border: 2px dashed var(--border);
            border-radius: 14px;
            padding: 2rem;
            margin: 1rem 0;
            cursor: pointer;
            transition: 0.2s;
            text-align: center;
        }

        .drop-zone:hover,
        .drop-zone.dragover {
            border-color: var(--primary);
            background: rgba(99, 102, 241, 0.05);
        }

        .drop-zone input {
            display: none;
        }

        /* ====== TOAST ====== */
        /* ====== PRELOADER OVERLAY ====== */
        #preloader {
            position: fixed;
            inset: 0;
            z-index: 99999;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 22px;
            background: rgba(8, 14, 26, 0.82);
            backdrop-filter: blur(6px);
            -webkit-backdrop-filter: blur(6px);
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.22s ease;
        }
        #preloader.active {
            opacity: 1;
            pointer-events: all;
        }

        /* Top slim progress bar */
        #nprogress-bar {
            position: fixed;
            top: 0; left: 0;
            width: 0%;
            height: 3px;
            z-index: 100000;
            background: linear-gradient(90deg, #38bdf8, #818cf8, #f472b6, #38bdf8);
            background-size: 300% 100%;
            border-radius: 0 2px 2px 0;
            box-shadow: 0 0 12px #38bdf8aa, 0 0 24px #818cf855;
            opacity: 0;
            transition: width 0.3s ease, opacity 0.3s ease;
            animation: bar-shimmer 2s linear infinite;
        }
        #nprogress-bar.running { opacity: 1; }

        /* Spinner rings */
        .pl-rings {
            position: relative;
            width: 72px; height: 72px;
        }
        .pl-rings .ring {
            position: absolute;
            inset: 0;
            border-radius: 50%;
            border: 3px solid transparent;
        }
        .pl-rings .ring-1 {
            border-top-color: #38bdf8;
            animation: spin1 1s linear infinite;
            box-shadow: 0 0 16px #38bdf866;
        }
        .pl-rings .ring-2 {
            inset: 9px;
            border-right-color: #818cf8;
            animation: spin2 0.75s linear infinite;
            box-shadow: 0 0 10px #818cf855;
        }
        .pl-rings .ring-3 {
            inset: 18px;
            border-bottom-color: #f472b6;
            animation: spin1 0.5s linear infinite reverse;
            box-shadow: 0 0 8px #f472b644;
        }
        .pl-rings .ring-dot {
            position: absolute;
            inset: 28px;
            border-radius: 50%;
            background: radial-gradient(circle, #38bdf8 0%, transparent 70%);
            animation: dot-pulse 1.2s ease-in-out infinite;
        }

        /* Action label */
        .pl-label {
            color: #e2e8f0;
            font-size: 0.88rem;
            font-weight: 500;
            letter-spacing: 0.06em;
            text-transform: uppercase;
            opacity: 0.9;
            animation: text-pulse 1.6s ease-in-out infinite;
        }
        /* Dots animation */
        .pl-dots {
            display: flex; gap: 6px; align-items: center;
        }
        .pl-dots span {
            width: 6px; height: 6px;
            border-radius: 50%;
            background: #38bdf8;
            animation: dot-bounce 1.2s ease-in-out infinite;
        }
        .pl-dots span:nth-child(2) { animation-delay: 0.2s; background: #818cf8; }
        .pl-dots span:nth-child(3) { animation-delay: 0.4s; background: #f472b6; }

        @keyframes spin1  { to { transform: rotate(360deg); } }
        @keyframes spin2  { to { transform: rotate(-360deg); } }
        @keyframes dot-pulse {
            0%, 100% { opacity: 0.6; transform: scale(0.8); }
            50%       { opacity: 1;   transform: scale(1.2); }
        }
        @keyframes text-pulse {
            0%, 100% { opacity: 0.7; }
            50%       { opacity: 1; }
        }
        @keyframes dot-bounce {
            0%, 80%, 100% { transform: scale(0.7); opacity: 0.5; }
            40%            { transform: scale(1.2); opacity: 1; }
        }
        @keyframes bar-shimmer {
            0%   { background-position: 300% 0; }
            100% { background-position: -300% 0; }
        }

        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            padding: 12px 20px;
            border-radius: 10px;
            font-size: 0.88rem;
            display: none;
            animation: slideIn 0.3s;
            min-width: 200px;
        }

        .toast.ok {
            background: rgba(16, 185, 129, 0.15);
            color: #10b981;
            border: 1px solid rgba(16, 185, 129, 0.3);
        }

        .toast.err {
            background: rgba(239, 68, 68, 0.15);
            color: #ef4444;
            border: 1px solid rgba(239, 68, 68, 0.3);
        }

        @keyframes slideIn {
            from {
                transform: translateX(100px);
                opacity: 0;
            }

            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        .empty-state {
            text-align: center;
            padding: 3rem 2rem;
            background: var(--bg-card);
            border-radius: 16px;
            border: 1px dashed var(--border);
        }

        /* Permission checkboxes */
        .perm-grid {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }

        .perm-group {
            background: rgba(0, 0, 0, 0.2);
            padding: 0.8rem;
            border-radius: 8px;
        }

        .perm-group h4 {
            font-size: 0.8rem;
            color: var(--text-muted);
            margin-bottom: 0.5rem;
            text-transform: uppercase;
        }

        .perm-group label {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 0.85rem;
            margin-bottom: 4px;
            cursor: pointer;
        }

        .perm-group input {
            accent-color: var(--primary);
        }

        /* Copy/Move path helper */
        .path-hint {
            color: var(--text-muted);
            font-size: 0.78rem;
            margin-bottom: 0.5rem;
        }

        .path-hint code {
            background: rgba(0, 0, 0, 0.3);
            padding: 2px 6px;
            border-radius: 4px;
            font-family: monospace;
        }
    </style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <?php
        // Base path for this domain's files inside cPanel (relative to home), e.g. "domains/example.com"
        $basePath = $root ?? $domain;
        // Build display path relative to domain
        $displayDir = str_replace($basePath, '/' . $domain, $dir);
        if ($displayDir === '/' . $domain)
            $displayDir = '/' . $domain;
    ?>

    <div class="animate-fade">
        <!-- ====== HEADER ====== -->
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.8rem;flex-wrap:wrap;gap:10px;">
            <div>
                <h2 style="font-size:1.3rem; margin-bottom:0.1rem;"><i class="fas fa-folder-open"
                        style="color:var(--primary);"></i> File Manager</h2>
                <p style="color:var(--text-muted); font-size:0.82rem;"><?php echo e($domain); ?></p>
            </div>
            <a href="<?php echo e(route('files')); ?>" class="cp-btn" style="border:1px solid var(--border); color:#ccc;">
                <i class="fas fa-exchange-alt"></i> Switch Domain
            </a>
        </div>

        
        <?php if(!Auth::user()->isAdmin() && isset($diskLimitGB) && $diskLimitGB > 0): ?>
        <div style="background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);border-radius:12px;padding:12px 16px;margin-bottom:14px;display:flex;align-items:center;gap:14px;flex-wrap:wrap;">
            <div style="flex-shrink:0;">
                <i class="fas fa-hdd" style="color:<?php echo e($quotaFull ? '#ef4444' : ($diskPercent >= 80 ? '#f59e0b' : '#3fb950')); ?>;font-size:1.1rem;"></i>
            </div>
            <div style="flex:1;min-width:180px;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:5px;">
                    <span style="font-size:.76rem;font-weight:600;color:<?php echo e($quotaFull ? '#ef4444' : '#e6edf3'); ?>;">
                        Storage
                        <?php if($quotaFull): ?> <span style="color:#ef4444;margin-left:4px;"><i class="fas fa-exclamation-circle"></i> QUOTA FULL</span>
                        <?php elseif($diskPercent >= 80): ?> <span style="color:#f59e0b;margin-left:4px;"><i class="fas fa-exclamation-triangle"></i> Almost full</span>
                        <?php endif; ?>
                    </span>
                    <span style="font-size:.74rem;color:#8b949e;">
                        <?php echo e(number_format($diskUsedDisplay ?? $diskUsedGB, 2)); ?> <?php echo e($diskUnit ?? 'GB'); ?>

                        / <?php echo e(number_format($diskLimitDisplay ?? $diskLimitGB, 2)); ?> <?php echo e($diskUnit ?? 'GB'); ?>

                        (<?php echo e($diskPercent); ?>%)
                    </span>
                </div>
                <div style="height:6px;background:rgba(255,255,255,.08);border-radius:99px;overflow:hidden;">
                    <div style="height:100%;width:<?php echo e($diskPercent); ?>%;border-radius:99px;background:<?php echo e($quotaFull ? '#ef4444' : ($diskPercent >= 80 ? 'linear-gradient(90deg,#f59e0b,#ef4444)' : 'linear-gradient(90deg,#3fb950,#22c55e)')); ?>;transition:width .4s;"></div>
                </div>
            </div>
            <?php if($quotaFull): ?>
            <div style="font-size:.72rem;color:#ef4444;font-weight:700;flex-shrink:0;">
                <i class="fas fa-lock"></i> Uploads blocked
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        
        <?php if(!Auth::user()->isAdmin() && isset($quotaFull) && $quotaFull): ?>
        <div style="background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);border-radius:10px;padding:12px 16px;margin-bottom:14px;font-size:.82rem;color:#fca5a5;display:flex;align-items:center;gap:10px;">
            <i class="fas fa-exclamation-circle" style="font-size:1rem;flex-shrink:0;"></i>
            <div>
                <strong>Storage quota full.</strong> You cannot upload files or create new content until you free up space or your admin increases your quota.
            </div>
        </div>
        <?php endif; ?>

        <!-- ====== TOP TOOLBAR ====== -->
        <div class="cp-toolbar">
            <button class="cp-btn blue" onclick="showNewFileModal()"><i class="fas fa-file-medical"></i> +File</button>
            <button class="cp-btn blue" onclick="showNewFolderModal()"><i class="fas fa-folder-plus"></i> +Folder</button>
            <div class="sep"></div>
            <button class="cp-btn" id="btnCopy" disabled onclick="clipboardCopy()"><i class="fas fa-copy"></i> Copy</button>
            <button class="cp-btn" id="btnCut" disabled onclick="clipboardCut()"><i class="fas fa-cut"></i> Cut</button>
            <button class="cp-btn green" id="btnPaste" disabled onclick="clipboardPaste()" style="display:none;"><i class="fas fa-paste"></i> Paste</button>
            <button class="cp-btn green" onclick="showUploadModal()"><i class="fas fa-upload"></i> Upload</button>
            <button class="cp-btn red" id="btnDelete" disabled onclick="deleteSelected()"><i class="fas fa-trash-alt"></i> Delete</button>
            <div class="sep"></div>
            <button class="cp-btn yellow" id="btnRename" disabled onclick="showRenameModal()"><i class="fas fa-i-cursor"></i> Rename</button>
            <button class="cp-btn blue" id="btnEdit" disabled onclick="editSelected()"><i class="fas fa-pencil-alt"></i> Edit</button>
            <button class="cp-btn blue" id="btnHtmlEdit" disabled onclick="editSelected()"><i class="fab fa-html5"></i> HTML Editor</button>
            <button class="cp-btn purple" id="btnPerms" disabled onclick="showPermissionsModal()"><i class="fas fa-key"></i> Permissions</button>
            <button class="cp-btn" id="btnView" disabled onclick="viewSelected()"><i class="fas fa-eye"></i> View</button>
            <button class="cp-btn orange" id="btnExtract" disabled onclick="extractSelected()"><i class="fas fa-file-archive"></i> Extract</button>
            <button class="cp-btn orange" id="btnCompress" disabled onclick="showCompressModal()"><i class="fas fa-compress-arrows-alt"></i> Compress & Download</button>
        </div>

        <!-- ====== CLIPBOARD INDICATOR ====== -->
        <div id="clipboardBar" style="display:none; padding:6px 14px; background:rgba(99,102,241,0.12); border:1px solid rgba(99,102,241,0.3); border-top:none; font-size:0.82rem; color:#818cf8; align-items:center; gap:8px;">
            <i class="fas fa-clipboard"></i>
            <span id="clipboardInfo"></span>
            <button onclick="clipboardClear()" style="margin-left:auto; background:none; border:none; color:#ef4444; cursor:pointer; font-size:0.8rem;"><i class="fas fa-times"></i> Clear</button>
        </div>

        <!-- ====== NAV BAR ====== -->
        <div class="cp-nav">
            <div class="path-box">
                <i class="fas fa-folder"></i>
                <span class="path-text">
                    <?php $__currentLoopData = $breadcrumbs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $bc): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <?php if(!$loop->last): ?>
                            <a href="<?php echo e(route('files', ['domain' => $domain, 'root' => $basePath, 'dir' => $bc['path']])); ?>"
                                onclick="progressStart('Opening <?php echo e($bc['name']); ?>...')"
                                style="color:#3498db; text-decoration:none;"><?php echo e($bc['name']); ?></a>/
                        <?php else: ?>
                            <?php echo e($bc['name']); ?>

                        <?php endif; ?>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </span>
            </div>
            <button class="nav-btn" onclick="goHome()"><i class="fas fa-home"></i> Home</button>
            <button class="nav-btn" onclick="goUp()"><i class="fas fa-level-up-alt"></i> Up One Level</button>
            <button class="nav-btn" onclick="history.back()"><i class="fas fa-arrow-left"></i> Back</button>
            <button class="nav-btn" onclick="history.forward()"><i class="fas fa-arrow-right"></i> Forward</button>
            <div class="nav-sep"></div>
            <button class="nav-btn" onclick="location.reload()"><i class="fas fa-sync-alt"></i> Reload</button>
            <button class="nav-btn" onclick="selectAll()"><i class="far fa-check-square"></i> Select All</button>
            <button class="nav-btn" onclick="unselectAll()"><i class="far fa-square"></i> Unselect All</button>
        </div>

        <!-- ====== FILE TABLE ====== -->
        <?php if(count($files) > 0): ?>
            <table class="fm-table">
                <thead>
                    <tr>
                        <th class="col-cb"><input type="checkbox" id="cbAll" onchange="toggleAll(this)"></th>
                        <th>Name</th>
                        <th>Size</th>
                        <th>Last Modified</th>
                        <th>Type</th>
                        <th>Perms</th>
                        <th style="width:100px;">Actions</th>
                    </tr>
                </thead>
                <tbody id="fileBody">
                    <?php $__currentLoopData = $files; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $f): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <?php
                            $isDir = ($f['type'] ?? '') === 'dir';
                            $fname = $f['file'] ?? $f['name'] ?? 'unknown';
                            $ext = pathinfo($fname, PATHINFO_EXTENSION);
                            $isZip = in_array(strtolower($ext), ['zip', 'tar', 'gz', 'bz2', 'rar', '7z']);
                            $isEditable = in_array(strtolower($ext), ['php', 'html', 'htm', 'css', 'js', 'json', 'txt', 'xml', 'htaccess', 'md', 'env', 'yml', 'yaml', 'ini', 'conf', 'log', 'sql', 'py', 'rb', 'sh']);
                            $icons = ['php' => 'fab fa-php', 'js' => 'fab fa-js-square', 'html' => 'fab fa-html5', 'htm' => 'fab fa-html5', 'css' => 'fab fa-css3-alt', 'json' => 'fas fa-code', 'txt' => 'fas fa-file-alt', 'zip' => 'fas fa-file-archive', 'tar' => 'fas fa-file-archive', 'gz' => 'fas fa-file-archive', 'jpg' => 'fas fa-file-image', 'jpeg' => 'fas fa-file-image', 'png' => 'fas fa-file-image', 'gif' => 'fas fa-file-image', 'svg' => 'fas fa-file-image', 'webp' => 'fas fa-file-image', 'pdf' => 'fas fa-file-pdf', 'mp4' => 'fas fa-file-video', 'mp3' => 'fas fa-file-audio', 'sql' => 'fas fa-database', 'py' => 'fab fa-python', 'md' => 'fab fa-markdown'];
                            $icon = $isDir ? 'fas fa-folder' : ($icons[strtolower($ext)] ?? 'fas fa-file');
                            $iconColor = $isDir ? '#fbbf24' : ($isZip ? '#ec4899' : '#6366f1');
                            $size = $isDir ? '-' : ($f['humansize'] ?? $f['size'] ?? '-');
                            $mtime = $f['mtime'] ?? $f['ctime'] ?? '-';
                            $perms = $f['niceperms'] ?? $f['permissions'] ?? '-';
                        ?>
                        <tr data-name="<?php echo e($fname); ?>" data-type="<?php echo e($isDir ? 'dir' : 'file'); ?>" data-zip="<?php echo e($isZip ? '1' : '0'); ?>"
                            data-editable="<?php echo e($isEditable ? '1' : '0'); ?>">
                            <td class="col-cb"><input type="checkbox" class="file-cb" onchange="updateToolbar()"></td>
                            <td>
                                <div class="row-name">
                                    <i class="<?php echo e($icon); ?>" style="color:<?php echo e($iconColor); ?>;"></i>
                                    <?php if($isDir): ?>
                                        <a
                                            href="<?php echo e(route('files', ['domain' => $domain, 'root' => $basePath, 'dir' => $dir . '/' . $fname])); ?>"
                                            onclick="progressStart('Opening <?php echo e($fname); ?>...')"><?php echo e($fname); ?></a>
                                    <?php else: ?>
                                        <span style="cursor:pointer;" ondblclick="editSingle('<?php echo e($fname); ?>')"><?php echo e($fname); ?></span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td style="color:var(--text-muted); font-size:0.8rem;"><?php echo e($size); ?></td>
                            <td style="color:var(--text-muted); font-size:0.8rem;"><?php echo e($mtime); ?></td>
                            <td style="color:var(--text-muted); font-size:0.8rem;"><?php echo e($isDir ? 'Folder' : strtoupper($ext ?: '-')); ?>

                            </td>
                            <td style="color:var(--text-muted); font-size:0.8rem; font-family:monospace;"><?php echo e($perms); ?></td>
                            <td>
                                <div class="row-actions">
                                    <?php if(!$isDir): ?>
                                        <button title="Edit" onclick="editSingle('<?php echo e($fname); ?>')"><i
                                                class="fas fa-pencil-alt"></i></button>
                                    <?php endif; ?>
                                    <?php if($isZip): ?>
                                        <button title="Extract" onclick="doExtract('<?php echo e($fname); ?>')" style="color:#e67e22;"><i
                                                class="fas fa-file-archive"></i></button>
                                    <?php endif; ?>
                                    <button title="Rename" onclick="showRenameFor('<?php echo e($fname); ?>')"><i
                                            class="fas fa-i-cursor"></i></button>
                                    <button title="Delete" onclick="deleteSingle('<?php echo e($fname); ?>')" style="color:#e74c3c;"><i
                                            class="fas fa-trash-alt"></i></button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </tbody>
            </table>
            <div style="padding: 8px 12px; font-size: 0.8rem; color: var(--text-muted);">
                <?php echo e(count($files)); ?> item(s) &middot; <span id="selInfo">0 selected</span>
            </div>
        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-folder-open" style="font-size:3rem; color:var(--text-muted); margin-bottom:1rem;"></i>
                <p style="color:var(--text-muted);">This directory is empty.</p>
            </div>
        <?php endif; ?>
    </div>

    <!-- ====== UPLOAD MODAL ====== -->
    <input type="file" id="fileInput" style="display:none" onchange="startUpload(this.files[0])">
    <div class="overlay" id="modalUpload">
        <div class="overlay-box">
            <h3><i class="fas fa-cloud-upload-alt" style="color:var(--primary);"></i> Upload File</h3>
            <div class="drop-zone" id="dropZone" onclick="document.getElementById('fileInput').click()">
                <i class="fas fa-cloud-upload-alt" style="font-size:2rem; color:var(--primary); margin-bottom:0.5rem;"></i>
                <p style="font-weight:600;">Drag &amp; Drop file here</p>
                <p style="color:var(--text-muted); font-size:0.8rem;">or click to browse</p>
            </div>
            <p id="uploadFileName" style="font-size:0.85rem; color:var(--primary); margin:0.8rem 0 0;"></p>
            <div class="btn-row" style="margin-top:1rem;">
                <button type="button" class="btn-cancel" onclick="closeModal('modalUpload')">Cancel</button>
                <button type="button" class="btn-ok" onclick="document.getElementById('fileInput').click()">Choose File</button>
            </div>
        </div>
    </div>

    <!-- ====== NEW FILE MODAL ====== -->
    <div class="overlay" id="modalNewFile">
        <div class="overlay-box">
            <h3><i class="fas fa-file-medical" style="color:var(--primary);"></i> Create New File</h3>
            <input type="text" class="form-input" id="newFileName" placeholder="filename.html">
            <div class="btn-row">
                <button class="btn-cancel" onclick="closeModal('modalNewFile')">Cancel</button>
                <button class="btn-ok" onclick="doCreateFile()">Create</button>
            </div>
        </div>
    </div>

    <!-- ====== NEW FOLDER MODAL ====== -->
    <div class="overlay" id="modalNewFolder">
        <div class="overlay-box">
            <h3><i class="fas fa-folder-plus" style="color:#fbbf24;"></i> Create New Folder</h3>
            <input type="text" class="form-input" id="newFolderName" placeholder="new-folder">
            <div class="btn-row">
                <button class="btn-cancel" onclick="closeModal('modalNewFolder')">Cancel</button>
                <button class="btn-ok" onclick="doCreateFolder()">Create</button>
            </div>
        </div>
    </div>

    <!-- ====== RENAME MODAL ====== -->
    <div class="overlay" id="modalRename">
        <div class="overlay-box">
            <h3><i class="fas fa-i-cursor" style="color:#f1c40f;"></i> Rename</h3>
            <input type="hidden" id="renameOldName">
            <input type="text" class="form-input" id="renameNewName" placeholder="New name">
            <div class="btn-row">
                <button class="btn-cancel" onclick="closeModal('modalRename')">Cancel</button>
                <button class="btn-ok" onclick="doRename()">Rename</button>
            </div>
        </div>
    </div>



    <!-- ====== COMPRESS MODAL ====== -->
    <div class="overlay" id="modalCompress">
        <div class="overlay-box">
            <h3><i class="fas fa-compress-arrows-alt" style="color:#e67e22;"></i> Compress & Download</h3>
            <p style="color:var(--text-muted); font-size:0.85rem; margin-bottom:0.8rem;" id="compressInfo">Compressing 0 items — All files will be in the zip root, no subfolders.</p>
            <input type="text" class="form-input" id="compressName" placeholder="archive.zip">
            <div class="btn-row">
                <button class="btn-cancel" onclick="closeModal('modalCompress')">Cancel</button>
                <button class="btn-ok" onclick="doCompress()">Compress & Download</button>
            </div>
        </div>
    </div>

    <!-- ====== PERMISSIONS MODAL ====== -->
    <div class="overlay" id="modalPerms">
        <div class="overlay-box">
            <h3><i class="fas fa-key" style="color:#9b59b6;"></i> Change Permissions</h3>
            <p style="color:var(--text-muted); font-size:0.85rem; margin-bottom:1rem;" id="permsFileName">file.txt</p>
            <input type="hidden" id="permsFile">
            <div class="perm-grid">
                <div class="perm-group">
                    <h4>Owner</h4>
                    <label><input type="checkbox" id="perm-owner-r" checked onchange="updatePermCode()"> Read</label>
                    <label><input type="checkbox" id="perm-owner-w" checked onchange="updatePermCode()"> Write</label>
                    <label><input type="checkbox" id="perm-owner-x" onchange="updatePermCode()"> Execute</label>
                </div>
                <div class="perm-group">
                    <h4>Group</h4>
                    <label><input type="checkbox" id="perm-group-r" checked onchange="updatePermCode()"> Read</label>
                    <label><input type="checkbox" id="perm-group-w" onchange="updatePermCode()"> Write</label>
                    <label><input type="checkbox" id="perm-group-x" onchange="updatePermCode()"> Execute</label>
                </div>
                <div class="perm-group">
                    <h4>World</h4>
                    <label><input type="checkbox" id="perm-world-r" checked onchange="updatePermCode()"> Read</label>
                    <label><input type="checkbox" id="perm-world-w" onchange="updatePermCode()"> Write</label>
                    <label><input type="checkbox" id="perm-world-x" onchange="updatePermCode()"> Execute</label>
                </div>
            </div>
            <input type="text" class="form-input" id="permCode" value="0644"
                style="font-family:monospace; font-size:1.1rem; text-align:center;">
            <div class="btn-row">
                <button class="btn-cancel" onclick="closeModal('modalPerms')">Cancel</button>
                <button class="btn-ok" onclick="doChangePerms()">Change Permissions</button>
            </div>
        </div>
    </div>

    <!-- ====== EDITOR ====== -->
    <div class="editor-overlay" id="editorPanel">
        <div class="editor-box">
            <div class="editor-header">
                <h3 style="font-size:0.95rem;"><i class="fas fa-code" style="color:var(--primary);"></i> <span
                        id="editorTitle">file.txt</span></h3>
                <div style="display:flex; gap:0.5rem;">
                    <button class="cp-btn" style="background:var(--primary); color:#fff; border-radius:6px;"
                        onclick="saveFile()"><i class="fas fa-save"></i> Save</button>
                    <button class="cp-btn" style="border:1px solid var(--border); border-radius:6px;"
                        onclick="closeEditor()"><i class="fas fa-times"></i> Close</button>
                </div>
            </div>
            <div class="editor-body"><textarea id="editorArea"></textarea></div>
        </div>
    </div>

    <!-- UPLOAD PROGRESS OVERLAY -->
    <div id="uploadProgressOverlay">
        <div id="uploadProgressBox">
            <div class="up-cloud-wrap">
                <div class="up-cloud-bg"><i id="upIcon" class="fas fa-cloud-upload-alt"></i></div>
                <div class="up-particles">
                    <span></span><span></span><span></span><span></span>
                </div>
            </div>
            <div class="up-filename" id="upFileName">Uploading...</div>
            <div class="up-filesize" id="upFileSize"></div>
            <div class="up-track"><div class="up-track-fill indeterminate" id="upFill"></div></div>
            <div class="up-stats">
                <span id="upTransferred"></span>
                <span class="up-pct" id="upPct">0%</span>
            </div>
            <div class="up-status" id="upStatus">Connecting...</div>
        </div>
    </div>

    <!-- CUSTOM CONFIRM MODAL -->
    <div id="confirmOverlay">
        <div id="confirmBox">
            <div id="confirmIconWrap" class="danger"><i id="confirmIcon" class="fas fa-trash-alt"></i></div>
            <div id="confirmTitle">Are you sure?</div>
            <div id="confirmMsg">This action cannot be undone.</div>
            <div class="confirm-btns">
                <button class="cb-cancel" id="confirmCancelBtn">Cancel</button>
                <button class="cb-ok" id="confirmOkBtn">Confirm</button>
            </div>
        </div>
    </div>

    <!-- TOP PROGRESS BAR -->
    <div id="nprogress-bar"></div>

    <!-- PRELOADER OVERLAY -->
    <div id="preloader">
        <div class="pl-rings">
            <div class="ring ring-1"></div>
            <div class="ring ring-2"></div>
            <div class="ring ring-3"></div>
            <div class="ring-dot"></div>
        </div>
        <div class="pl-label" id="action-label">Processing...</div>
        <div class="pl-dots">
            <span></span><span></span><span></span>
        </div>
    </div>

    <!-- TOAST -->
    <div class="toast" id="toast"></div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/javascript/javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/php/php.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/css/css.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/xml/xml.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/htmlmixed/htmlmixed.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/clike/clike.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/sql/sql.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/python/python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/markdown/markdown.min.js"></script>

    <script>
        const DIR = <?php echo json_encode($dir, 15, 512) ?>;
        const DOMAIN = <?php echo json_encode($domain, 15, 512) ?>;
        const BASE = <?php echo json_encode($root ?? $domain, 15, 512) ?>;
        const CSRF = "<?php echo e(csrf_token()); ?>";
        let editor = null, editingFile = null;

        // Convert full path to display path (hide public_html)
        function displayPath(fullPath) {
            return fullPath.replace(BASE, '/' + DOMAIN).replace(/\/+/g, '/');
        }

        // Convert user input path to full server path
        function toFullPath(userInput) {
            userInput = userInput.trim();
            // If user types "/" meaning domain root
            if (userInput === '/' || userInput === '') return BASE;
            // Remove leading slash if present
            if (userInput.startsWith('/')) userInput = userInput.substring(1);
            return BASE + '/' + userInput;
        }

        // ========== PRELOADER ==========
        let _pTimer = null, _pDone = false;
        function progressStart(label) {
            const bar    = document.getElementById('nprogress-bar');
            const loader = document.getElementById('preloader');
            const lbl    = document.getElementById('action-label');
            clearTimeout(_pTimer);
            _pDone = false;
            lbl.textContent = label || 'Processing...';
            // Top bar
            bar.style.transition = 'none';
            bar.style.width = '0%';
            bar.classList.add('running');
            requestAnimationFrame(() => {
                bar.style.transition = 'width 0.7s ease';
                bar.style.width = '45%';
                _pTimer = setTimeout(() => {
                    bar.style.transition = 'width 2s ease';
                    bar.style.width = '80%';
                }, 720);
            });
            // Overlay
            loader.classList.add('active');
        }
        function progressDone() {
            if (_pDone) return;
            _pDone = true;
            clearTimeout(_pTimer);
            const bar    = document.getElementById('nprogress-bar');
            const loader = document.getElementById('preloader');
            // Complete bar
            bar.style.transition = 'width 0.18s ease';
            bar.style.width = '100%';
            // Hide overlay
            loader.classList.remove('active');
            setTimeout(() => {
                bar.style.transition = 'opacity 0.3s ease';
                bar.style.opacity = '0';
                bar.classList.remove('running');
                setTimeout(() => { bar.style.width = '0%'; bar.style.opacity = ''; }, 350);
            }, 200);
        }

        // ========== CUSTOM CONFIRM ==========
        function showConfirm({ title, msg, icon, type, okLabel } = {}) {
            return new Promise(resolve => {
                const overlay  = document.getElementById('confirmOverlay');
                const iconWrap = document.getElementById('confirmIconWrap');
                const iconEl   = document.getElementById('confirmIcon');
                const okBtn    = document.getElementById('confirmOkBtn');
                document.getElementById('confirmTitle').textContent = title || 'Are you sure?';
                document.getElementById('confirmMsg').textContent   = msg   || 'This action cannot be undone.';
                iconWrap.className = 'danger';
                if (type) { iconWrap.className = type; okBtn.className = 'cb-ok ' + type; }
                else       { iconWrap.className = 'danger'; okBtn.className = 'cb-ok'; }
                iconEl.className = icon || 'fas fa-exclamation-triangle';
                okBtn.textContent = okLabel || 'Confirm';
                overlay.classList.add('open');
                const finish = (val) => {
                    overlay.classList.remove('open');
                    okBtn.replaceWith(okBtn.cloneNode(true));
                    document.getElementById('confirmCancelBtn').replaceWith(document.getElementById('confirmCancelBtn').cloneNode(true));
                    resolve(val);
                };
                document.getElementById('confirmOkBtn').addEventListener('click', () => finish(true),  { once: true });
                document.getElementById('confirmCancelBtn').addEventListener('click', () => finish(false), { once: true });
            });
        }

        // ========== HELPERS ==========
        function openModal(id) { document.getElementById(id).style.display = 'block'; }
        function closeModal(id) { document.getElementById(id).style.display = 'none'; }
        function toast(msg, type) {
            const t = document.getElementById('toast');
            t.className = 'toast ' + (type || 'ok');
            t.innerText = msg;
            t.style.display = 'block';
            setTimeout(() => t.style.display = 'none', 3000);
        }
        async function api(url, body, label) {
            progressStart(label || 'Processing...');
            try {
                const res = await fetch(url, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                    body: JSON.stringify(body)
                });
                const data = await res.json();
                progressDone();
                return data;
            } catch (e) {
                progressDone();
                throw e;
            }
        }
        function getSelected() {
            return Array.from(document.querySelectorAll('.file-cb:checked')).map(cb => {
                const tr = cb.closest('tr');
                return { name: tr.dataset.name, type: tr.dataset.type, zip: tr.dataset.zip === '1' };
            });
        }
        function getSelectedNames() { return getSelected().map(f => f.name); }

        // ========== SELECTION ==========
        function toggleAll(master) {
            document.querySelectorAll('.file-cb').forEach(cb => cb.checked = master.checked);
            updateToolbar();
        }
        function selectAll() {
            document.querySelectorAll('.file-cb').forEach(cb => cb.checked = true);
            if (document.getElementById('cbAll')) document.getElementById('cbAll').checked = true;
            updateToolbar();
        }
        function unselectAll() {
            document.querySelectorAll('.file-cb').forEach(cb => cb.checked = false);
            if (document.getElementById('cbAll')) document.getElementById('cbAll').checked = false;
            updateToolbar();
        }
        function updateToolbar() {
            const sel = getSelected();
            const count = sel.length;
            const single = count === 1;
            const singleFile = single && sel[0].type === 'file';
            const hasZip = sel.some(f => f.zip);

            document.getElementById('btnCopy').disabled = count === 0;
            document.getElementById('btnCut').disabled = count === 0;
            document.getElementById('btnDelete').disabled = count === 0;
            document.getElementById('btnRename').disabled = !single;
            document.getElementById('btnEdit').disabled = !singleFile;
            document.getElementById('btnHtmlEdit').disabled = !singleFile;
            document.getElementById('btnPerms').disabled = !single;
            document.getElementById('btnView').disabled = !singleFile;
            document.getElementById('btnExtract').disabled = !(single && hasZip);
            document.getElementById('btnCompress').disabled = count === 0;

            document.getElementById('selInfo').innerText = count + ' selected';
            document.querySelectorAll('#fileBody tr').forEach(tr => {
                tr.classList.toggle('selected', tr.querySelector('.file-cb')?.checked);
            });
        }

        // ========== NAVIGATION ==========
        function navigate(url, label) { progressStart(label || 'Loading...'); window.location.href = url; }
        function goHome() { navigate(`<?php echo e(route('files')); ?>?domain=${DOMAIN}&root=${BASE}&dir=${BASE}`, 'Going Home...'); }
        function goUp() {
            const parts = DIR.split('/');
            if (parts.length > 2) {
                parts.pop();
                const upDir = parts.join('/');
                if (upDir.startsWith(BASE) || upDir === BASE.substring(0, BASE.lastIndexOf('/'))) {
                    if (upDir.length >= BASE.length) {
                        navigate(`<?php echo e(route('files')); ?>?domain=${DOMAIN}&root=${BASE}&dir=${upDir}`, 'Going Up...');
                    }
                }
            }
        }

        // ========== CREATE FILE ==========
        function showNewFileModal() { document.getElementById('newFileName').value = ''; openModal('modalNewFile'); setTimeout(() => document.getElementById('newFileName').focus(), 100); }
        async function doCreateFile() {
            const name = document.getElementById('newFileName').value.trim();
            if (!name) return;
            const data = await api("<?php echo e(route('files.newfile')); ?>", { dir: DIR, file_name: name }, 'Creating File...');
            if (data.success) { toast('File created!'); setTimeout(() => location.reload(), 600); }
            else toast(data.message || 'Failed', 'err');
            closeModal('modalNewFile');
        }

        // ========== CREATE FOLDER ==========
        function showNewFolderModal() { document.getElementById('newFolderName').value = ''; openModal('modalNewFolder'); setTimeout(() => document.getElementById('newFolderName').focus(), 100); }
        async function doCreateFolder() {
            const name = document.getElementById('newFolderName').value.trim();
            if (!name) return;
            closeModal('modalNewFolder');
            const data = await api("<?php echo e(route('files.folder')); ?>", { dir: DIR, folder_name: name }, 'Creating Folder...');
            if (data.success) { toast('Folder created!'); setTimeout(() => location.reload(), 600); }
            else toast(data.message || 'Failed to create folder', 'err');
        }

        // ========== DELETE ==========
        async function deleteSelected() {
            const files = getSelectedNames();
            if (!files.length) return;
            const ok = await showConfirm({
                title: `Delete ${files.length} item(s)?`,
                msg: `"${files.slice(0,3).join('", "')}"${files.length > 3 ? ` and ${files.length - 3} more` : ''} will be permanently removed.`,
                icon: 'fas fa-trash-alt', type: 'danger', okLabel: 'Delete'
            });
            if (ok) await doDelete(files);
        }
        async function deleteSingle(name) {
            const ok = await showConfirm({
                title: `Delete "${name}"?`,
                msg: 'This file will be permanently removed.',
                icon: 'fas fa-trash-alt', type: 'danger', okLabel: 'Delete'
            });
            if (ok) doDelete([name]);
        }
        async function doDelete(files) {
            const data = await api("<?php echo e(route('files.delete')); ?>", { files, dir: DIR }, `Deleting ${files.length} item(s)...`);
            if (data.success) { toast('Deleted!'); setTimeout(() => location.reload(), 600); }
            else toast(data.message || 'Failed', 'err');
        }

        // ========== RENAME ==========
        function showRenameModal() {
            const sel = getSelected();
            if (sel.length !== 1) return;
            showRenameFor(sel[0].name);
        }
        function showRenameFor(name) {
            document.getElementById('renameOldName').value = name;
            document.getElementById('renameNewName').value = name;
            openModal('modalRename');
            setTimeout(() => document.getElementById('renameNewName').select(), 100);
        }
        async function doRename() {
            const oldN = document.getElementById('renameOldName').value;
            const newN = document.getElementById('renameNewName').value.trim();
            if (!newN || oldN === newN) { closeModal('modalRename'); return; }
            const data = await api("<?php echo e(route('files.rename')); ?>", { dir: DIR, old_name: oldN, new_name: newN }, 'Renaming...');
            if (data.success) { toast('Renamed!'); setTimeout(() => location.reload(), 600); }
            else toast(data.message || 'Failed', 'err');
            closeModal('modalRename');
        }

        // ========== CLIPBOARD COPY / CUT / PASTE ==========
        function clipboardCopy() {
            const files = getSelectedNames();
            if (!files.length) return;
            const clipData = { op: 'copy', files: files, sourceDir: DIR };
            sessionStorage.setItem('fm_clipboard', JSON.stringify(clipData));
            toast(`📋 ${files.length} item(s) copied to clipboard`);
            updateClipboardUI();
            unselectAll();
        }
        function clipboardCut() {
            const files = getSelectedNames();
            if (!files.length) return;
            const clipData = { op: 'move', files: files, sourceDir: DIR };
            sessionStorage.setItem('fm_clipboard', JSON.stringify(clipData));
            toast(`✂️ ${files.length} item(s) cut to clipboard`);
            updateClipboardUI();
            unselectAll();
        }
        async function clipboardPaste() {
            const raw = sessionStorage.getItem('fm_clipboard');
            if (!raw) return;
            const clip = JSON.parse(raw);
            if (!clip.files || !clip.files.length) return;
            
            const opLabel = clip.op === 'copy' ? 'Copying' : 'Moving';
            toast(`${opLabel} ${clip.files.length} item(s)...`);
            
            const url = clip.op === 'copy' ? "<?php echo e(route('files.copy')); ?>" : "<?php echo e(route('files.move')); ?>";
            const data = await api(url, { files: clip.files, dir: clip.sourceDir, dest: DIR }, clip.op === 'copy' ? 'Copying...' : 'Moving...');
            
            if (data.success) {
                // Clear clipboard after move (cut), keep after copy
                if (clip.op === 'move') {
                    sessionStorage.removeItem('fm_clipboard');
                }
                toast(clip.op === 'copy' ? '✅ Pasted (copied)!' : '✅ Pasted (moved)!');
                setTimeout(() => location.reload(), 600);
            } else {
                toast(data.message || 'Paste failed', 'err');
            }
        }
        function clipboardClear() {
            sessionStorage.removeItem('fm_clipboard');
            updateClipboardUI();
            toast('Clipboard cleared');
        }
        function updateClipboardUI() {
            const raw = sessionStorage.getItem('fm_clipboard');
            const bar = document.getElementById('clipboardBar');
            const pasteBtn = document.getElementById('btnPaste');
            
            if (raw) {
                const clip = JSON.parse(raw);
                const opIcon = clip.op === 'copy' ? '📋 Copied' : '✂️ Cut';
                // Show source path nicely
                let srcDisplay = '~/' + clip.sourceDir.replace(/^\//, '');
                const info = `${opIcon}: ${clip.files.length} item(s) from ${srcDisplay}`;
                document.getElementById('clipboardInfo').innerText = info;
                bar.style.display = 'flex';
                pasteBtn.style.display = '';
                pasteBtn.disabled = false;
            } else {
                bar.style.display = 'none';
                pasteBtn.style.display = 'none';
                pasteBtn.disabled = true;
            }
        }
        // Initialize clipboard UI on page load
        updateClipboardUI();

        // ========== EXTRACT ==========
        function extractSelected() {
            const sel = getSelected();
            if (sel.length === 1 && sel[0].zip) doExtract(sel[0].name);
        }
        async function doExtract(name) {
            const ok = await showConfirm({
                title: `Extract "${name}"?`,
                msg: 'Files will be extracted to the current directory.',
                icon: 'fas fa-file-archive', type: 'info', okLabel: 'Extract'
            });
            if (!ok) return;
            const data = await api("<?php echo e(route('files.extract')); ?>", { file: name, dir: DIR }, 'Extracting...');
            if (data.success) { toast('Extracted!'); setTimeout(() => location.reload(), 1000); }
            else toast(data.message || 'Failed', 'err');
        }

        // ========== COMPRESS (flat zip + download) ==========
        function showCompressModal() {
            const sel = getSelected();
            document.getElementById('compressInfo').innerText = `Compressing ${sel.length} item(s) — All files will be in the zip root, no subfolders.`;
            document.getElementById('compressName').value = 'archive.zip';
            openModal('modalCompress');
        }
        async function doCompress() {
            const name = document.getElementById('compressName').value.trim();
            const selected = getSelected();
            if (!name || !selected.length) return;
            progressStart('Compressing & Downloading...');
            const body = { dir: DIR, archive_name: name, selected: selected.map(f => ({ name: f.name, type: f.type })) };
            try {
                const res = await fetch("<?php echo e(route('files.compress.download')); ?>", {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                    body: JSON.stringify(body)
                });
                progressDone();
                if (!res.ok) {
                    const err = await res.json().catch(() => ({}));
                    toast(err.message || 'Compress failed', 'err');
                    return;
                }
                const blob = await res.blob();
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = name.match(/\.zip$/i) ? name : name + '.zip';
                a.click();
                URL.revokeObjectURL(url);
                toast('Zip downloaded!');
            } catch (e) {
                progressDone();
                toast(e.message || 'Failed', 'err');
            }
        }

        // ========== PERMISSIONS ==========
        function showPermissionsModal() {
            const sel = getSelected();
            if (sel.length !== 1) return;
            document.getElementById('permsFile').value = sel[0].name;
            document.getElementById('permsFileName').innerText = sel[0].name;
            document.getElementById('permCode').value = '0644';
            openModal('modalPerms');
        }
        function updatePermCode() {
            let code = 0;
            if (document.getElementById('perm-owner-r').checked) code += 400;
            if (document.getElementById('perm-owner-w').checked) code += 200;
            if (document.getElementById('perm-owner-x').checked) code += 100;
            if (document.getElementById('perm-group-r').checked) code += 40;
            if (document.getElementById('perm-group-w').checked) code += 20;
            if (document.getElementById('perm-group-x').checked) code += 10;
            if (document.getElementById('perm-world-r').checked) code += 4;
            if (document.getElementById('perm-world-w').checked) code += 2;
            if (document.getElementById('perm-world-x').checked) code += 1;
            document.getElementById('permCode').value = '0' + code.toString();
        }
        async function doChangePerms() {
            const file = document.getElementById('permsFile').value;
            const perms = document.getElementById('permCode').value;
            const data = await api("<?php echo e(route('files.permissions')); ?>", { file, dir: DIR, perms }, 'Changing Permissions...');
            if (data.success) { toast('Permissions changed!'); setTimeout(() => location.reload(), 600); }
            else toast(data.message || 'Failed', 'err');
            closeModal('modalPerms');
        }

        // ========== VIEW FILE ==========
        function viewSelected() {
            const sel = getSelected();
            if (sel.length === 1 && sel[0].type === 'file') editSingle(sel[0].name);
        }

        // ========== DOWNLOAD ==========
        function downloadSelected() {
            const sel = getSelected();
            if (sel.length === 1 && sel[0].type === 'file') {
                const name = sel[0].name;
                const url = `<?php echo e(route('files.download')); ?>?file=${encodeURIComponent(name)}&dir=${encodeURIComponent(DIR)}`;
                window.location.href = url;
            }
        }

        // ========== EDIT ==========
        function editSelected() {
            const sel = getSelected();
            if (sel.length === 1 && sel[0].type === 'file') editSingle(sel[0].name);
        }
        async function editSingle(name) {
            editingFile = name;
            document.getElementById('editorTitle').innerText = name;
            document.getElementById('editorPanel').style.display = 'block';

            if (!editor) {
                editor = CodeMirror.fromTextArea(document.getElementById('editorArea'), {
                    lineNumbers: true, theme: 'dracula', mode: getModeForFile(name),
                    indentUnit: 4, lineWrapping: true, matchBrackets: true
                });
            } else {
                editor.setOption('mode', getModeForFile(name));
            }
            editor.setValue('Loading...');

            try {
                const res = await fetch(`<?php echo e(route('files.edit')); ?>?file=${encodeURIComponent(name)}&dir=${encodeURIComponent(DIR)}`);
                const data = await res.json();
                if (data.success) { editor.setValue(data.content); editor.refresh(); }
                else { toast('Failed to load.', 'err'); closeEditor(); }
            } catch (e) { toast('Connection error.', 'err'); closeEditor(); }
        }
        async function saveFile() {
            if (!editingFile || !editor) return;
            const data = await api("<?php echo e(route('files.save')); ?>", { file: editingFile, dir: DIR, content: editor.getValue() }, 'Saving File...');
            if (data.success) toast('Saved!');
            else toast('Save failed.', 'err');
        }
        function closeEditor() { document.getElementById('editorPanel').style.display = 'none'; editingFile = null; }
        function getModeForFile(name) {
            const ext = name.split('.').pop().toLowerCase();
            const modes = { php: 'application/x-httpd-php', js: 'javascript', css: 'css', html: 'htmlmixed', htm: 'htmlmixed', xml: 'xml', json: 'javascript', sql: 'text/x-sql', py: 'python', md: 'markdown', txt: 'text/plain' };
            return modes[ext] || 'text/plain';
        }

        // ========== UPLOAD WITH PROGRESS OVERLAY ==========
        function showUploadModal() { openModal('modalUpload'); }

        function fmtBytes(b) {
            if (b < 1024) return b + ' B';
            if (b < 1048576) return (b/1024).toFixed(1) + ' KB';
            return (b/1048576).toFixed(2) + ' MB';
        }

        function startUpload(file) {
            if (!file) return;
            closeModal('modalUpload');
            const overlay = document.getElementById('uploadProgressOverlay');
            const box     = document.getElementById('uploadProgressBox');
            const fill    = document.getElementById('upFill');
            box.className = '';
            document.getElementById('upIcon').className = 'fas fa-cloud-upload-alt';
            document.getElementById('upFileName').textContent  = file.name;
            document.getElementById('upFileSize').textContent  = fmtBytes(file.size);
            document.getElementById('upPct').textContent       = '0%';
            document.getElementById('upTransferred').textContent = '0 B / ' + fmtBytes(file.size);
            document.getElementById('upStatus').textContent    = 'Uploading...';
            fill.className = 'up-track-fill';
            fill.style.width = '0%';
            overlay.classList.add('open');

            const fd = new FormData();
            fd.append('file', file);
            fd.append('dir', DIR);
            fd.append('domain', DOMAIN);
            fd.append('_token', CSRF);

            const xhr = new XMLHttpRequest();
            const startTime = Date.now();

            xhr.upload.addEventListener('progress', e => {
                if (!e.lengthComputable) return;
                const pct = Math.round(e.loaded / e.total * 100);
                fill.style.width = pct + '%';
                document.getElementById('upPct').textContent = pct + '%';
                document.getElementById('upTransferred').textContent = fmtBytes(e.loaded) + ' / ' + fmtBytes(e.total);
                const elapsed = (Date.now() - startTime) / 1000;
                if (elapsed > 0.3) {
                    const speed = e.loaded / elapsed;
                    document.getElementById('upStatus').textContent = fmtBytes(speed) + '/s uploading...';
                }
            });

            xhr.addEventListener('load', () => {
                document.getElementById('fileInput').value = '';
                try {
                    const res = JSON.parse(xhr.responseText);
                    if (res.success) {
                        box.classList.add('done');
                        document.getElementById('upIcon').className = 'fas fa-check';
                        document.getElementById('upPct').textContent = '100%';
                        fill.style.width = '100%';
                        document.getElementById('upStatus').textContent = 'Upload complete!';
                        setTimeout(() => { overlay.classList.remove('open'); location.reload(); }, 1200);
                    } else {
                        showUploadError(res.message || 'Upload failed.');
                    }
                } catch(e) { showUploadError('Upload failed.'); }
            });
            xhr.addEventListener('error', () => showUploadError('Network error.'));
            xhr.addEventListener('abort', () => overlay.classList.remove('open'));
            xhr.open('POST', "<?php echo e(route('files.upload')); ?>");
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.send(fd);
        }

        function showUploadError(msg) {
            const box = document.getElementById('uploadProgressBox');
            box.classList.add('error');
            document.getElementById('upIcon').className = 'fas fa-times';
            document.getElementById('upStatus').textContent = msg;
            document.getElementById('upPct').textContent = '✗';
            setTimeout(() => document.getElementById('uploadProgressOverlay').classList.remove('open'), 2500);
        }

        const dz = document.getElementById('dropZone');
        if (dz) {
            dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('dragover'); });
            dz.addEventListener('dragleave', () => dz.classList.remove('dragover'));
            dz.addEventListener('drop', e => {
                e.preventDefault(); dz.classList.remove('dragover');
                if (e.dataTransfer.files[0]) startUpload(e.dataTransfer.files[0]);
            });
        }

        // ========== KEYBOARD SHORTCUTS ==========
        document.addEventListener('keydown', e => {
            if (e.key === 'Escape') { closeEditor(); document.querySelectorAll('.overlay').forEach(o => o.style.display = 'none'); }
            if (e.ctrlKey && e.key === 's' && editingFile) { e.preventDefault(); saveFile(); }
            if (e.ctrlKey && e.key === 'a' && !editingFile) { e.preventDefault(); selectAll(); }
            if (e.ctrlKey && e.key === 'c' && !editingFile) { e.preventDefault(); clipboardCopy(); }
            if (e.ctrlKey && e.key === 'x' && !editingFile) { e.preventDefault(); clipboardCut(); }
            if (e.ctrlKey && e.key === 'v' && !editingFile) { e.preventDefault(); clipboardPaste(); }
        });

        // Close overlays by clicking backdrop
        document.querySelectorAll('.overlay').forEach(o => {
            o.addEventListener('click', e => { if (e.target === o) o.style.display = 'none'; });
        });
    </script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.dashboard', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Program Files\Ampps\www\resources\views/dashboard/files.blade.php ENDPATH**/ ?>