<?php $__env->startSection('styles'); ?>
    <style>
        /* ── Variables ── */
        :root {
            --ad-blue: #58a6ff;
            --ad-green: #3fb950;
            --ad-red: #f85149;
            --ad-yellow: #d29922;
            --ad-purple: #a371f7;
            --ad-surface: #161b22;
            --ad-border: #30363d;
            --ad-muted: #8b949e;
        }

        /* ── Page header ── */
        .ad-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 12px;
            margin-bottom: 24px;
        }

        .ad-header h2 {
            font-size: 1.15rem;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .ad-header h2 i {
            color: var(--ad-purple);
        }

        /* ── Tabs ── */
        .ad-tabs {
            display: flex;
            gap: 4px;
            background: rgba(255, 255, 255, .04);
            border: 1px solid var(--ad-border);
            border-radius: 12px;
            padding: 4px;
            margin-bottom: 24px;
            flex-wrap: wrap;
        }

        .ad-tab {
            padding: 8px 20px;
            border-radius: 8px;
            border: none;
            background: transparent;
            color: var(--ad-muted);
            cursor: pointer;
            font-size: .82rem;
            font-weight: 600;
            transition: all .15s;
            display: flex;
            align-items: center;
            gap: 7px;
            font-family: inherit;
            position: relative;
        }

        .ad-tab.active {
            background: #6366f1;
            color: #fff;
            box-shadow: 0 4px 12px rgba(99, 102, 241, .35);
        }

        .ad-tab .badge {
            position: absolute;
            top: 4px;
            right: 4px;
            min-width: 16px;
            height: 16px;
            border-radius: 8px;
            background: #ef4444;
            color: #fff;
            font-size: .6rem;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0 4px;
        }

        .ad-panel {
            display: none;
        }

        .ad-panel.active {
            display: block;
        }

        /* ── Stats row ── */
        .ad-stats {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 12px;
            margin-bottom: 24px;
        }

        .ad-stat {
            background: var(--ad-surface);
            border: 1px solid var(--ad-border);
            border-radius: 12px;
            padding: 16px;
        }

        .ad-stat-val {
            font-size: 1.6rem;
            font-weight: 700;
            margin-bottom: 4px;
        }

        .ad-stat-label {
            font-size: .72rem;
            color: var(--ad-muted);
            text-transform: uppercase;
            letter-spacing: .06em;
        }

        /* ── Table ── */
        .ad-table-wrap {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        .ad-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 700px;
        }

        .ad-table th {
            padding: 9px 14px;
            font-size: .7rem;
            font-weight: 700;
            color: var(--ad-muted);
            text-transform: uppercase;
            letter-spacing: .07em;
            border-bottom: 1px solid var(--ad-border);
            text-align: left;
            white-space: nowrap;
        }

        .ad-table td {
            padding: 12px 14px;
            font-size: .82rem;
            border-bottom: 1px solid rgba(255, 255, 255, .04);
            vertical-align: middle;
        }

        .ad-table tr:last-child td {
            border-bottom: none;
        }

        .ad-table tr:hover td {
            background: rgba(255, 255, 255, .02);
        }

        /* Status badges */
        .st-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 3px 10px;
            border-radius: 20px;
            font-size: .7rem;
            font-weight: 700;
        }

        .st-active {
            background: rgba(63, 185, 80, .12);
            color: #3fb950;
            border: 1px solid rgba(63, 185, 80, .2);
        }

        .st-suspended {
            background: rgba(245, 158, 11, .12);
            color: #f59e0b;
            border: 1px solid rgba(245, 158, 11, .2);
        }

        .st-expired {
            background: rgba(248, 81, 73, .12);
            color: #f85149;
            border: 1px solid rgba(248, 81, 73, .2);
        }

        .st-dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: currentColor;
        }

        /* Action buttons */
        .ad-btn {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 5px 12px;
            border-radius: 7px;
            border: none;
            font-size: .75rem;
            font-weight: 700;
            cursor: pointer;
            font-family: inherit;
            transition: all .13s;
        }

        .ad-btn.edit {
            background: rgba(88, 166, 255, .1);
            color: var(--ad-blue);
        }

        .ad-btn.edit:hover {
            background: rgba(88, 166, 255, .2);
        }

        .ad-btn.danger {
            background: rgba(248, 81, 73, .1);
            color: var(--ad-red);
        }

        .ad-btn.danger:hover {
            background: rgba(248, 81, 73, .2);
        }

        .ad-btn.chat {
            background: rgba(99, 102, 241, .1);
            color: #818cf8;
        }

        .ad-btn.chat:hover {
            background: rgba(99, 102, 241, .2);
        }

        .ad-btn.primary {
            background: #6366f1;
            color: #fff;
        }

        .ad-btn.primary:hover {
            background: #4f46e5;
        }

        .ad-btn.success {
            background: rgba(63, 185, 80, .12);
            color: #3fb950;
        }

        .ad-btn.success:hover {
            background: rgba(63, 185, 80, .2);
        }

        /* Create form */
        .ad-form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 12px;
        }

        .ad-field label {
            display: block;
            font-size: .72rem;
            color: var(--ad-muted);
            margin-bottom: 4px;
        }

        .ad-input {
            width: 100%;
            background: var(--ad-surface);
            border: 1px solid var(--ad-border);
            border-radius: 8px;
            color: #e6edf3;
            padding: 8px 12px;
            font-size: .82rem;
            outline: none;
            font-family: inherit;
        }

        .ad-input:focus {
            border-color: var(--ad-blue);
        }

        .ad-select {
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%238b949e' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 10px center;
        }

        /* Notice cards */
        .notice-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-top: 16px;
        }

        .notice-card {
            background: var(--ad-surface);
            border: 1px solid var(--ad-border);
            border-radius: 12px;
            padding: 14px 16px;
            display: flex;
            align-items: flex-start;
            gap: 12px;
        }

        .notice-icon {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: .85rem;
            flex-shrink: 0;
        }

        .notice-card.info .notice-icon {
            background: rgba(88, 166, 255, .1);
            color: var(--ad-blue);
        }

        .notice-card.warning .notice-icon {
            background: rgba(210, 153, 34, .1);
            color: var(--ad-yellow);
        }

        .notice-card.danger .notice-icon {
            background: rgba(248, 81, 73, .1);
            color: var(--ad-red);
        }

        .notice-card.success .notice-icon {
            background: rgba(63, 185, 80, .1);
            color: var(--ad-green);
        }

        .notice-title {
            font-size: .85rem;
            font-weight: 700;
            margin-bottom: 3px;
        }

        .notice-body {
            font-size: .76rem;
            color: var(--ad-muted);
            line-height: 1.4;
        }

        .notice-meta {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-top: 6px;
            font-size: .7rem;
            color: var(--ad-muted);
        }

        .ticker-chip {
            background: rgba(99, 102, 241, .1);
            color: #818cf8;
            border-radius: 20px;
            padding: 2px 8px;
            font-size: .66rem;
        }

        /* Overlay modal */
        .ad-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, .75);
            backdrop-filter: blur(6px);
            z-index: 800;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .ad-overlay.show {
            display: flex;
        }

        .ad-modal {
            background: #161b22;
            border: 1px solid var(--ad-border);
            border-radius: 16px;
            width: min(620px, 100%);
            max-height: 90vh;
            overflow-y: auto;
            padding: 28px;
        }

        .ad-modal-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 22px;
        }

        .ad-modal-head h3 {
            font-size: 1rem;
            font-weight: 700;
        }

        .ad-close {
            background: none;
            border: none;
            color: var(--ad-muted);
            font-size: 1.2rem;
            cursor: pointer;
        }

        .ad-close:hover {
            color: #e6edf3;
        }

        .ad-modal-footer {
            display: flex;
            gap: 8px;
            justify-content: flex-end;
            margin-top: 20px;
            padding-top: 16px;
            border-top: 1px solid var(--ad-border);
        }

        /* ════════════════════════════════════════
       CHAT PANEL — Two-pane layout
       ════════════════════════════════════════ */
        .chat-layout {
            display: grid;
            grid-template-columns: 260px 1fr;
            gap: 16px;
            align-items: start;
        }

        @media(max-width:768px) {
            .chat-layout {
                grid-template-columns: 1fr;
            }
        }

        /* ── Left: user list ── */
        .chat-sidebar {
            background: var(--ad-surface);
            border: 1px solid var(--ad-border);
            border-radius: 14px;
            overflow: hidden;
        }

        .chat-sidebar-head {
            padding: 14px 16px;
            border-bottom: 1px solid var(--ad-border);
            font-size: .82rem;
            font-weight: 700;
            color: #e6edf3;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .chat-user-list {
            display: flex;
            flex-direction: column;
            gap: 0;
            max-height: 560px;
            overflow-y: auto;
        }

        .chat-user-item {
            padding: 12px 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            cursor: pointer;
            transition: background .12s;
            border-bottom: 1px solid rgba(255, 255, 255, .04);
        }

        .chat-user-item:last-child {
            border-bottom: none;
        }

        .chat-user-item:hover {
            background: rgba(255, 255, 255, .04);
        }

        .chat-user-item.active {
            background: rgba(99, 102, 241, .12);
            border-left: 3px solid #6366f1;
        }

        .chat-user-name {
            font-size: .83rem;
            font-weight: 600;
            color: #e6edf3;
        }

        .chat-user-email {
            font-size: .7rem;
            color: var(--ad-muted);
            margin-top: 2px;
        }

        .chat-unread {
            background: #ef4444;
            color: #fff;
            border-radius: 10px;
            padding: 2px 7px;
            font-size: .67rem;
            font-weight: 700;
            flex-shrink: 0;
        }

        /* ── Right: chat window ── */
        .chat-pane {
            background: var(--ad-surface);
            border: 1px solid var(--ad-border);
            border-radius: 14px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            min-height: 560px;
            max-height: 560px;
        }

        .chat-pane-empty {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            flex: 1;
            color: var(--ad-muted);
            gap: 10px;
        }

        .chat-pane-empty i {
            font-size: 2.4rem;
            opacity: .25;
        }

        .chat-pane-empty p {
            font-size: .82rem;
            opacity: .45;
        }

        /* ── Chat pane header ── */
        .chat-pane-head {
            padding: 10px 14px;
            background: #0d1117;
            border-bottom: 1px solid var(--ad-border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            flex-shrink: 0;
        }

        .chat-pane-user {
            display: flex;
            align-items: center;
            gap: 9px;
            min-width: 0;
        }

        .chat-pane-user-av {
            width: 30px;
            height: 30px;
            min-width: 30px;
            border-radius: 50%;
            background: linear-gradient(135deg, #6366f1, #8b5cf6);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: .6rem;
            font-weight: 800;
            color: #fff;
            flex-shrink: 0;
            overflow: hidden;
            line-height: 1;
        }

        .chat-pane-user-name {
            font-size: .78rem;
            font-weight: 700;
            color: #e6edf3;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 180px;
        }

        .chat-pane-user-email {
            font-size: .64rem;
            color: var(--ad-muted);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 180px;
        }

        /* ── Agent status bar ── */
        .chat-agent-bar {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 7px 14px;
            border-bottom: 1px solid var(--ad-border);
            background: rgba(99, 102, 241, .06);
            flex-shrink: 0;
        }

        .agent-bar-avatar {
            width: 24px;
            height: 24px;
            min-width: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: .55rem;
            font-weight: 800;
            color: #fff;
            flex-shrink: 0;
            overflow: hidden;
            line-height: 1;
        }

        .agent-bar-name {
            font-size: .76rem;
            font-weight: 700;
            color: #c7d2fe;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .agent-bar-status {
            font-size: .62rem;
            color: #4ade80;
            display: flex;
            align-items: center;
            gap: 4px;
            white-space: nowrap;
        }

        .agent-bar-status::before {
            content: '';
            width: 5px;
            height: 5px;
            border-radius: 50%;
            background: #4ade80;
            animation: recBlink2 1.5s step-end infinite;
        }

        .agent-bar-btn {
            padding: 4px 10px;
            border-radius: 7px;
            border: none;
            font-size: .7rem;
            font-weight: 700;
            cursor: pointer;
            transition: all .15s;
        }

        /* ── Join panel ── */
        .agent-join-panel {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 9px 14px;
            border-bottom: 1px solid var(--ad-border);
            background: rgba(0, 0, 0, .2);
            flex-shrink: 0;
        }

        .agent-join-panel input {
            flex: 1;
            background: #161b22;
            border: 1px solid var(--ad-border);
            border-radius: 8px;
            color: #e6edf3;
            padding: 6px 10px;
            font-size: .78rem;
            outline: none;
            font-family: inherit;
            min-width: 0;
        }

        .agent-join-panel input:focus {
            border-color: #6366f1;
        }

        /* ── Messages area ── */
        .chat-msgs {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding: 14px;
            display: flex;
            flex-direction: column;
            gap: 7px;
            background: #0d1117;
        }

        /* ── System message (joined/left) ── */
        .chat-msg.system {
            align-self: stretch;
            width: 100%;
            max-width: 100%;
        }

        .chat-system-event {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 4px 0;
        }

        .chat-system-line {
            flex: 1;
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(99, 102, 241, .2), transparent);
            min-width: 0;
        }

        .chat-system-pill {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 4px 12px 4px 5px;
            border-radius: 99px;
            font-size: .68rem;
            font-weight: 600;
            white-space: nowrap;
            flex-shrink: 0;
        }

        .chat-system-pill.joined {
            background: rgba(63, 185, 80, .12);
            border: 1px solid rgba(63, 185, 80, .25);
            color: #4ade80;
        }

        .chat-system-pill.left {
            background: rgba(239, 68, 68, .08);
            border: 1px solid rgba(239, 68, 68, .18);
            color: #f87171;
        }

        .agent-avatar {
            width: 20px;
            height: 20px;
            min-width: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: .52rem;
            font-weight: 800;
            color: #fff;
            flex-shrink: 0;
            overflow: hidden;
            line-height: 1;
        }

        /* ── Regular message bubbles ── */
        .chat-msg {
            max-width: 75%;
            word-break: break-word;
        }

        .chat-msg.user {
            align-self: flex-start;
        }

        .chat-msg.admin {
            align-self: flex-end;
        }

        .chat-bubble {
            padding: 8px 12px;
            border-radius: 12px;
            font-size: .8rem;
            line-height: 1.45;
        }

        .chat-msg.user .chat-bubble {
            background: rgba(56, 189, 248, .1);
            color: #bae6fd;
            border-bottom-left-radius: 3px;
        }

        .chat-msg.admin .chat-bubble {
            background: linear-gradient(135deg, rgba(99, 102, 241, .2), rgba(139, 92, 246, .15));
            color: #c7d2fe;
            border-bottom-right-radius: 3px;
        }

        .chat-msg .msg-time {
            font-size: .6rem;
            opacity: .4;
            margin-top: 3px;
        }

        .chat-msg.admin .msg-time {
            text-align: right;
        }

        .chat-agent-label {
            font-size: .6rem;
            color: #818cf8;
            font-weight: 700;
            margin-bottom: 3px;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 5px;
        }

        .chat-img {
            max-width: min(200px, 100%);
            max-height: 150px;
            border-radius: 8px;
            cursor: zoom-in;
            display: block;
        }

        .chat-audio {
            width: 100%;
            max-width: 220px;
            height: 32px;
            accent-color: #6366f1;
            display: block;
        }

        /* ── Image preview bar ── */
        .chat-img-preview {
            background: rgba(99, 102, 241, .08);
            border: 1px dashed rgba(99, 102, 241, .3);
            border-radius: 8px;
            padding: 6px 12px;
            margin: 0 12px 4px;
            display: none;
            align-items: center;
            gap: 8px;
            font-size: .75rem;
            color: #a5b4fc;
            flex-shrink: 0;
        }

        .chat-img-preview img {
            height: 34px;
            border-radius: 4px;
        }

        /* ── Recording indicator ── */
        .chat-rec-indicator {
            background: rgba(239, 68, 68, .08);
            border: 1px solid rgba(239, 68, 68, .2);
            border-radius: 8px;
            padding: 5px 12px;
            margin: 0 12px 4px;
            display: none;
            align-items: center;
            gap: 6px;
            font-size: .73rem;
            color: #fca5a5;
            flex-shrink: 0;
        }

        .chat-rec-dot {
            width: 7px;
            height: 7px;
            border-radius: 50%;
            background: #ef4444;
            animation: recBlink2 1s step-end infinite;
        }

        @keyframes recBlink2 {

            0%,
            100% {
                opacity: 1;
            }

            50% {
                opacity: 0;
            }
        }

        /* ── Compose bar ── */
        .chat-compose {
            display: flex;
            gap: 6px;
            padding: 10px 12px;
            border-top: 1px solid var(--ad-border);
            align-items: center;
            background: #161b22;
            flex-shrink: 0;
        }

        .chat-compose input {
            flex: 1;
            background: #0d1117;
            border: 1px solid var(--ad-border);
            border-radius: 8px;
            color: #e6edf3;
            padding: 8px 12px;
            font-size: .8rem;
            outline: none;
            font-family: inherit;
            min-width: 0;
        }

        .chat-compose input:focus {
            border-color: #6366f1;
        }

        .chat-compose-btn {
            background: #0d1117;
            border: 1px solid var(--ad-border);
            border-radius: 8px;
            color: var(--ad-muted);
            padding: 7px 10px;
            cursor: pointer;
            font-size: .8rem;
            transition: all .15s;
            flex-shrink: 0;
        }

        .chat-compose-btn:hover {
            background: #6366f1;
            border-color: #6366f1;
            color: #fff;
        }

        .chat-compose-btn.active {
            background: #ef4444;
            border-color: #ef4444;
            color: #fff;
        }

        .chat-send-btn {
            background: #6366f1;
            border: none;
            border-radius: 8px;
            color: #fff;
            padding: 8px 14px;
            cursor: pointer;
            font-size: .8rem;
            flex-shrink: 0;
        }

        /* ── Switch agent modal ── */
        .switch-agent-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, .75);
            backdrop-filter: blur(6px);
            z-index: 900;
            align-items: center;
            justify-content: center;
        }

        .switch-agent-overlay.show {
            display: flex;
        }

        .switch-agent-modal {
            background: #161b22;
            border: 1px solid #30363d;
            border-radius: 16px;
            padding: 28px;
            width: min(400px, calc(100vw - 32px));
            text-align: center;
        }

        .switch-agent-modal h3 {
            font-size: 1rem;
            font-weight: 700;
            margin-bottom: 6px;
        }

        .switch-agent-modal p {
            font-size: .78rem;
            color: var(--ad-muted);
            margin-bottom: 20px;
        }

        /* Section card */
        .ad-card {
            background: var(--ad-surface);
            border: 1px solid var(--ad-border);
            border-radius: 14px;
            padding: 20px;
            margin-bottom: 18px;
        }

        .ad-card-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 18px;
        }

        .ad-card-head h3 {
            font-size: .9rem;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        @media (max-width:640px) {
            .ad-form-grid {
                grid-template-columns: 1fr;
            }

            .ad-stats {
                grid-template-columns: 1fr 1fr;
            }

            .ad-tabs {
                overflow-x: auto;
            }
        }
    </style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <div class="ad-header">
        <h2><i class="fas fa-users-cog"></i> Admin Dashboard</h2>
    </div>

    
    <?php
        $totalClients = $clients->count();
        $activeClients = $clients->where('status', 'active')->count();
        $suspendedClients = $clients->where('status', 'suspended')->count();
        $expiredClients = $clients->filter(fn($u) => $u->subscriptionStatus() === 'expired')->count();
        $totalUnread = $unreadChats->sum();
    ?>
    <div class="ad-stats">
        <div class="ad-stat">
            <div class="ad-stat-val" style="color:#a371f7;"><?php echo e($totalClients); ?></div>
            <div class="ad-stat-label">Total Clients</div>
        </div>
        <div class="ad-stat">
            <div class="ad-stat-val" style="color:#3fb950;"><?php echo e($activeClients); ?></div>
            <div class="ad-stat-label">Active</div>
        </div>
        <div class="ad-stat">
            <div class="ad-stat-val" style="color:#f59e0b;"><?php echo e($suspendedClients); ?></div>
            <div class="ad-stat-label">Suspended</div>
        </div>
        <div class="ad-stat">
            <div class="ad-stat-val" style="color:#f85149;"><?php echo e($expiredClients); ?></div>
            <div class="ad-stat-label">Expired</div>
        </div>
        <div class="ad-stat">
            <div class="ad-stat-val" style="color:#58a6ff;"><?php echo e($notices->count()); ?></div>
            <div class="ad-stat-label">Notices</div>
        </div>
        <div class="ad-stat">
            <div class="ad-stat-val" style="color:#ec4899;"><?php echo e($totalUnread); ?></div>
            <div class="ad-stat-label">Unread Chats</div>
        </div>
    </div>

    
    
    <div id="adminNotifBar"
        style="display:none;background:linear-gradient(90deg,rgba(99,102,241,.15),rgba(99,102,241,.05));border:1px solid rgba(99,102,241,.3);border-radius:10px;padding:10px 16px;margin-bottom:14px;display:none;align-items:center;gap:12px;">
        <div
            style="width:36px;height:36px;border-radius:50%;background:rgba(99,102,241,.2);display:flex;align-items:center;justify-content:center;animation:pulse 1.5s infinite;">
            <i class="fas fa-bell" style="color:#818cf8;"></i></div>
        <div>
            <div style="font-size:.84rem;font-weight:700;color:#a5b4fc;" id="notifMsg">New message received!</div>
            <div style="font-size:.72rem;color:#8b949e;" id="notifFrom"></div>
        </div>
        <button onclick="document.getElementById('adminNotifBar').style.display='none'"
            style="margin-left:auto;background:none;border:none;color:#8b949e;cursor:pointer;"><i
                class="fas fa-times"></i></button>
    </div>

    <div class="ad-tabs">
        <button class="ad-tab active" onclick="adTab(this,'tabClients')"><i class="fas fa-users"></i> Clients</button>
        <button class="ad-tab" onclick="adTab(this,'tabNotices')"><i class="fas fa-bullhorn"></i> Notices</button>
        <button class="ad-tab" onclick="adTab(this,'tabChat')" id="chatTabBtn">
            <i class="fas fa-comments"></i> Support Chat
            <span class="badge" id="adminChatBadge"
                style="<?php echo e($totalUnreadCount > 0 ? '' : 'display:none'); ?>"><?php echo e($totalUnreadCount); ?></span>
        </button>
        <button class="ad-tab" onclick="adTab(this,'tabNotifications')" id="notifTabBtn"><i class="fas fa-bell"></i>
            Notifications</button>
        <button class="ad-tab" onclick="adTab(this,'tabCreate')"><i class="fas fa-user-plus"></i> Add Client</button>
        <button class="ad-tab" onclick="adTab(this,'tabSettings')"><i class="fas fa-cog"></i> Settings</button>
    </div>

    
    <div class="ad-panel active" id="tabClients">
        <div class="ad-card">
            <div class="ad-card-head">
                <h3><i class="fas fa-list" style="color:#a371f7;"></i> All Clients</h3>
                <input type="text" class="ad-input" style="width:220px;" placeholder="Search clients…"
                    oninput="filterClients(this.value)">
            </div>
            <div class="ad-table-wrap">
                <table class="ad-table" id="clientTable">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Plan</th>
                            <th>Status</th>
                            <th>Expires</th>
                            <th>Billing</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $__empty_1 = true; $__currentLoopData = $clients; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $client): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                        <?php $st = $client->subscriptionStatus(); ?>
                                        <tr class="client-row" data-search="<?php echo e(strtolower($client->name . ' ' . $client->email)); ?>">
                                            <td><strong><?php echo e($client->name); ?></strong><br><span
                                                    style="font-size:.7rem;color:#8b949e;"><?php echo e($client->primary_domain ?? '—'); ?></span></td>
                                            <td><?php echo e($client->email); ?></td>
                                            <td><span style="font-size:.78rem;"><?php echo e($client->plan_name ?? 'Basic'); ?></span></td>
                                            <td>
                                                <span class="st-badge st-<?php echo e($st); ?>">
                                                    <span class="st-dot"></span>
                                                    <?php echo e(ucfirst($st)); ?>

                                                </span>
                                            </td>
                                            <td style="font-size:.78rem;">
                                                <?php echo $client->subscription_expires_at
                            ? '<span style="color:#e6edf3;">' . $client->subscription_expires_at->format('d M Y') . '</span>'
                            : '<span style="color:#475569;font-style:italic;">—</span>'; ?>

                                            </td>
                                            <td style="font-size:.78rem;">$<?php echo e(number_format($client->billing_amount, 2)); ?></td>
                                            <td>
                                                <div style="display:flex;gap:6px;flex-wrap:wrap;">
                                                    <a href="<?php echo e(route('admin.clients.manage', $client->id)); ?>" class="ad-btn edit"
                                                        style="background:rgba(163,113,247,.1);color:var(--ad-purple);">
                                                        <i class="fas fa-tasks"></i> Manage
                                                    </a>
                                                    <button class="ad-btn edit" onclick="openEditModal(<?php echo e($client->id); ?>)">
                                                        <i class="fas fa-edit"></i> Edit
                                                    </button>
                                                    <button class="ad-btn chat"
                                                        onclick="adTab(document.querySelector('[onclick*=tabChat]'),'tabChat');openChatFor(<?php echo e($client->id); ?>, '<?php echo e(addslashes($client->name)); ?>')">
                                                        <i class="fas fa-comment"></i>
                                                        <?php if(isset($unreadChats[$client->id]) && $unreadChats[$client->id] > 0): ?>
                                                            <span
                                                                style="background:#ef4444;border-radius:10px;padding:0 5px;font-size:.65rem;"><?php echo e($unreadChats[$client->id]); ?></span>
                                                        <?php endif; ?>
                                                    </button>
                                                    <form method="POST" action="<?php echo e(route('admin.clients.delete', $client->id)); ?>"
                                                        onsubmit="return confirm('Delete <?php echo e($client->name); ?>? This cannot be undone.')">
                                                        <?php echo csrf_field(); ?> <?php echo method_field('DELETE'); ?>
                                                        <button type="submit" class="ad-btn danger"><i class="fas fa-trash"></i></button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                            <tr>
                                <td colspan="7" style="text-align:center;padding:32px;color:#8b949e;"><i class="fas fa-users"
                                        style="font-size:1.5rem;margin-bottom:8px;display:block;"></i>No clients yet.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    
    <div class="ad-panel" id="tabNotices">
        <div class="ad-card">
            <div class="ad-card-head">
                <h3><i class="fas fa-plus-circle" style="color:#3fb950;"></i> Create Notice</h3>
            </div>
            <div class="ad-form-grid" style="margin-bottom:14px;">
                <div class="ad-field" style="grid-column:1/-1;">
                    <label>Title</label>
                    <input type="text" class="ad-input" id="ntTitle" placeholder="Notice title">
                </div>
                <div class="ad-field" style="grid-column:1/-1;">
                    <label>Message</label>
                    <textarea class="ad-input" id="ntBody" rows="3" placeholder="Notice body…"
                        style="resize:vertical;"></textarea>
                </div>
                <div class="ad-field">
                    <label>Type</label>
                    <select class="ad-input ad-select" id="ntType">
                        <option value="info">Info</option>
                        <option value="warning">Warning</option>
                        <option value="danger">Danger</option>
                        <option value="success">Success</option>
                    </select>
                </div>
                <div class="ad-field" style="display:flex;align-items:flex-end;gap:8px;">
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:.8rem;color:#e6edf3;">
                        <input type="checkbox" id="ntTicker" style="accent-color:#6366f1;width:16px;height:16px;">
                        Show in Ticker
                    </label>
                </div>
            </div>
            <button class="ad-btn primary" onclick="createNotice()"><i class="fas fa-plus"></i> Post Notice</button>
        </div>

        <div class="ad-card">
            <div class="ad-card-head">
                <h3><i class="fas fa-list" style="color:#58a6ff;"></i> Active Notices</h3>
            </div>
            <div class="notice-list" id="noticeList">
                <?php $__empty_1 = true; $__currentLoopData = $notices; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $notice): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                    <div class="notice-card <?php echo e($notice->type); ?>" id="notice-<?php echo e($notice->id); ?>">
                        <div class="notice-icon">
                            <i
                                class="fas fa-<?php echo e($notice->type === 'info' ? 'info-circle' : ($notice->type === 'warning' ? 'exclamation-triangle' : ($notice->type === 'danger' ? 'times-circle' : 'check-circle'))); ?>"></i>
                        </div>
                        <div style="flex:1;">
                            <div class="notice-title"><?php echo e($notice->title); ?></div>
                            <div class="notice-body"><?php echo e($notice->body); ?></div>
                            <div class="notice-meta">
                                <span><?php echo e($notice->created_at->diffForHumans()); ?></span>
                                <?php if($notice->is_ticker): ?><span class="ticker-chip"><i class="fas fa-broadcast-tower"
                                style="margin-right:3px;"></i> Ticker</span><?php endif; ?>
                                <span class="st-badge <?php echo e($notice->is_active ? 'st-active' : 'st-expired'); ?>"
                                    style="font-size:.65rem;padding:2px 7px;"><?php echo e($notice->is_active ? 'Active' : 'Inactive'); ?></span>
                            </div>
                        </div>
                        <div style="display:flex;flex-direction:column;gap:6px;flex-shrink:0;">
                            <button class="ad-btn danger" onclick="deleteNotice(<?php echo e($notice->id); ?>)"><i
                                    class="fas fa-trash"></i></button>
                        </div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                    <p style="color:#8b949e;font-size:.82rem;text-align:center;padding:20px;">No notices yet.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    
    <div class="ad-panel" id="tabChat">
        <div class="chat-layout">

            
            <div class="chat-sidebar">
                <div class="chat-sidebar-head">
                    <i class="fas fa-comments" style="color:#58a6ff;"></i>
                    Support Chats
                    <?php if($totalUnreadCount > 0): ?>
                        <span class="chat-unread" style="margin-left:auto;"><?php echo e($totalUnreadCount); ?></span>
                    <?php endif; ?>
                </div>
                <div class="chat-user-list" id="chatUserList">
                    <?php $__empty_1 = true; $__currentLoopData = $clients; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $client): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <div class="chat-user-item" id="cui-<?php echo e($client->id); ?>"
                            onclick="openChatFor(<?php echo e($client->id); ?>, '<?php echo e(addslashes($client->name)); ?>', '<?php echo e(addslashes($client->email)); ?>')">
                            <div style="min-width:0;">
                                <div class="chat-user-name"><?php echo e($client->name); ?></div>
                                <div class="chat-user-email"><?php echo e($client->email); ?></div>
                            </div>
                            <?php if(isset($unreadChats[$client->id]) && $unreadChats[$client->id] > 0): ?>
                                <span class="chat-unread" id="unread-badge-<?php echo e($client->id); ?>"><?php echo e($unreadChats[$client->id]); ?></span>
                            <?php else: ?>
                                <span class="chat-unread" id="unread-badge-<?php echo e($client->id); ?>" style="display:none;"></span>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <p style="color:#8b949e;text-align:center;padding:20px;font-size:.82rem;">No clients.</p>
                    <?php endif; ?>
                </div>
            </div>

            
            <div class="chat-pane" id="chatPane">
                
                <div class="chat-pane-empty" id="chatPaneEmpty">
                    <i class="fas fa-comments"></i>
                    <p>Select a client to start chatting</p>
                </div>

                
                <div id="chatPaneHead" class="chat-pane-head" style="display:none;">
                    <div class="chat-pane-user">
                        <div class="chat-pane-user-av" id="chatPaneAv">?</div>
                        <div>
                            <div class="chat-pane-user-name" id="chatPaneUserName"></div>
                            <div class="chat-pane-user-email" id="chatPaneUserEmail"></div>
                        </div>
                    </div>
                    <div style="display:flex;gap:6px;flex-shrink:0;">
                        <button class="ad-btn edit" style="font-size:.7rem;padding:5px 10px;" onclick="showSwitchAgent()">
                            <i class="fas fa-exchange-alt"></i> Switch Agent
                        </button>
                    </div>
                </div>

                
                <div id="chatAgentBar" class="chat-agent-bar" style="display:none;">
                    <div class="agent-bar-avatar" id="chatAgentAvatarBar"></div>
                    <div>
                        <div class="agent-bar-name" id="chatAgentNameBar"></div>
                        <div class="agent-bar-status">Active in this chat</div>
                    </div>
                    <button class="agent-bar-btn"
                        style="background:rgba(239,68,68,.12);color:#f87171;border:1px solid rgba(239,68,68,.2);"
                        onclick="adminLeaveChat()">
                        <i class="fas fa-sign-out-alt"></i> Leave
                    </button>
                </div>

                
                <div id="chatJoinPanel" class="agent-join-panel" style="display:none;">
                    <i class="fas fa-user-tie" style="color:#818cf8;flex-shrink:0;"></i>
                    <input type="text" id="adminJoinNameInput" placeholder="Enter agent name to join…" maxlength="60"
                        onkeydown="if(event.key==='Enter')adminJoinChat()">
                    <button class="ad-btn success" style="font-size:.72rem;white-space:nowrap;flex-shrink:0;"
                        onclick="adminJoinChat()">
                        <i class="fas fa-sign-in-alt"></i> Join
                    </button>
                </div>

                
                <div class="chat-msgs" id="adminChatMsgs" style="display:none;"></div>

                
                <div class="chat-img-preview" id="adminImgPreview">
                    <img id="adminImgThumb" src="" alt="">
                    <span id="adminImgName"
                        style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:.75rem;"></span>
                    <button onclick="adminClearImg()"
                        style="background:none;border:none;color:#ef4444;cursor:pointer;font-size:.85rem;">✕</button>
                </div>

                
                <div class="chat-rec-indicator" id="adminRecIndicator">
                    <span class="chat-rec-dot"></span>
                    <span id="adminRecTime">0:00</span>
                    <span style="flex:1;">Recording…</span>
                    <button onclick="adminStopRec(true)"
                        style="background:none;border:none;color:#fca5a5;cursor:pointer;font-size:.73rem;font-weight:700;">Send</button>
                    <button onclick="adminStopRec(false)"
                        style="background:none;border:none;color:var(--ad-muted);cursor:pointer;font-size:.73rem;">Cancel</button>
                </div>

                
                <div class="chat-compose" id="chatCompose" style="display:none;">
                    <button class="chat-compose-btn" onclick="adminPickImg()" title="Image"><i
                            class="fas fa-image"></i></button>
                    <button class="chat-compose-btn" id="adminVoiceBtn" onclick="adminToggleRec()" title="Voice"><i
                            class="fas fa-microphone"></i></button>
                    <input type="text" id="adminChatInput" placeholder="Type reply…"
                        onkeydown="if(event.key==='Enter')adminSendReply()">
                    <button class="chat-send-btn" onclick="adminSendReply()"><i class="fas fa-paper-plane"></i></button>
                </div>
            </div>

        </div>

        
        <input type="file" id="adminFileInput" accept="image/*" style="display:none" onchange="adminHandleFile(this)">

        
        <div class="switch-agent-overlay" id="switchAgentOverlay" onclick="if(event.target===this)closeSwitchAgent()">
            <div class="switch-agent-modal">
                <div
                    style="width:52px;height:52px;border-radius:50%;background:linear-gradient(135deg,#6366f1,#8b5cf6);display:flex;align-items:center;justify-content:center;margin:0 auto 14px;font-size:1.3rem;">
                    <i class="fas fa-exchange-alt" style="color:#fff;"></i>
                </div>
                <h3>Switch Agent</h3>
                <p>Leave the current agent session and join as a new one.</p>
                <input type="text" id="switchAgentInput" class="ad-input" placeholder="New agent name…" maxlength="60"
                    style="margin-bottom:16px;" onkeydown="if(event.key==='Enter')confirmSwitchAgent()">
                <div style="display:flex;gap:8px;justify-content:center;">
                    <button class="ad-btn" onclick="closeSwitchAgent()"
                        style="background:rgba(255,255,255,.05);">Cancel</button>
                    <button class="ad-btn success" onclick="confirmSwitchAgent()"><i class="fas fa-check"></i>
                        Switch</button>
                </div>
            </div>
        </div>
    </div>

    
    <div class="ad-panel" id="tabCreate">
        <?php if(session('success')): ?>
            <div
                style="background:rgba(63,185,80,.1);border:1px solid rgba(63,185,80,.2);border-radius:10px;padding:12px 16px;margin-bottom:16px;font-size:.82rem;color:#3fb950;">
        <i class="fas fa-check-circle" style="margin-right:6px;"></i><?php echo e(session('success')); ?></div><?php endif; ?>
        <div class="ad-card">
            <div class="ad-card-head">
                <h3><i class="fas fa-user-plus" style="color:#3fb950;"></i> Create New Client</h3>
            </div>
            <form method="POST" action="<?php echo e(route('admin.clients.store')); ?>">
                <?php echo csrf_field(); ?>
                <div class="ad-form-grid">
                    <div class="ad-field"><label>Full Name *</label><input name="name" class="ad-input" required
                            placeholder="John Doe" value="<?php echo e(old('name')); ?>"></div>
                    <div class="ad-field"><label>Email *</label><input name="email" type="email" class="ad-input" required
                            placeholder="john@example.com" value="<?php echo e(old('email')); ?>"></div>
                    <div class="ad-field"><label>Password *</label><input name="password" type="password" class="ad-input"
                            required placeholder="Min 8 chars"></div>
                    <div class="ad-field"><label>Plan Name</label><input name="plan_name" class="ad-input"
                            placeholder="Basic / Pro / Enterprise" value="<?php echo e(old('plan_name', 'Basic')); ?>"></div>
                    <div class="ad-field"><label>Billing Amount ($)</label><input name="billing_amount" type="number"
                            step="0.01" class="ad-input" placeholder="0.00" value="<?php echo e(old('billing_amount', 0)); ?>"></div>
                    <div class="ad-field"><label>Subscription Expires</label><input name="subscription_expires_at"
                            type="date" class="ad-input" value="<?php echo e(old('subscription_expires_at')); ?>"></div>
                    <div class="ad-field"><label>Primary Domain</label><input name="primary_domain" class="ad-input"
                            placeholder="example.com" value="<?php echo e(old('primary_domain')); ?>"></div>
                    <div class="ad-field"><label>Disk Quota (GB) *</label><input name="disk_quota" type="number"
                            class="ad-input" required value="<?php echo e(old('disk_quota', 10)); ?>"></div>
                    <div class="ad-field"><label>Domain Limit *</label><input name="domain_limit" type="number"
                            class="ad-input" required value="<?php echo e(old('domain_limit', 5)); ?>"></div>
                    <div class="ad-field"><label>Email Limit *</label><input name="email_limit" type="number"
                            class="ad-input" required value="<?php echo e(old('email_limit', 10)); ?>"></div>
                </div>
                <?php if($errors->any()): ?>
                <div style="color:#f85149;font-size:.78rem;margin:12px 0;"><?php echo e(implode(', ', $errors->all())); ?></div><?php endif; ?>
                <div style="margin-top:16px;">
                    <button type="submit" class="ad-btn primary"><i class="fas fa-plus"></i> Create Client</button>
                </div>
            </form>
        </div>
    </div>

    
    <div class="ad-panel" id="tabNotifications">

        
        <div class="ad-card">
            <div class="ad-card-head">
                <h3><i class="fas fa-paper-plane" style="color:#6366f1;"></i> Send Notification</h3>
            </div>
            <div class="ad-form-grid" style="margin-bottom:16px;">
                <div class="ad-field">
                    <label>Title *</label>
                    <input type="text" class="ad-input" id="nfTitle" placeholder="Notification title" maxlength="255">
                </div>
                <div class="ad-field">
                    <label>Type</label>
                    <select class="ad-input ad-select" id="nfType">
                        <option value="info">ℹ️ Info</option>
                        <option value="success">✅ Success</option>
                        <option value="warning">⚠️ Warning</option>
                        <option value="danger">🚨 Danger</option>
                    </select>
                </div>
                <div class="ad-field" style="grid-column:1/-1;">
                    <label>Message *</label>
                    <textarea class="ad-input" id="nfMessage" rows="3" placeholder="Notification message…"
                        style="resize:vertical;"></textarea>
                </div>
                <div class="ad-field">
                    <label>Target</label>
                    <select class="ad-input ad-select" id="nfTarget" onchange="toggleNfUserSelect()">
                        <option value="all">📢 All Users</option>
                        <option value="user">👤 Specific User</option>
                    </select>
                </div>
                <div class="ad-field" id="nfUserWrap" style="display:none;">
                    <label>Select User *</label>
                    <select class="ad-input ad-select" id="nfUserId">
                        <option value="">— Choose user —</option>
                        <?php $__currentLoopData = $clients; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $client): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($client->id); ?>"><?php echo e($client->name); ?> (<?php echo e($client->email); ?>)</option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
            </div>
            <button class="ad-btn primary" onclick="sendAdminNotif()">
                <i class="fas fa-paper-plane"></i> Send Notification
            </button>
            <span id="nfSentMsg" style="display:none;color:#3fb950;font-size:.78rem;margin-left:12px;"><i
                    class="fas fa-check-circle"></i> Sent!</span>
        </div>

        
        <div class="ad-card">
            <div class="ad-card-head">
                <h3><i class="fas fa-list" style="color:#58a6ff;"></i> Sent Notifications</h3>
                <button class="ad-btn edit" style="font-size:.72rem;" onclick="loadAdminNotifs()"><i
                        class="fas fa-sync-alt"></i> Refresh</button>
            </div>
            <div id="adminNotifList">
                <p style="color:#8b949e;font-size:.8rem;text-align:center;padding:20px;">Loading…</p>
            </div>
        </div>
    </div>

    
    <div class="ad-panel" id="tabSettings">
        <div class="ad-card">
            <div class="ad-card-head">
                <h3><i class="fas fa-cog" style="color:#58a6ff;"></i> Global Settings</h3>
            </div>
            <div style="max-width:560px;display:flex;flex-direction:column;gap:16px;">

                
                <div class="ad-field">
                    <label style="font-size:.8rem;color:#8b949e;margin-bottom:6px;display:block;">
                        <i class="fas fa-envelope" style="margin-right:4px;color:#58a6ff;"></i>
                        Admin Contact Email
                        <span style="font-size:.7rem;color:#475569;">(shown on expired domain page)</span>
                    </label>
                    <input type="email" class="ad-input" id="adminEmail"
                        value="<?php echo e(\App\Models\AdminSetting::get('admin_email', '')); ?>" placeholder="admin@yourdomain.com">
                </div>

                
                <div class="ad-field">
                    <label style="font-size:.8rem;color:#8b949e;margin-bottom:6px;display:block;">
                        <i class="fas fa-redo" style="margin-right:4px;color:#f59e0b;"></i>
                        Custom Renewal / Billing Page URL
                        <span style="font-size:.7rem;color:#475569;">(optional — leave blank to use built-in expired
                            page)</span>
                    </label>
                    <input type="url" class="ad-input" id="globalRenewUrl" value="<?php echo e($renewUrl ?? ''); ?>"
                        placeholder="https://yourdomain.com/renew">
                    <p style="font-size:.72rem;color:#475569;margin-top:5px;">
                        Leave blank to redirect to: <code
                            style="background:rgba(255,255,255,.06);padding:1px 6px;border-radius:4px;font-size:.68rem;"><?php echo e(url('/hosting-expired')); ?></code>
                    </p>
                </div>

                <div>
                    <button class="ad-btn primary" onclick="saveGlobalSettings()"><i class="fas fa-save"></i> Save
                        Settings</button>
                    <span id="settingsSaved" style="display:none;color:#3fb950;font-size:.78rem;margin-left:10px;"><i
                            class="fas fa-check-circle"></i> Settings saved.</span>
                </div>
            </div>
        </div>

        <div class="ad-card">
            <div class="ad-card-head">
                <h3><i class="fas fa-tools" style="color:#3fb950;"></i> System Maintenance</h3>
            </div>
            <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:center;">
                <button class="ad-btn success" onclick="runStorageLink()" id="btnStorageLink">
                    <i class="fas fa-link"></i> Run storage:link
                </button>
                <button class="ad-btn danger" onclick="runCacheClear()" id="btnCacheClear">
                    <i class="fas fa-broom"></i> Clear All Caches
                </button>
                <span id="toolStatus" style="font-size:.78rem;color:#8b949e;"></span>
            </div>
            <p style="font-size:.72rem;color:#475569;margin-top:8px;max-width:560px;">
                <strong>Clear All Caches</strong> will run: <code>cache:clear</code>, <code>config:clear</code>,
                <code>route:clear</code> and <code>view:clear</code>.
            </p>
        </div>
    </div>

    
    <div class="ad-overlay" id="editModal">
        <div class="ad-modal" onclick="event.stopPropagation()">
            <div class="ad-modal-head">
                <h3><i class="fas fa-edit" style="color:#58a6ff;margin-right:8px;"></i> Edit Client</h3>
                <button class="ad-close" onclick="closeEditModal()"><i class="fas fa-times"></i></button>
            </div>
            <div id="editFormWrap"></div>
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
    <script>
        var EDIT_URL = '<?php echo e(url("/admin/clients")); ?>';
        var NOTICE_URL = '<?php echo e(url("/admin/notices")); ?>';
        var CHAT_URL = '<?php echo e(url("/admin/support")); ?>';
        var SETTINGS_URL = '<?php echo e(route("admin.settings.save")); ?>';
        var TOOL_URL = '<?php echo e(route("admin.settings.tool")); ?>';
        var UNREAD_URL = '<?php echo e(route("admin.unread")); ?>';
        var CSRF = '<?php echo e(csrf_token()); ?>';
        var currentChatUser = null;
        var prevUnreadTotal = <?php echo e($totalUnreadCount); ?>;
        var prevUnreadUsers = <?php echo json_encode($unreadChats); ?>;

        // ── Web Audio notification sound ──────────────────────────────
        var AudioCtx = window.AudioContext || window.webkitAudioContext;
        function playNotifSound() {
            try {
                var ctx = new AudioCtx();
                var nodes = [
                    { freq: 880, start: 0, dur: .08, gain: .4 },
                    { freq: 1100, start: .09, dur: .08, gain: .35 },
                    { freq: 1320, start: .18, dur: .12, gain: .3 },
                ];
                nodes.forEach(function (n) {
                    var osc = ctx.createOscillator();
                    var g = ctx.createGain();
                    osc.type = 'sine';
                    osc.frequency.value = n.freq;
                    g.gain.setValueAtTime(n.gain, ctx.currentTime + n.start);
                    g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + n.start + n.dur);
                    osc.connect(g); g.connect(ctx.destination);
                    osc.start(ctx.currentTime + n.start);
                    osc.stop(ctx.currentTime + n.start + n.dur);
                });
            } catch (e) { }
        }

        function showAdminNotif(msg, from) {
            playNotifSound();
            var bar = document.getElementById('adminNotifBar');
            document.getElementById('notifMsg').textContent = msg;
            document.getElementById('notifFrom').textContent = from || '';
            bar.style.display = 'flex';
            setTimeout(function () { bar.style.display = 'none'; }, 8000);
            // Browser notification
            if (Notification.permission === 'granted') {
                new Notification('Server Panel — New Message', { body: (from ? from + ': ' : '') + msg, icon: '' });
            }
        }

        // Request browser notification permission
        if (Notification.permission === 'default') {
            document.addEventListener('click', function () { Notification.requestPermission(); }, { once: true });
        }

        // ── Poll for new messages every 5s ────────────────────────────
        function pollUnread() {
            fetch(UNREAD_URL, { headers: { 'Accept': 'application/json' } })
                .then(r => r.json())
                .then(function (d) {
                    var newTotal = d.total || 0;
                    var badge = document.getElementById('adminChatBadge');
                    badge.textContent = newTotal;
                    badge.style.display = newTotal > 0 ? 'flex' : 'none';

                    // Detect new messages
                    if (newTotal > prevUnreadTotal) {
                        var diff = newTotal - prevUnreadTotal;
                        var names = [];
                        for (var uid in d.per_user) {
                            var prev = prevUnreadUsers[uid] || 0;
                            if ((d.per_user[uid] || 0) > prev) {
                                // find user name from DOM
                                var el = document.querySelector('[onclick*="openChatFor(' + uid + ',"]');
                                if (el) {
                                    var n = el.querySelector('.chat-user-name');
                                    if (n) names.push(n.textContent.trim());
                                }
                            }
                        }
                        showAdminNotif(diff + ' new message' + (diff > 1 ? 's' : ''), names.join(', ') || 'A client');
                    }
                    prevUnreadTotal = newTotal;
                    prevUnreadUsers = d.per_user || {};

                    // Update per-user badges
                    document.querySelectorAll('.chat-user-item').forEach(function (item) {
                        var onclick = item.getAttribute('onclick') || '';
                        var m = onclick.match(/openChatFor\((\d+)/);
                        if (!m) return;
                        var uid = m[1];
                        var cnt = d.per_user[uid] || 0;
                        var badge = item.querySelector('.chat-unread');
                        if (cnt > 0) {
                            if (!badge) {
                                badge = document.createElement('span');
                                badge.className = 'chat-unread';
                                item.appendChild(badge);
                            }
                            badge.textContent = cnt + ' new';
                        } else if (badge) {
                            badge.remove();
                        }
                    });
                });
        }
        setInterval(pollUnread, 5000);

        // ── Tabs ──────────────────────────────────────────────
        function adTab(btn, panelId) {
            document.querySelectorAll('.ad-tab').forEach(b => b.classList.remove('active'));
            document.querySelectorAll('.ad-panel').forEach(p => p.classList.remove('active'));
            if (btn) btn.classList.add('active');
            document.getElementById(panelId).classList.add('active');
        }

        // ── Filter clients ────────────────────────────────────
        function filterClients(q) {
            q = q.toLowerCase();
            document.querySelectorAll('.client-row').forEach(function (row) {
                row.style.display = !q || row.dataset.search.includes(q) ? '' : 'none';
            });
        }

        // ── Edit modal ─────────────────────────────────────────
        function openEditModal(id) {
            var row = document.querySelector('.client-row[data-search]');
            // Build form via AJAX (get current values from DOM row)
            var rows = document.querySelectorAll('.client-row');
            var userRow = null;
            rows.forEach(function (r) {
                var btn = r.querySelector('[onclick*="openEditModal(' + id + ')"]');
                if (btn) userRow = r;
            });

            // Fetch fresh data via a quick JSON endpoint (we'll just build from DOM for now)
            document.getElementById('editFormWrap').innerHTML = '<p style="color:#8b949e;text-align:center;padding:20px;"><i class="fas fa-spinner fa-spin"></i> Loading...</p>';
            document.getElementById('editModal').classList.add('show');

            fetch(EDIT_URL + '/' + id + '/data', { headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' } })
                .then(r => r.json())
                .then(d => buildEditForm(id, d))
                .catch(() => buildEditForm(id, null, id));
        }

        function buildEditForm(id, data) {
            var unit = data?.disk_quota_unit || 'GB';
            var quotaInput =
                '<div class="ad-field"><label>Storage Quota *</label>' +
                '<div style="display:flex;gap:6px;">' +
                '<input name="disk_quota" type="number" class="ad-input" value="' + (data?.disk_quota ?? 10) + '" required style="flex:1;">' +
                '<select name="disk_quota_unit" class="ad-input ad-select" style="width:80px;">' +
                ['KB', 'MB', 'GB', 'TB'].map(u => '<option value="' + u + '"' + (unit === u ? ' selected' : '') + '>' + u + '</option>').join('') +
                '</select></div></div>';

            var html = '<form onsubmit="submitEdit(event,' + id + ')">' +
                '<div class="ad-form-grid">' +
                fld('Name *', 'name', data?.name ?? '', 'text', true) +
                fld('Email *', 'email', data?.email ?? '', 'email', true) +
                fld('Password (blank = keep)', 'password', '', 'password') +
                fld('Plan', 'plan_name', data?.plan_name ?? 'Basic', 'text') +
                fld('Billing ($)', 'billing_amount', data?.billing_amount ?? 0, 'number') +
                fld('Expires', 'subscription_expires_at', data?.subscription_expires_at ?? '', 'date') +
                fld('Primary Domain', 'primary_domain', data?.primary_domain ?? '', 'text') +
                quotaInput +
                fld('Domain Limit', 'domain_limit', data?.domain_limit ?? 5, 'number', true) +
                fld('Email Limit', 'email_limit', data?.email_limit ?? 10, 'number', true) +
                '</div>' +
                '<div class="ad-field" style="margin-top:12px;"><label>Status</label>' +
                '<select name="status" class="ad-input ad-select">' +
                ['active', 'suspended', 'expired'].map(s => '<option value="' + s + '"' + (data?.status === s ? ' selected' : '') + '>' + s.charAt(0).toUpperCase() + s.slice(1) + '</option>').join('') +
                '</select></div>' +
                '<div class="ad-field" style="margin-top:12px;">' +
                '<label><i class="fas fa-redo" style="color:#f59e0b;margin-right:4px;"></i> Custom Renew URL <span style="color:#475569;font-size:.68rem;">(overrides global)</span></label>' +
                '<input name="renew_url" type="url" class="ad-input" value="' + (data?.renew_url ?? '').replace(/"/g, '&quot;') + '" placeholder="https://..."></div>' +
                '<div style="margin-top:14px;padding:12px;background:rgba(0,0,0,.2);border-radius:10px;display:flex;gap:8px;align-items:center;flex-wrap:wrap;">' +
                '<span style="font-size:.75rem;color:#8b949e;"><i class="fas fa-globe"></i> Domain Redirect:</span>' +
                '<button type="button" class="ad-btn danger" style="font-size:.72rem;" onclick="applyRedirect(' + id + ')"><i class="fas fa-ban"></i> Apply Redirect Now</button>' +
                '<button type="button" class="ad-btn success" style="font-size:.72rem;" onclick="removeRedirect(' + id + ')"><i class="fas fa-check"></i> Remove Redirect</button>' +
                '<span style="font-size:.68rem;color:#475569;">(saves changes first)</span>' +
                '</div>' +
                '<div id="editErr" style="color:#f85149;font-size:.78rem;margin-top:10px;display:none;"></div>' +
                '<div class="ad-modal-footer">' +
                '<button type="button" class="ad-btn danger" style="border:1px solid;" onclick="closeEditModal()"><i class="fas fa-times"></i> Cancel</button>' +
                '<button type="submit" class="ad-btn primary"><i class="fas fa-save"></i> Save Changes</button>' +
                '</div></form>';
            document.getElementById('editFormWrap').innerHTML = html;
        }

        function fld(label, name, val, type, req) {
            return '<div class="ad-field"><label>' + label + '</label>' +
                '<input name="' + name + '" type="' + type + '" class="ad-input" value="' + String(val).replace(/"/g, '&quot;') + '"' + (req ? ' required' : '') + '></div>';
        }

        function submitEdit(e, id) {
            e.preventDefault();
            var form = e.target;
            var data = {};
            new FormData(form).forEach((v, k) => { if (v !== '') data[k] = v; });
            if (!data.password) delete data.password;

            fetch(EDIT_URL + '/' + id, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' },
                body: JSON.stringify(data)
            }).then(r => r.json()).then(function (d) {
                if (d.success) { closeEditModal(); location.reload(); }
                else {
                    var err = document.getElementById('editErr');
                    err.textContent = Object.values(d.errors || {}).flat().join(', ') || 'Error';
                    err.style.display = 'block';
                }
            });
        }

        function closeEditModal() {
            document.getElementById('editModal').classList.remove('show');
        }

        // Get user data for edit form
        // We'll add a GET route to fetch user JSON
        document.getElementById('editModal').addEventListener('click', function (e) {
            if (e.target === this) closeEditModal();
        });

        // ── Notices ───────────────────────────────────────────
        function createNotice() {
            var title = document.getElementById('ntTitle').value.trim();
            var body = document.getElementById('ntBody').value.trim();
            var type = document.getElementById('ntType').value;
            var ticker = document.getElementById('ntTicker').checked;
            if (!title || !body) { alert('Please fill title and message.'); return; }

            fetch(NOTICE_URL, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                body: JSON.stringify({ title, body, type, is_ticker: ticker ? 1 : 0 })
            }).then(r => r.json()).then(function (d) {
                if (d.success) location.reload();
            });
        }

        function deleteNotice(id) {
            if (!confirm('Delete this notice?')) return;
            fetch(NOTICE_URL + '/' + id, {
                method: 'DELETE',
                headers: { 'X-CSRF-TOKEN': CSRF }
            }).then(r => r.json()).then(function (d) {
                if (d.success) {
                    var el = document.getElementById('notice-' + id);
                    if (el) el.remove();
                }
            });
        }

        // ── Chat ──────────────────────────────────────────────
        // ── Chat — open/close ────────────────────────────────────────
        function openChatFor(userId, userName, userEmail) {
            document.querySelectorAll('.chat-user-item').forEach(function (el) { el.classList.remove('active'); });
            var item = document.getElementById('cui-' + userId);
            if (item) item.classList.add('active');

            currentChatUser = userId;
            currentAgentName = null;
            updateAgentBar(null);

            var initials = (userName || '?').trim().split(/\s+/).map(function (w) { return w[0]; }).join('').slice(0, 2).toUpperCase();
            document.getElementById('chatPaneAv').textContent = initials;
            document.getElementById('chatPaneUserName').textContent = userName || 'User';
            document.getElementById('chatPaneUserEmail').textContent = userEmail || '';

            document.getElementById('chatPaneEmpty').style.display = 'none';
            document.getElementById('chatPaneHead').style.display = 'flex';
            document.getElementById('adminChatMsgs').style.display = 'flex';
            document.getElementById('chatCompose').style.display = 'flex';

            loadChatMessages(userId);
        }

        function closeChatWindow() {
            currentChatUser = null;
            currentAgentName = null;
            document.getElementById('chatPaneEmpty').style.display = 'flex';
            document.getElementById('chatPaneHead').style.display = 'none';
            document.getElementById('chatAgentBar').style.display = 'none';
            document.getElementById('chatJoinPanel').style.display = 'none';
            document.getElementById('adminChatMsgs').style.display = 'none';
            document.getElementById('chatCompose').style.display = 'none';
            document.querySelectorAll('.chat-user-item').forEach(function (el) { el.classList.remove('active'); });
        }

        var ADMIN_UPLOAD_URL = '<?php echo e(url("/admin/support")); ?>';
        var ADMIN_AGENT_URL = '<?php echo e(url("/admin/support")); ?>';
        var currentAgentName = null; // active agent in current chat

        // ── Avatar color from name ────────────────────────────────────
        var AGENT_COLORS = ['#6366f1', '#8b5cf6', '#ec4899', '#f59e0b', '#10b981', '#3b82f6', '#ef4444', '#14b8a6'];
        function agentColor(name) {
            if (!name) return '#6366f1';
            var sum = 0; for (var i = 0; i < name.length; i++) sum += name.charCodeAt(i);
            return AGENT_COLORS[sum % AGENT_COLORS.length];
        }
        function agentInitials(name) {
            if (!name) return '?';
            var parts = name.trim().split(/\s+/);
            return (parts[0][0] + (parts[1] ? parts[1][0] : '')).toUpperCase();
        }
        function makeAvatar(name, size) {
            size = size || 20;
            var color = agentColor(name);
            var fs = (size * 0.32).toFixed(2);
            return '<div class="agent-avatar" style="width:' + size + 'px;height:' + size + 'px;min-width:' + size + 'px;background:' + color + ';font-size:' + fs + 'rem;line-height:1;overflow:hidden;">' + agentInitials(name) + '</div>';
        }

        // ── System / join / leave message render ─────────────────────
        function adminRenderMsg(m) {
            var type = m.message_type || 'text';

            // System messages (joined / left)
            if (type === 'system' || m.sender === 'system') {
                var isJoin = m.message && m.message.toLowerCase().includes('joined');
                var pillClass = isJoin ? 'joined' : 'left';
                var icon = isJoin ? '👋' : '🚪';
                var avatarHtml = m.agent_name ? makeAvatar(m.agent_name, 22) : '';
                return '<div class="chat-msg system">'
                    + '<div class="chat-system-event">'
                    + '<div class="chat-system-line"></div>'
                    + '<div class="chat-system-pill ' + pillClass + '">'
                    + avatarHtml
                    + icon + ' ' + escHtml(m.message)
                    + '</div>'
                    + '<div class="chat-system-line"></div>'
                    + '</div>'
                    + '<div class="msg-time" style="text-align:center;font-size:.58rem;">' + m.created_at + '</div>'
                    + '</div>';
            }

            // Regular messages
            var agentHtml = '';
            if (m.sender === 'admin' && m.agent_name) {
                var av = makeAvatar(m.agent_name, 18);
                agentHtml = '<div class="chat-agent-label">' + escHtml(m.agent_name) + av + '</div>';
            }
            var content = '';
            if (type === 'image' && m.file_url) {
                content = '<img src="' + m.file_url + '" class="chat-img" onclick="window.open(this.src)" onerror="this.style.display=\'none\'">';
                if (m.message && m.message !== '📷 Image') content += '<div style="font-size:.73rem;margin-top:3px;">' + escHtml(m.message) + '</div>';
            } else if (type === 'voice' && m.file_url) {
                content = '<audio class="chat-audio" controls src="' + m.file_url + '"></audio>';
            } else {
                content = escHtml(m.message);
            }
            return '<div class="chat-msg ' + m.sender + '">'
                + agentHtml
                + '<div class="chat-bubble">' + content + '</div>'
                + '<div class="msg-time">' + m.created_at + '</div>'
                + '</div>';
        }

        function loadChatMessages(userId) {
            fetch(CHAT_URL + '/' + userId, { headers: { 'Accept': 'application/json' } })
                .then(r => r.json())
                .then(function (d) {
                    var box = document.getElementById('adminChatMsgs');
                    if (!d.messages || !d.messages.length) {
                        box.innerHTML = '<p style="color:#8b949e;font-size:.78rem;text-align:center;padding:16px;">No messages yet.</p>';
                        return;
                    }
                    box.innerHTML = d.messages.map(adminRenderMsg).join('');
                    box.scrollTop = box.scrollHeight;
                });
        }

        function adminSendReply() {
            if (!currentChatUser) return;
            if (adminStagedFile) { adminUploadStaged(); return; }
            var input = document.getElementById('adminChatInput');
            var msg = input.value.trim();
            if (!msg) return;
            input.value = '';
            fetch(CHAT_URL + '/' + currentChatUser + '/reply', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                body: JSON.stringify({ message: msg, agent_name: currentAgentName || null })
            }).then(() => loadChatMessages(currentChatUser));
        }

        function escHtml(s) {
            return String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        }

        // ── Agent join / leave ────────────────────────────────────────
        function adminJoinChat() {
            var name = document.getElementById('adminJoinNameInput').value.trim();
            if (!name) { document.getElementById('adminJoinNameInput').focus(); return; }
            if (!currentChatUser) return;
            fetch(ADMIN_AGENT_URL + '/' + currentChatUser + '/agent', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                body: JSON.stringify({ action: 'join', agent_name: name })
            }).then(r => r.json()).then(function (d) {
                if (d.success) {
                    currentAgentName = name;
                    updateAgentBar(name);
                    loadChatMessages(currentChatUser);
                }
            });
        }
        function adminLeaveChat() {
            if (!currentAgentName || !currentChatUser) return;
            var name = currentAgentName;
            fetch(ADMIN_AGENT_URL + '/' + currentChatUser + '/agent', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                body: JSON.stringify({ action: 'leave', agent_name: name })
            }).then(r => r.json()).then(function (d) {
                currentAgentName = null;
                updateAgentBar(null);
                loadChatMessages(currentChatUser);
            });
        }
        function updateAgentBar(name) {
            var bar = document.getElementById('chatAgentBar');
            var jpanel = document.getElementById('chatJoinPanel');
            if (!currentChatUser) { bar.style.display = 'none'; jpanel.style.display = 'none'; return; }
            if (name) {
                var color = agentColor(name);
                document.getElementById('chatAgentAvatarBar').style.background = color;
                document.getElementById('chatAgentAvatarBar').textContent = agentInitials(name);
                document.getElementById('chatAgentNameBar').textContent = name;
                bar.style.display = 'flex';
                jpanel.style.display = 'none';
                document.getElementById('adminChatInput').placeholder = 'Reply as ' + name + '…';
            } else {
                bar.style.display = 'none';
                jpanel.style.display = 'flex';
                document.getElementById('adminJoinNameInput').value = '';
                document.getElementById('adminChatInput').placeholder = 'Type reply or paste image…';
            }
        }

        // ── Switch agent modal ────────────────────────────────────────
        function showSwitchAgent() {
            document.getElementById('switchAgentInput').value = currentAgentName || '';
            document.getElementById('switchAgentOverlay').classList.add('show');
            setTimeout(function () { document.getElementById('switchAgentInput').focus(); }, 100);
        }
        function closeSwitchAgent() {
            document.getElementById('switchAgentOverlay').classList.remove('show');
        }
        function confirmSwitchAgent() {
            var newName = document.getElementById('switchAgentInput').value.trim();
            if (!newName) { document.getElementById('switchAgentInput').focus(); return; }
            closeSwitchAgent();
            if (!currentChatUser) return;

            var doJoin = function () {
                fetch(ADMIN_AGENT_URL + '/' + currentChatUser + '/agent', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                    body: JSON.stringify({ action: 'join', agent_name: newName })
                }).then(r => r.json()).then(function (d) {
                    currentAgentName = newName;
                    updateAgentBar(newName);
                    loadChatMessages(currentChatUser);
                });
            };

            // If someone is already joined, leave first
            if (currentAgentName) {
                fetch(ADMIN_AGENT_URL + '/' + currentChatUser + '/agent', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                    body: JSON.stringify({ action: 'leave', agent_name: currentAgentName })
                }).then(doJoin);
            } else {
                doJoin();
            }
        }

        // (agent state reset is handled in openChatFor directly)

        // ── Admin image sharing ───────────────────────────────────────
        var adminStagedFile = null;
        function adminPickImg() { document.getElementById('adminFileInput').click(); }
        function adminHandleFile(inp) {
            if (inp.files && inp.files[0]) adminStageFile(inp.files[0]);
        }
        function adminStageFile(file) {
            if (!file.type.startsWith('image/')) return;
            adminStagedFile = file;
            var reader = new FileReader();
            reader.onload = function (e) {
                document.getElementById('adminImgThumb').src = e.target.result;
                document.getElementById('adminImgName').textContent = file.name || 'pasted image';
                document.getElementById('adminImgPreview').style.display = 'flex';
            };
            reader.readAsDataURL(file);
        }
        function adminClearImg() {
            adminStagedFile = null;
            document.getElementById('adminImgPreview').style.display = 'none';
            document.getElementById('adminImgThumb').src = '';
        }
        function adminUploadStaged() {
            if (!adminStagedFile || !currentChatUser) return;
            var caption = document.getElementById('adminChatInput').value.trim();
            var fd = new FormData();
            fd.append('file', adminStagedFile);
            fd.append('type', 'image');
            fd.append('caption', caption);
            fd.append('agent_name', currentAgentName || '');
            fd.append('_token', CSRF);
            adminClearImg();
            document.getElementById('adminChatInput').value = '';
            fetch(ADMIN_UPLOAD_URL + '/' + currentChatUser + '/upload', { method: 'POST', body: fd })
                .then(() => loadChatMessages(currentChatUser));
        }

        // ── Admin clipboard paste ─────────────────────────────────────
        document.addEventListener('paste', function (e) {
            if (!currentChatUser) return;
            var items = (e.clipboardData || e.originalEvent.clipboardData).items;
            for (var i = 0; i < items.length; i++) {
                if (items[i].type.startsWith('image/')) {
                    var file = items[i].getAsFile();
                    if (file) adminStageFile(file);
                    e.preventDefault();
                    break;
                }
            }
        });

        // ── Admin voice recording ─────────────────────────────────────
        var adminMediaRecorder = null, adminAudioChunks = [], adminRecTimerEl = null, adminRecSeconds = 0;
        function adminToggleRec() {
            if (adminMediaRecorder && adminMediaRecorder.state === 'recording') adminStopRec(true);
            else adminStartRec();
        }
        function adminStartRec() {
            navigator.mediaDevices.getUserMedia({ audio: true }).then(function (stream) {
                adminAudioChunks = [];
                adminMediaRecorder = new MediaRecorder(stream);
                adminMediaRecorder.ondataavailable = function (e) { adminAudioChunks.push(e.data); };
                adminMediaRecorder.start();
                document.getElementById('adminRecIndicator').style.display = 'flex';
                document.getElementById('adminVoiceBtn').classList.add('active');
                adminRecSeconds = 0;
                adminRecTimerEl = setInterval(function () {
                    adminRecSeconds++;
                    var m = Math.floor(adminRecSeconds / 60), s = adminRecSeconds % 60;
                    document.getElementById('adminRecTime').textContent = m + ':' + (s < 10 ? '0' : '') + s;
                }, 1000);
            }).catch(function () { alert('Microphone access denied.'); });
        }
        function adminStopRec(send) {
            if (!adminMediaRecorder) return;
            clearInterval(adminRecTimerEl);
            document.getElementById('adminRecIndicator').style.display = 'none';
            document.getElementById('adminVoiceBtn').classList.remove('active');
            adminMediaRecorder.onstop = function () {
                if (send && currentChatUser) {
                    var blob = new Blob(adminAudioChunks, { type: 'audio/webm' });
                    var fd = new FormData();
                    fd.append('file', blob, 'voice_' + Date.now() + '.webm');
                    fd.append('type', 'voice');
                    fd.append('agent_name', currentAgentName || '');
                    fd.append('_token', CSRF);
                    fetch(ADMIN_UPLOAD_URL + '/' + currentChatUser + '/upload', { method: 'POST', body: fd })
                        .then(() => loadChatMessages(currentChatUser));
                }
                adminMediaRecorder.stream.getTracks().forEach(t => t.stop());
                adminMediaRecorder = null; adminAudioChunks = [];
            };
            adminMediaRecorder.stop();
        }

        // Poll chat every 6s if open
        setInterval(function () {
            if (currentChatUser) loadChatMessages(currentChatUser);
        }, 6000);

        // ── Admin Notifications ───────────────────────────────────────
        var ADMIN_NOTIF_URL = '<?php echo e(url("/admin/notifications")); ?>';

        var NOTIF_TYPE_ICONS = { info: 'fa-info-circle', warning: 'fa-exclamation-triangle', success: 'fa-check-circle', danger: 'fa-times-circle' };
        var NOTIF_TYPE_COLORS = { info: '#3b82f6', warning: '#f59e0b', success: '#22c55e', danger: '#ef4444' };

        function toggleNfUserSelect() {
            var t = document.getElementById('nfTarget').value;
            document.getElementById('nfUserWrap').style.display = t === 'user' ? 'block' : 'none';
        }

        function sendAdminNotif() {
            var title = document.getElementById('nfTitle').value.trim();
            var message = document.getElementById('nfMessage').value.trim();
            var type = document.getElementById('nfType').value;
            var target = document.getElementById('nfTarget').value;
            var userId = document.getElementById('nfUserId').value;

            if (!title || !message) { alert('Title and message are required.'); return; }
            if (target === 'user' && !userId) { alert('Please select a user.'); return; }

            fetch(ADMIN_NOTIF_URL, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                body: JSON.stringify({ title, message, type, target, user_id: userId || null })
            }).then(r => r.json()).then(function (d) {
                if (d.success) {
                    document.getElementById('nfTitle').value = '';
                    document.getElementById('nfMessage').value = '';
                    var el = document.getElementById('nfSentMsg');
                    el.style.display = 'inline';
                    setTimeout(function () { el.style.display = 'none'; }, 3000);
                    loadAdminNotifs();
                }
            });
        }

        function loadAdminNotifs() {
            fetch(ADMIN_NOTIF_URL, { headers: { 'Accept': 'application/json' } })
                .then(r => r.json())
                .then(function (d) {
                    var box = document.getElementById('adminNotifList');
                    if (!d.notifications || !d.notifications.length) {
                        box.innerHTML = '<p style="color:#8b949e;font-size:.8rem;text-align:center;padding:20px;">No notifications sent yet.</p>';
                        return;
                    }
                    box.innerHTML = d.notifications.map(function (n) {
                        var color = NOTIF_TYPE_COLORS[n.type] || '#6366f1';
                        var icon = NOTIF_TYPE_ICONS[n.type] || 'fa-bell';
                        var badge = n.target === 'all'
                            ? '<span style="background:rgba(99,102,241,.15);color:#818cf8;border-radius:20px;padding:2px 8px;font-size:.65rem;font-weight:700;">📢 All Users</span>'
                            : '<span style="background:rgba(56,189,248,.12);color:#7dd3fc;border-radius:20px;padding:2px 8px;font-size:.65rem;font-weight:700;">👤 ' + escHtml(n.user_name || 'User') + '</span>';
                        return '<div style="display:flex;align-items:flex-start;gap:12px;padding:12px 14px;background:var(--ad-surface);border:1px solid var(--ad-border);border-radius:12px;margin-bottom:8px;">'
                            + '<div style="width:36px;height:36px;min-width:36px;border-radius:10px;background:rgba(' + hexToRgb(color) + ',.1);display:flex;align-items:center;justify-content:center;color:' + color + ';">'
                            + '<i class="fas ' + icon + '"></i></div>'
                            + '<div style="flex:1;min-width:0;">'
                            + '<div style="font-size:.82rem;font-weight:700;color:#e6edf3;margin-bottom:2px;">' + escHtml(n.title) + '</div>'
                            + '<div style="font-size:.75rem;color:#8b949e;margin-bottom:5px;">' + escHtml(n.message) + '</div>'
                            + '<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">'
                            + badge
                            + '<span style="font-size:.65rem;color:#475569;">' + n.created_at + '</span>'
                            + '</div></div>'
                            + '<button onclick="deleteAdminNotif(' + n.id + ',this)" class="ad-btn danger" style="font-size:.7rem;padding:4px 8px;flex-shrink:0;"><i class="fas fa-trash"></i></button>'
                            + '</div>';
                    }).join('');
                });
        }

        function deleteAdminNotif(id, btn) {
            btn.disabled = true;
            fetch(ADMIN_NOTIF_URL + '/' + id, {
                method: 'DELETE',
                headers: { 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' }
            }).then(r => r.json()).then(function (d) {
                if (d.success) loadAdminNotifs();
                else btn.disabled = false;
            });
        }

        function hexToRgb(hex) {
            var r = parseInt(hex.slice(1, 3), 16), g = parseInt(hex.slice(3, 5), 16), b = parseInt(hex.slice(5, 7), 16);
            return r + ',' + g + ',' + b;
        }

        // Auto-load notifs when tab is opened
        document.querySelector('[onclick*="tabNotifications"]') && document.querySelector('[onclick*="tabNotifications"]').addEventListener('click', function () { setTimeout(loadAdminNotifs, 100); });

        // ── Domain redirect toggle ────────────────────────────────────
        function applyRedirect(id) {
            fetch(EDIT_URL + '/' + id + '/redirect', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                body: JSON.stringify({ action: 'apply' })
            }).then(r => r.json()).then(function (d) {
                if (d.success) alert('Redirect applied to domain(s).');
            });
        }
        function removeRedirect(id) {
            fetch(EDIT_URL + '/' + id + '/redirect', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                body: JSON.stringify({ action: 'remove' })
            }).then(r => r.json()).then(function (d) {
                if (d.success) alert('Redirect removed from domain(s).');
            });
        }

        // ── Save global settings ──────────────────────────────────────
        function saveGlobalSettings() {
            var url = document.getElementById('globalRenewUrl').value;
            var email = document.getElementById('adminEmail').value;
            fetch(SETTINGS_URL, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
                body: JSON.stringify({ renew_url: url, admin_email: email })
            }).then(r => r.json()).then(function (d) {
                if (d.success) {
                    var el = document.getElementById('settingsSaved');
                    el.style.display = 'inline';
                    setTimeout(function () { el.style.display = 'none'; }, 3000);
                }
            });
        }

        // ── System tools (storage:link, cache clear) ──────────────────
        function setToolStatus(msg, type) {
            var el = document.getElementById('toolStatus');
            if (!el) return;
            el.style.color = type === 'err' ? '#f85149' : '#3fb950';
            el.innerHTML = msg;
        }

        function runStorageLink() {
            var btn = document.getElementById('btnStorageLink');
            btn.disabled = true;
            setToolStatus('Running storage:link…', 'ok');
            fetch(TOOL_URL, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' },
                body: JSON.stringify({ action: 'storage_link' })
            }).then(r => r.json()).then(function (d) {
                if (d.success) {
                    setToolStatus('storage:link executed successfully.', 'ok');
                } else {
                    setToolStatus(d.message || 'storage:link failed.', 'err');
                }
            }).catch(function () {
                setToolStatus('storage:link failed.', 'err');
            }).finally(function () {
                btn.disabled = false;
            });
        }

        function runCacheClear() {
            var btn = document.getElementById('btnCacheClear');
            btn.disabled = true;
            setToolStatus('Clearing application caches…', 'ok');
            fetch(TOOL_URL, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' },
                body: JSON.stringify({ action: 'cache_clear' })
            }).then(r => r.json()).then(function (d) {
                if (d.success) {
                    setToolStatus('All caches cleared successfully.', 'ok');
                } else {
                    setToolStatus(d.message || 'Cache clear failed.', 'err');
                }
            }).catch(function () {
                setToolStatus('Cache clear failed.', 'err');
            }).finally(function () {
                btn.disabled = false;
            });
        }
    </script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.dashboard', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/fullread/public_html/resources/views/admin/index.blade.php ENDPATH**/ ?>