
<?php $__env->startSection('title', 'Prototype Desain'); ?>

<?php $__env->startSection('styles'); ?>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
    <style>
        body {
            background: #f4f4f4;
        }

        .admin-dashboard {
            display: flex;
            min-height: 100vh;
            background: #f4f4f4;
        }

        .sidebar {
            width: 260px;
            background: #23272b;
            color: #fff;
            display: flex;
            flex-direction: column;
            padding: 24px 0 0 0;
            border-right: 1px solid #e5e7eb;
        }

        .sidebar .sidebar-header {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 0 24px 24px 24px;
            font-size: 1.1rem;
            font-weight: 700;
        }

        .sidebar .sidebar-header i {
            font-size: 1.6rem;
            color: #22c1b6;
        }

        .sidebar .sidebar-header span {
            font-size: 1.1rem;
            font-weight: 700;
            color: #fff;
        }

        .sidebar-nav {
            flex: 1;
            padding: 0 0 0 0;
        }

        .sidebar-nav ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-nav li {
            margin-bottom: 4px;
        }

        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 28px;
            color: #bfc5c9;
            text-decoration: none;
            border-radius: 8px 0 0 8px;
            font-size: 1rem;
            transition: background 0.2s, color 0.2s;
        }

        .sidebar-nav a.active,
        .sidebar-nav a:hover {
            background: #22c1b6;
            color: #fff;
        }

        .sidebar-footer {
            padding: 18px 24px;
            border-top: 1px solid #333;
            background: #23272b;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 0.98rem;
        }

        .sidebar-footer .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: #444;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 1.2rem;
            font-weight: 700;
        }

        .sidebar-footer .user-info {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }

        .sidebar-footer .user-info span {
            color: #fff;
            font-weight: 600;
            font-size: 1rem;
        }

        .sidebar-footer .user-info small {
            color: #bfc5c9;
            font-size: 0.95rem;
        }

        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #f4f4f4;
        }

        .main-header {
            background: #fff;
            padding: 24px 32px 16px 32px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e5e7eb;
        }
        
        /* Keep admin header/navbar white regardless of site dark/light mode */
        body.dark-mode .admin-dashboard .main-header,
        .admin-dashboard .main-header {
            background: #ffffff !important;
            color: #222 !important;
            border-bottom: 1px solid #e5e7eb !important;
        }

        /* Ensure header child elements keep their intended colors in dark mode */
        body.dark-mode .admin-dashboard .main-header .title,
        body.dark-mode .admin-dashboard .main-header .subtitle,
        body.dark-mode .admin-dashboard .main-header .header-actions,
        body.dark-mode .admin-dashboard .main-header .header-actions * {
            color: inherit !important;
            background: transparent !important;
        }

        .title {
            font-size: 1.4rem;
            font-weight: 700;
            color: #222;
        }

        .subtitle {
            color: #6b7280;
            font-size: 1.05rem;
            margin-top: 2px;
        }

        .header-actions {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #22c1b6 0%, #1da89c 100%);
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 10px 24px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(34, 193, 182, 0.3);
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, #1da89c 0%, #178f84 100%);
            box-shadow: 0 4px 16px rgba(34, 193, 182, 0.4);
            transform: translateY(-2px);
        }

        .btn-primary i {
            font-size: 0.95rem;
        }

        .btn-secondary {
            background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 10px 24px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(107, 114, 128, 0.3);
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-secondary:hover {
            background: linear-gradient(135deg, #4b5563 0%, #374151 100%);
            box-shadow: 0 4px 16px rgba(107, 114, 128, 0.4);
            transform: translateY(-2px);
        }

        .btn-secondary i {
            font-size: 0.95rem;
        }

        .btn-danger {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 10px 24px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-danger:hover {
            background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
            box-shadow: 0 4px 16px rgba(239, 68, 68, 0.4);
            transform: translateY(-2px);
        }

        .btn-danger i {
            font-size: 0.95rem;
        }

        .main-content {
            padding: 32px;
        }

        .content-section {
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
            padding: 0;
            margin-bottom: 32px;
            overflow: hidden;
            border: 1px solid #e5e7eb;
            transition: all 0.3s ease;
        }

        .content-section:hover {
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }

        .category-section {
            border-left: 4px solid #22c1b6;
        }

        .designs-section {
            border-left: 4px solid #f59e0b;
        }

        .section-header {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 24px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 2px solid #e5e7eb;
        }

        .section-header-left {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .section-icon {
            width: 56px;
            height: 56px;
            background: linear-gradient(135deg, #22c1b6 0%, #1da89c 100%);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 1.5rem;
            box-shadow: 0 4px 12px rgba(34, 193, 182, 0.3);
        }

        .designs-icon {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
        }

        .section-title-new {
            font-size: 1.4rem;
            font-weight: 700;
            color: #23272b;
            margin: 0 0 4px 0;
        }

        .section-subtitle {
            font-size: 0.95rem;
            color: #6b7280;
            margin: 0;
        }

        .section-body {
            padding: 32px;
        }

        .loading-spinner {
            text-align: center;
            padding: 40px;
            color: #9ca3af;
            font-size: 1.1rem;
        }

        .loading-spinner i {
            font-size: 2rem;
            margin-bottom: 12px;
            display: block;
            color: #22c1b6;
        }

        .section-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #23272b;
            margin-bottom: 1.5rem;
        }

        .badge {
            display: inline-block;
            padding: 6px 16px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.95rem;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-radius: 8px;
            padding: 10px 18px;
            margin-bottom: 1rem;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-radius: 8px;
            padding: 10px 18px;
            margin-bottom: 1rem;
        }

        #designTable th {
            background: #f8f9fa;
            color: #374151;
            font-weight: 600;
            padding: 12px 16px;
            border-bottom: 2px solid #e5e7eb;
        }

        #designTable td {
            padding: 12px 16px;
            border-bottom: 1px solid #e5e7eb;
            color: #6b7280;
            vertical-align: middle;
        }

        #designTable tr:hover {
            background: #f8f9fa;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .form-group {
            margin-bottom: 18px;
            position: relative;
        }

        .form-group label {
            font-weight: 600;
            margin-bottom: 6px;
            display: block;
        }

        .form-group input[type="text"],
        .form-group textarea,
        .form-group select,
        .form-group input[type="file"] {
            width: 100%;
            padding: 10px 14px;
            border-radius: 8px;
            border: 1px solid #d1d5db;
            background: #fff;
            font-size: 1rem;
            margin-top: 4px;
            box-sizing: border-box;
        }

        #design_category {
            appearance: menulist !important;
            background: #ffffff !important;
            background-color: #ffffff !important;
            color: #000000 !important;
            font-weight: 500 !important;
            pointer-events: auto !important;
            border: 1px solid #d1d5db !important;
            cursor: pointer !important;
            opacity: 1 !important;
            box-shadow: none !important;
            -webkit-appearance: menulist !important;
            -moz-appearance: menulist !important;
        }

        /* Super aggressive override untuk kategori dropdown */
        #design_category,
        #design_category:enabled,
        #design_category:not(:disabled) {
            background: #ffffff !important;
            background-color: #ffffff !important;
            color: #000000 !important;
            pointer-events: auto !important;
            cursor: pointer !important;
            opacity: 1 !important;
            filter: none !important;
        }

        .form-group select {
            appearance: menulist !important;
            background: #ffffff !important;
            color: #000000 !important;
            font-weight: 500;
            pointer-events: auto !important;
            border: 1px solid #d1d5db !important;
            cursor: pointer !important;
            opacity: 1 !important;
            box-shadow: none !important;
            -webkit-appearance: menulist !important;
            -moz-appearance: menulist !important;
        }

        /* DataTables Enhanced Styling */
        .dataTables_wrapper {
            padding: 1.5rem;
            background: #ffffff;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }

        .dataTables_filter input {
            border: 2px solid #e5e7eb !important;
            border-radius: 8px !important;
            padding: 8px 16px !important;
            font-size: 14px !important;
            width: 250px !important;
            transition: all 0.3s ease !important;
        }

        .dataTables_filter input:focus {
            border-color: #22c1b6 !important;
            outline: none !important;
            box-shadow: 0 0 0 3px rgba(34, 193, 182, 0.1) !important;
        }

        #designTable thead th {
            background: linear-gradient(135deg, #f2f2f2ff) !important;
            color: black !important;
            font-weight: 600 !important;
            padding: 12px 8px !important;
            border: none !important;
            text-align: center !important;
            font-size: 14px !important;
        }

        #designTable tbody td {
            padding: 12px 8px !important;
            vertical-align: middle !important;
            border-bottom: 1px solid #f3f4f6 !important;
            font-size: 13px !important;
        }

        #designTable tbody tr:hover {
            background-color: #f8fafc !important;
        }

        .dataTables_info {
            color: #6b7280 !important;
            font-size: 14px !important;
            font-weight: 500 !important;
        }

        .dataTables_paginate .paginate_button {
            border: 1px solid #e5e7eb !important;
            border-radius: 6px !important;
            margin: 0 2px !important;
            padding: 6px 12px !important;
            color: #374151 !important;
            background: white !important;
        }

        .dataTables_paginate .paginate_button:hover {
            background: #22c1b6 !important;
            border-color: #22c1b6 !important;
            color: white !important;
        }

        .dataTables_paginate .paginate_button.current {
            background: #22c1b6 !important;
            border-color: #22c1b6 !important;
            color: white !important;
        }

        /* File download button styling */
        .btn-download {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
            color: white !important;
            padding: 6px 12px !important;
            border-radius: 6px !important;
            text-decoration: none !important;
            font-size: 12px !important;
            font-weight: 600 !important;
            display: inline-flex !important;
            align-items: center !important;
            gap: 4px !important;
            transition: all 0.3s ease !important;
            border: none !important;
        }

        .btn-download:hover {
            transform: translateY(-1px) !important;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4) !important;
            color: white !important;
            text-decoration: none !important;
        }

        /* Badge styling */
        .badge {
            padding: 4px 12px !important;
            border-radius: 20px !important;
            font-size: 11px !important;
            font-weight: 600 !important;
            text-transform: uppercase !important;
            letter-spacing: 0.5px !important;
        }

        /* Image preview styling */
        .img-preview {
            transition: all 0.3s ease !important;
            border: 2px solid transparent !important;
            cursor: pointer !important;
        }

        .img-preview:hover {
            transform: scale(1.05) !important;
            border-color: #22c1b6 !important;
            box-shadow: 0 4px 12px rgba(34, 193, 182, 0.3) !important;
        }

        .form-group input[type="file"] {
            padding: 6px 0;
            background: #fff;
        }

        .modal-content {
            background: #fff;
            margin: 5% auto;
            padding: 24px;
            border-radius: 12px;
            width: 90%;
            max-width: 520px;
            position: relative;
            box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
            max-height: 85vh;
            overflow-y: auto;
        }

        .modal-header {
            border-bottom: 1px solid #e5e7eb;
            margin-bottom: 18px;
        }

        .modal-title {
            font-size: 1.15rem;
            font-weight: 700;
            color: #23272b;
        }

        .close {
            position: absolute;
            right: 24px;
            top: 24px;
            font-size: 24px;
            cursor: pointer;
        }

        /* Force white background untuk dropdown kategori */
        #design_category,
        #design_category:focus,
        #design_category:hover,
        #design_category:active {
            background: #ffffff !important;
            background-color: #ffffff !important;
            color: #000000 !important;
            pointer-events: auto !important;
            cursor: pointer !important;
            opacity: 1 !important;
            box-shadow: none !important;
        }

        /* Remove any gray background from form groups */
        .form-group,
        .form-container,
        .modal-content {
            background: #ffffff !important;
        }

        /* HAPUS NICE-SELECT PLUGIN */
        .nice-select,
        div.nice-select,
        .nice-select-dropdown {
            display: none !important;
            visibility: hidden !important;
            opacity: 0 !important;
            height: 0 !important;
            width: 0 !important;
            position: absolute !important;
            left: -9999px !important;
            z-index: -1 !important;
        }

        /* Force show original select - ALL SELECTS */
        select#design_category,
        select#design_video,
        select#design_is_inherited {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            position: relative !important;
            z-index: 999 !important;
            background: #ffffff !important;
            color: #000000 !important;
        }

        /* Tambahkan CSS berikut di dalam <style> agar DataTables hanya menampilkan satu ikon sort per kolom */
        table.dataTable thead .sorting:after,
        table.dataTable thead .sorting_asc:after,
        table.dataTable thead .sorting_desc:after {
            content: '';
            display: none !important;
        }
        table.dataTable thead th {
            position: relative;
        }
        th.dt-orderable-asc, th.dt-orderable-desc, th.dt-ordering-asc, th.dt-ordering-desc {
            background-repeat: no-repeat !important;
            background-position: right 16px center !important;
            background-size: 18px 18px !important;
            /* Remove default DataTables arrow */
        }
        th.dt-ordering-asc::after {
            content: "▲";
            color: #667eea;
            font-size: 1.1em;
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            font-weight: bold;
        }
        th.dt-ordering-desc::after {
            content: "▼";
            color: #667eea;
            font-size: 1.1em;
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            font-weight: bold;
        }
        th.dt-orderable-asc:not(.dt-ordering-asc):not(.dt-ordering-desc)::after,
        th.dt-orderable-desc:not(.dt-ordering-asc):not(.dt-ordering-desc)::after {
            content: "▲▼";
            color: #d1d5db;
            font-size: 1.1em;
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            font-weight: bold;
        }

        /* Animation for sections */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .category-section {
            animation: fadeInUp 0.5s ease-out;
        }

        .designs-section {
            animation: fadeInUp 0.5s ease-out 0.1s;
            animation-fill-mode: both;
        }

        /* Loading spinner animation */
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .fa-spin {
            animation: spin 1s linear infinite;
        }

        /* Hover effect for table rows */
        #categoryTable tbody tr,
        #designTable tbody tr {
            transition: all 0.2s ease;
        }

        #categoryTable tbody tr:hover,
        #designTable tbody tr:hover {
            background-color: #f8fafc !important;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        /* Badge enhancement */
        .badge {
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }
    </style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <div class="admin-dashboard">
        <?php echo $__env->make('admin.components.sidebar', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
        <main class="main">
            <div class="main-header">
                <div>
                    <div class="title">Prototype Desain</div>
                    <div class="subtitle">Manajemen Desain Prototype Rumah & Kategori</div>
                </div>
                <div class="header-actions">
                    <button type="button" class="btn-primary" onclick="openAddDesignModal()">
                        <i class="fas fa-plus"></i> Tambah Desain
                    </button>
                    <button type="button" class="btn-secondary" onclick="loadDesigns()">
                        <i class="fas fa-sync"></i> Refresh
                    </button>
                </div>
            </div>
            <div class="main-content">
                <div id="alert-container"></div>
                
                <!-- Kategori Desain Prototype Section -->
                <div class="content-section category-section">
                    <div class="section-header">
                        <div class="section-header-left">
                            <div class="section-icon">
                                <i class="fas fa-folder-open"></i>
                            </div>
                            <div>
                                <h2 class="section-title-new">Kategori Desain Prototype</h2>
                                <p class="section-subtitle">Kelola kategori untuk mengelompokkan desain prototype rumah</p>
                            </div>
                        </div>
                        <button class="btn-primary" onclick="openAddCategoryModal()">
                            <i class="fas fa-plus"></i> Tambah Kategori
                        </button>
                    </div>
                    <div class="section-body">
                        <div id="categoryListContainer">
                            <div class="loading-spinner">
                                <i class="fas fa-spinner fa-spin"></i> Memuat data...
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Daftar Desain Prototype Section -->
                <div class="content-section designs-section">
                    <div class="section-header">
                        <div class="section-header-left">
                            <div class="section-icon designs-icon">
                                <i class="fas fa-drafting-compass"></i>
                            </div>
                            <div>
                                <h2 class="section-title-new">Daftar Desain Prototype</h2>
                                <p class="section-subtitle">Kelola semua desain prototype rumah yang tersedia</p>
                            </div>
                        </div>
                        <button class="btn-primary" onclick="openAddDesignModal()">
                            <i class="fas fa-plus"></i> Tambah Desain
                        </button>
                    </div>
                    <div class="section-body">
                        <div id="designListContainer">
                            <div class="loading-spinner">
                                <i class="fas fa-spinner fa-spin"></i> Memuat data...
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal Add/Edit Design -->
            <div id="designModal" class="modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <div class="modal-title" id="designModalTitle">Tambah Desain</div>
                        <span class="close" onclick="closeDesignModal()">&times;</span>
                    </div>
                    <div class="form-container">
                        <form id="designForm" enctype="multipart/form-data">
                            <input type="hidden" id="design_id" name="id">
                            <div class="form-group">
                                <label for="design_title">Judul Desain</label>
                                <input type="text" id="design_title" name="title" required maxlength="255"
                                    style="width:100%;padding:10px 14px;border-radius:8px;border:1px solid #d1d5db;">
                            </div>
                            <div class="form-group">
                                <label for="design_description">Deskripsi</label>
                                <textarea id="design_description" name="description" maxlength="1000"
                                    style="width:100%;padding:10px 14px;border-radius:8px;border:1px solid #d1d5db;"></textarea>
                            </div>
                            <div class="form-group" style="background:#fff !important;">
                                <label for="design_category">Kategori</label>
                                <select id="design_category" name="category_id" required
                                    style="width:100% !important;padding:10px 14px !important;border-radius:8px !important;border:1px solid #d1d5db !important;background:#ffffff !important;background-color:#ffffff !important;color:#000000 !important;box-shadow:none !important;pointer-events:auto !important;cursor:pointer !important;opacity:1 !important;appearance:menulist !important;-webkit-appearance:menulist !important;-moz-appearance:menulist !important;">
                                    <option value="">Pilih Kategori</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="design_video">Video Terkait (opsional)</label>
                                <select id="design_video" name="video_id"
                                    style="width:100%;padding:10px 14px;border-radius:8px;border:1px solid #d1d5db;"></select>
                            </div>
                            <div class="form-group">
                                <label for="design_image">Gambar</label>
                                <input type="file" id="design_image" name="prototypeDesign_image" accept="image/*"
                                    style="width:100%;padding:10px 14px;border-radius:8px;border:1px solid #d1d5db;">
                            </div>
                            <div class="form-group">
                                <label for="design_file">File Desain (PDF/DWG)</label>
                                <input type="file" id="design_file" name="prototypeDesign_file" accept=".pdf"
                                    style="width:100%;padding:10px 14px;border-radius:8px;border:1px solid #d1d5db;">
                            </div>
                            <div class="form-group">
                                <label for="design_is_inherited">Status Distribusi</label>
                                <select id="design_is_inherited" name="is_inherited"
                                    style="width:100%;padding:10px 14px;border-radius:8px;border:1px solid #d1d5db;">
                                    <option value="0">Tidak Diturunkan</option>
                                    <option value="1">Diturunkan</option>
                                </select>
                            </div>
                            <div class="form-actions"
                                style="display:flex;justify-content:flex-end;gap:12px;margin-top:18px;">
                                <button type="button" class="btn-secondary" onclick="closeDesignModal()">Batal</button>
                                <button type="submit" class="btn-primary">Simpan</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Modal Add/Edit Category -->
            <div id="categoryModal" class="modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <div class="modal-title" id="categoryModalTitle">Tambah Kategori</div>
                        <span class="close" onclick="closeCategoryModal()">&times;</span>
                    </div>
                    <div class="form-container">
                        <form id="categoryForm">
                            <input type="hidden" id="category_id" name="id">
                            <div class="form-group">
                                <label for="category_name">Nama Kategori</label>
                                <input type="text" id="category_name" name="name" required maxlength="255"
                                    style="width:100%;padding:10px 14px;border-radius:8px;border:1px solid #d1d5db;">
                            </div>
                            <div class="form-group">
                                <label for="category_description">Deskripsi</label>
                                <textarea id="category_description" name="description" maxlength="100"
                                    style="width:100%;padding:10px 14px;border-radius:8px;border:1px solid #d1d5db;"></textarea>
                            </div>
                            <div class="form-actions"
                                style="display:flex;justify-content:flex-end;gap:12px;margin-top:18px;">
                                <button type="button" class="btn-secondary"
                                    onclick="closeCategoryModal()">Batal</button>
                                <button type="submit" class="btn-primary">Simpan</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        const baseUrl = '<?php echo e(env('BASE_URL')); ?>';
        let designList = [];
        let categoryList = [];
        let videoList = [];
        let userRole = '<?php echo e(session('auth.user.role') ?? ''); ?>';

        // Debug baseUrl dan user session
        console.log('=== CONFIGURATION ===');
        console.log('Base URL:', baseUrl);
        console.log('User Role:', userRole);
        console.log('User Session Data:', {
            userId: '<?php echo e(session('auth.user.id') ?? 'not found'); ?>',
            siteId: '<?php echo e(session('auth.user.site_id') ?? 'not found'); ?>',
            username: '<?php echo e(session('auth.user.username') ?? 'not found'); ?>',
            email: '<?php echo e(session('auth.user.email') ?? 'not found'); ?>',
            fullUserData: <?php echo json_encode(session('auth.user', 'session not found'), 512) ?>,
            allSessionKeys: <?php echo json_encode(array_keys(session()->all()), 15, 512) ?>
        });

        function showAlert(message, type = 'success') {
            const alertContainer = document.getElementById('alert-container');
            const alertClass = type === 'success' ? 'alert-success' : 'alert-error';
            alertContainer.innerHTML = `<div class="alert ${alertClass}">${message}</div>`;
            setTimeout(() => {
                alertContainer.innerHTML = '';
            }, 4000);
        }

        function getAuthToken() {
            // Try multiple possible token storage locations
            let token = localStorage.getItem('accessToken') ||
                localStorage.getItem('auth_token') ||
                localStorage.getItem('token') ||
                sessionStorage.getItem('accessToken') ||
                sessionStorage.getItem('auth_token') ||
                sessionStorage.getItem('token');

            console.log('=== TOKEN CHECK ===');
            console.log('localStorage.accessToken:', localStorage.getItem('accessToken'));
            console.log('localStorage.auth_token:', localStorage.getItem('auth_token'));
            console.log('localStorage.token:', localStorage.getItem('token'));
            console.log('sessionStorage.accessToken:', sessionStorage.getItem('accessToken'));
            console.log('Final token:', token ? 'Found' : 'Not found');

            return token || '';
        }

        async function loadDesigns() {
            try {
                const token = getAuthToken();
                const res = await fetch(baseUrl + '/api/admin/prototype-design', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                const data = await res.json();
                designList = Array.isArray(data) ? data : (data.data || []);
                renderDesignList();
            } catch (err) {
                showAlert('Gagal memuat desain: ' + err.message, 'error');
            }
        }

        // Move updateCategoryDropdown to global scope
        function updateCategoryDropdown() {
            const select = document.getElementById('design_category');
            if (!select) {
                console.log('Select element not found!');
                return;
            }

            console.log('=== UPDATE CATEGORY DROPDOWN ===');
            console.log('Select element:', select);
            console.log('CategoryList:', categoryList);
            console.log('CategoryList length:', categoryList ? categoryList.length : 'undefined');

            // Paksa reset semua style dan properties
            select.disabled = false;
            select.style.removeProperty('background');
            select.style.removeProperty('background-color');
            select.style.removeProperty('color');
            select.style.removeProperty('pointer-events');
            select.style.removeProperty('opacity');
            select.style.removeProperty('box-shadow');

            // Set style yang benar dengan force
            select.style.setProperty('background', '#ffffff', 'important');
            select.style.setProperty('background-color', '#ffffff', 'important');
            select.style.setProperty('color', '#000000', 'important');
            select.style.setProperty('pointer-events', 'auto', 'important');
            select.style.setProperty('cursor', 'pointer', 'important');
            select.style.setProperty('opacity', '1', 'important');
            select.style.setProperty('border', '1px solid #d1d5db', 'important');
            select.style.setProperty('box-shadow', 'none', 'important');

            // Isi dropdown
            if (!categoryList || categoryList.length === 0) {
                select.innerHTML = '<option value="">Belum ada kategori</option>';
                console.log('No categories available');
            } else {
                const options = '<option value="">Pilih Kategori</option>' +
                    categoryList.map(cat => {
                        console.log('Adding category:', cat);
                        return `<option value="${cat.id}">${cat.name}</option>`;
                    }).join('');
                select.innerHTML = options;
                console.log('Added', categoryList.length, 'categories to dropdown');
                console.log('Final dropdown HTML:', select.innerHTML);
            }

            // Force refresh
            select.blur();
            select.focus();
            select.blur();
        }

        async function loadCategories() {
            try {
                const token = getAuthToken();
                const res = await fetch(baseUrl + '/api/admin/prototype-design-category', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                if (!res.ok) {
                    throw new Error(`HTTP ${res.status}: ${res.statusText}`);
                }
                const data = await res.json();
                categoryList = Array.isArray(data) ? data : (data.data || []);
                updateCategoryDropdown();
                renderCategoryList();
            } catch (err) {
                showAlert('Gagal memuat kategori: ' + err.message, 'error');
                const select = document.getElementById('design_category');
                if (select) {
                    select.innerHTML = '<option value="">Gagal memuat kategori</option>';
                }
                categoryList = [];
            }
        }

        function renderCategoryList() {
            const container = document.getElementById('categoryListContainer');
            if (!categoryList || categoryList.length === 0) {
                container.innerHTML = `
                    <div style="text-align:center;padding:60px 20px;">
                        <i class="fas fa-folder-open" style="font-size:4rem;color:#d1d5db;margin-bottom:16px;display:block;"></i>
                        <p style="color:#6b7280;font-size:1.1rem;margin:0;font-weight:600;">Belum ada kategori</p>
                        <p style="color:#9ca3af;font-size:0.95rem;margin-top:8px;">Klik tombol "Tambah Kategori" untuk menambahkan kategori baru</p>
                    </div>
                `;
                return;
            }
            container.innerHTML = `<table id="categoryTable" class="display" style="width:100%;border-radius:12px;overflow:hidden;">
		<thead>
			<tr>
				<th>Nama Kategori</th>
				<th>Deskripsi</th>
				<th>Aksi</th>
			</tr>
		</thead>
		<tbody>
		${categoryList.map(cat => `
    			<tr>
    				<td><strong style="color:#23272b;">${cat.name}</strong></td>
    				<td>${cat.description || '<span style="color:#9ca3af;font-style:italic;">Tidak ada deskripsi</span>'}</td>
    				<td style="min-width:120px;">
    					<button class="btn-primary" style="padding:6px 18px;border-radius:8px;font-weight:600;font-size:0.95rem;margin-right:6px;" onclick="openEditCategoryModal(${cat.id})"><i class="fas fa-edit"></i> Edit</button>
    					<button class="btn-danger" style="padding:6px 18px;border-radius:8px;font-weight:600;font-size:0.95rem;" onclick="deleteCategory(${cat.id})"><i class="fas fa-trash"></i></button>
    				</td>
    			</tr>
    		`).join('')}
		</tbody></table>`;
            if (window.$ && window.$.fn.dataTable) {
                $('#categoryTable').DataTable({
                    "order": [[0, "desc"]],
                    "pageLength": 10,
                    "responsive": true,
                    "autoWidth": false,
                    "language": {
                        "lengthMenu": "Tampilkan _MENU_ entri",
                        "zeroRecords": "Tidak ada data yang ditemukan",
                        "info": "Menampilkan halaman _PAGE_ dari _PAGES_",
                        "infoEmpty": "Tidak ada data",
                        "infoFiltered": "(disaring dari _MAX_ total entri)",
                        "search": "Cari:",
                        "paginate": {
                            "first": "Pertama",
                            "last": "Terakhir",
                            "next": "Selanjutnya",
                            "previous": "Sebelumnya"
                        }
                    },
                    "columnDefs": [
                        { targets: '_all', className: 'dt-center' }
                    ],
                    "drawCallback": function(settings) {
                        $('#categoryTable thead th').removeClass('dt-ordering-asc dt-ordering-desc');
                        var order = settings.aaSorting && settings.aaSorting[0];
                        if (order) {
                            var colIdx = order[0];
                            var dir = order[1];
                            var th = $('#categoryTable thead th').eq(colIdx);
                            th.addClass(dir === 'asc' ? 'dt-ordering-asc' : 'dt-ordering-desc');
                        }
                    }
                });
            } else {
                const scriptJq = document.createElement('script');
                scriptJq.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
                scriptJq.onload = () => {
                    const scriptDt = document.createElement('script');
                    scriptDt.src = 'https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js';
                    scriptDt.onload = () => {
                        $('#categoryTable').DataTable({
                            "order": [[0, "desc"]],
                            "pageLength": 10,
                            "responsive": true,
                            "autoWidth": false,
                            "language": {
                                "lengthMenu": "Tampilkan _MENU_ entri",
                                "zeroRecords": "Tidak ada data yang ditemukan",
                                "info": "Menampilkan halaman _PAGE_ dari _PAGES_",
                                "infoEmpty": "Tidak ada data",
                                "infoFiltered": "(disaring dari _MAX_ total entri)",
                                "search": "Cari:",
                                "paginate": {
                                    "first": "Pertama",
                                    "last": "Terakhir",
                                    "next": "Selanjutnya",
                                    "previous": "Sebelumnya"
                                }
                            },
                            "columnDefs": [
                                { targets: '_all', className: 'dt-center' }
                            ],
                            "drawCallback": function(settings) {
                                $('#categoryTable thead th').removeClass('dt-ordering-asc dt-ordering-desc');
                                var order = settings.aaSorting && settings.aaSorting[0];
                                if (order) {
                                    var colIdx = order[0];
                                    var dir = order[1];
                                    var th = $('#categoryTable thead th').eq(colIdx);
                                    th.addClass(dir === 'asc' ? 'dt-ordering-asc' : 'dt-ordering-desc');
                                }
                            }
                        });
                    };
                    document.body.appendChild(scriptDt);
                };
                document.body.appendChild(scriptJq);
            }
        }

        function openAddCategoryModal() {
            document.getElementById('categoryModalTitle').textContent = 'Tambah Kategori';
            document.getElementById('categoryForm').reset();
            document.getElementById('category_id').value = '';
            document.getElementById('categoryModal').style.display = 'block';
        }

        function openEditCategoryModal(id) {
            const cat = categoryList.find(c => c.id === id);
            if (!cat) return;
            document.getElementById('categoryModalTitle').textContent = 'Edit Kategori';
            document.getElementById('category_id').value = cat.id;
            document.getElementById('category_name').value = cat.name;
            document.getElementById('category_description').value = cat.description || '';
            document.getElementById('categoryModal').style.display = 'block';
        }

        function closeCategoryModal() {
            document.getElementById('categoryModal').style.display = 'none';
        }

        document.getElementById('categoryForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const id = document.getElementById('category_id').value;
            const name = document.getElementById('category_name').value;
            const description = document.getElementById('category_description').value;
            const token = getAuthToken();
            try {
                let res;
                const headers = {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                };
                if (id) {
                    res = await fetch(baseUrl + '/api/admin/prototype-design-category/' + id, {
                        method: 'PUT',
                        headers,
                        body: JSON.stringify({
                            name,
                            description
                        })
                    });
                } else {
                    res = await fetch(baseUrl + '/api/admin/prototype-design-category', {
                        method: 'POST',
                        headers,
                        body: JSON.stringify({
                            name,
                            description
                        })
                    });
                }
                if (!res.ok) throw new Error('Gagal menyimpan kategori');
                showAlert('Kategori berhasil disimpan!', 'success');
                closeCategoryModal();
                await loadCategories();
            } catch (err) {
                showAlert('Gagal simpan kategori: ' + err.message, 'error');
            }
        });

        async function deleteCategory(id) {
            if (!confirm('Hapus kategori ini?')) return;
            const token = getAuthToken();
            try {
                const res = await fetch(baseUrl + '/api/admin/prototype-design-category/' + id, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                if (!res.ok) throw new Error('Gagal hapus kategori');
                showAlert('Kategori berhasil dihapus!', 'success');
                await loadCategories();
            } catch (err) {
                showAlert('Gagal hapus kategori: ' + err.message, 'error');
            }
        }

        async function loadVideos() {
            try {
                const token = getAuthToken();
                const res = await fetch(baseUrl + '/api/admin/video', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                const data = await res.json();
                videoList = Array.isArray(data) ? data : (data.data || []);
                const select = document.getElementById('design_video');
                select.innerHTML = '<option value="">- Pilih Video -</option>' + videoList.map(v =>
                    `<option value="${v.id}">${v.name}</option>`).join('');
            } catch (err) {
                showAlert('Gagal memuat video: ' + err.message, 'error');
            }
        }

        function renderDesignList() {
            const container = document.getElementById('designListContainer');
            if (!designList || designList.length === 0) {
                container.innerHTML = `
                    <div style="text-align:center;padding:60px 20px;">
                        <i class="fas fa-drafting-compass" style="font-size:4rem;color:#d1d5db;margin-bottom:16px;display:block;"></i>
                        <p style="color:#6b7280;font-size:1.1rem;margin:0;font-weight:600;">Belum ada desain prototype</p>
                        <p style="color:#9ca3af;font-size:0.95rem;margin-top:8px;">Klik tombol "Tambah Desain" untuk menambahkan desain prototype baru</p>
                    </div>
                `;
                return;
            }

            console.log('=== DESIGN LIST DEBUG ===');
            console.log('Design list data:', designList);
            if (designList.length > 0) {
                console.log('First design object keys:', Object.keys(designList[0]));
                console.log('First design sample:', designList[0]);
            }

            container.innerHTML = `<table id="designTable" class="display" style="width:100%;border-radius:12px;overflow:hidden;">
		<thead>
			<tr>
				<th>Judul</th>
				<th>Kategori</th>
				<th>Deskripsi</th>
				<th>Gambar</th>
				<th>File</th>
				<th>Video</th>
				<th>Distribusi</th>
				<th>Aksi</th>
			</tr>
		</thead>
		<tbody>
		${designList.map(design => {
			console.log('Processing design:', design.id, design.title);
			
			// Handle different possible field names for images
			const imagePath = design.path_image || design.prototypeDesign_image || design.image_path || design.image;
			const filePath = design.path_file || design.prototypeDesign_file || design.file_path || design.file;
			
            // Category handling
            let categoryName = '-';
            if (design.category && design.category.name) {
                categoryName = design.category.name;
            } else if (design.category_name) {
                categoryName = design.category_name;
            } else if (design.category_id && Array.isArray(categoryList)) {
                var foundCat = categoryList.find(cat => cat.id == design.category_id || cat.id === String(design.category_id) || cat.id === Number(design.category_id));
                if (foundCat && foundCat.name) categoryName = foundCat.name;
            }
			
            // Video handling
            let videoName = '-';
            if (design.video && design.video.name) {
                videoName = design.video.name;
            } else if (design.video_name) {
                videoName = design.video_name;
            } else if (design.video_id && Array.isArray(videoList)) {
                var foundVid = videoList.find(v => v.id == design.video_id || v.id === String(design.video_id) || v.id === Number(design.video_id));
                if (foundVid && foundVid.name) videoName = foundVid.name;
            }
			
			// Image display
			const imageDisplay = imagePath ? 
				`<img src="${baseUrl}/${imagePath}" alt="Gambar" style="max-width:80px;height:60px;object-fit:cover;border-radius:8px;cursor:pointer;" onclick="window.open('${baseUrl}/${imagePath}', '_blank')">` : 
				'<span style="color:#9ca3af;">No Image</span>';
			
			// File download link
			const fileDisplay = filePath ? 
				`<a href="${baseUrl}/${filePath}" target="_blank" class="btn-primary" style="padding:4px 12px;border-radius:6px;text-decoration:none;font-size:0.85rem;"><i class="fas fa-download"></i> Download</a>` : 
				'<span style="color:#9ca3af;">No File</span>';
			
            // Video display
            let videoDisplay = '<span style="color:#9ca3af;">No Video</span>';
            let videoObj = null;
            if (design.video && (design.video.link_video || design.video.url || design.video.link)) {
                videoObj = design.video;
            } else if (design.video_id && Array.isArray(videoList)) {
                videoObj = videoList.find(v => v.id == design.video_id || v.id === String(design.video_id) || v.id === Number(design.video_id));
            }
            if (videoObj && (videoObj.link_video || videoObj.url || videoObj.link)) {
                let videoUrl = videoObj.link_video || videoObj.url || videoObj.link;
                // YouTube embed
                const ytMatch = videoUrl.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([\w-]+)/);
                if (ytMatch) {
                    videoDisplay = `<iframe width="180" height="100" src="https://www.youtube.com/embed/${ytMatch[1]}" frameborder="0" allowfullscreen style="border-radius:8px;border:1px solid #e5e7eb;"></iframe>`;
                } else {
                    // Jika bukan YouTube, tampilkan thumbnail atau link
                    videoDisplay = `<a href="${videoUrl}" target="_blank" style="color:#22c1b6;font-weight:600;text-decoration:underline;">${videoName}</a>`;
                }
            }
			
			return `
    				<tr>
    					<td><strong>${design.title || 'No Title'}</strong></td>
    					<td><span style="color:#374151;font-weight:600;">${categoryName}</span></td>
    					<td style="max-width:200px;">${design.description || '<span style="color:#9ca3af;">No Description</span>'}</td>
    					<td style="text-align:center;">${imageDisplay}</td>
    					<td style="text-align:center;">${fileDisplay}</td>
    					<td style="text-align:center;">${videoDisplay}</td>
    					<td><span class="badge" style="${design.is_inherited ? 'background:#14b8a6;color:#fff;' : 'background:#f59e42;color:#fff;'}">${design.is_inherited ? 'Diturunkan' : 'Tidak'}</span></td>
    					<td style="min-width:120px;">
    						<button class="btn-primary" style="padding:6px 18px;border-radius:8px;font-weight:600;font-size:0.95rem;margin-right:6px;" onclick="openEditDesignModal(${design.id})"><i class="fas fa-edit"></i> Edit</button>
    						<button class="btn-danger" style="padding:6px 18px;border-radius:8px;font-weight:600;font-size:0.95rem;" onclick="deleteDesign(${design.id})"><i class="fas fa-trash"></i></button>
    					</td>
    				</tr>
    			`;
		}).join('')}
		</tbody></table>`;
            if (window.$ && window.$.fn.dataTable) {
                $('#designTable').DataTable({
                    "order": [[0, "desc"]],
                    "pageLength": 10,
                    "responsive": true,
                    "autoWidth": false,
                    "language": {
                        "lengthMenu": "Tampilkan _MENU_ entri",
                        "zeroRecords": "Tidak ada data yang ditemukan",
                        "info": "Menampilkan halaman _PAGE_ dari _PAGES_",
                        "infoEmpty": "Tidak ada data",
                        "infoFiltered": "(disaring dari _MAX_ total entri)",
                        "search": "Cari:",
                        "paginate": {
                            "first": "Pertama",
                            "last": "Terakhir",
                            "next": "Selanjutnya",
                            "previous": "Sebelumnya"
                        }
                    },
                    "columnDefs": [
                        { targets: '_all', className: 'dt-center' }
                    ],
                    "drawCallback": function(settings) {
                        $('#designTable thead th').removeClass('dt-ordering-asc dt-ordering-desc');
                        var order = settings.aaSorting && settings.aaSorting[0];
                        if (order) {
                            var colIdx = order[0];
                            var dir = order[1];
                            var th = $('#designTable thead th').eq(colIdx);
                            th.addClass(dir === 'asc' ? 'dt-ordering-asc' : 'dt-ordering-desc');
                        }
                    }
                });
            } else {
                const scriptJq = document.createElement('script');
                scriptJq.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
                scriptJq.onload = () => {
                    const scriptDt = document.createElement('script');
                    scriptDt.src = 'https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js';
                    scriptDt.onload = () => {
                        $('#designTable').DataTable({
                            "order": [[0, "desc"]],
                            "pageLength": 10,
                            "responsive": true,
                            "autoWidth": false,
                            "language": {
                                "lengthMenu": "Tampilkan _MENU_ entri",
                                "zeroRecords": "Tidak ada data yang ditemukan",
                                "info": "Menampilkan halaman _PAGE_ dari _PAGES_",
                                "infoEmpty": "Tidak ada data",
                                "infoFiltered": "(disaring dari _MAX_ total entri)",
                                "search": "Cari:",
                                "paginate": {
                                    "first": "Pertama",
                                    "last": "Terakhir",
                                    "next": "Selanjutnya",
                                    "previous": "Sebelumnya"
                                }
                            },
                            "columnDefs": [
                                { targets: '_all', className: 'dt-center' }
                            ],
                            "drawCallback": function(settings) {
                                $('#designTable thead th').removeClass('dt-ordering-asc dt-ordering-desc');
                                var order = settings.aaSorting && settings.aaSorting[0];
                                if (order) {
                                    var colIdx = order[0];
                                    var dir = order[1];
                                    var th = $('#designTable thead th').eq(colIdx);
                                    th.addClass(dir === 'asc' ? 'dt-ordering-asc' : 'dt-ordering-desc');
                                }
                            }
                        });
                    };
                    document.body.appendChild(scriptDt);
                };
                document.body.appendChild(scriptJq);
            }
        }

        async function openAddDesignModal() {
            console.log('=== OPENING ADD DESIGN MODAL ===');
            document.getElementById('designModalTitle').textContent = 'Tambah Desain';
            document.getElementById('designForm').reset();
            document.getElementById('design_id').value = '';
            setInheritedField();

            // Pastikan kategori dan video sudah di-load sebelum modal tampil
            await loadCategories();
            await loadVideos();

            // Force enable ALL dropdowns
            const dropdowns = ['design_category', 'design_video', 'design_is_inherited'];
            dropdowns.forEach(function(id) {
                const select = document.getElementById(id);
                if (select) {
                    select.disabled = false;
                    select.removeAttribute('disabled');
                    // Force styling
                    select.style.setProperty('background', '#ffffff', 'important');
                    select.style.setProperty('background-color', '#ffffff', 'important');
                    select.style.setProperty('color', '#000000', 'important');
                    select.style.setProperty('pointer-events', 'auto', 'important');
                    select.style.setProperty('cursor', 'pointer', 'important');
                    select.style.setProperty('border', '1px solid #d1d5db', 'important');
                    select.style.setProperty('display', 'block', 'important');
                    select.style.setProperty('visibility', 'visible', 'important');
                    console.log('Dropdown force-enabled:', id);
                }
            });

            updateCategoryDropdown();
            document.getElementById('designModal').style.display = 'block';

            // Extra safety - update dropdown setelah modal visible
            setTimeout(() => {
                updateCategoryDropdown();
                console.log('Extra dropdown update after modal shown');
            }, 200);
        }

        function openEditDesignModal(id) {
            const design = designList.find(d => d.id === id);
            if (!design) return;
            document.getElementById('designModalTitle').textContent = 'Edit Desain';
            document.getElementById('design_id').value = design.id;
            document.getElementById('design_title').value = design.title;
            document.getElementById('design_description').value = design.description || '';
            document.getElementById('designModal').style.display = 'block';
            setInheritedField();
            // Ensure categories are loaded and dropdown is updated
            if (categoryList.length === 0) {
                loadCategories().then(() => {
                    updateCategoryDropdown();
                    document.getElementById('design_category').value = design.category_id || '';
                    document.getElementById('design_video').value = design.video_id || '';
                    document.getElementById('design_is_inherited').value = design.is_inherited ? '1' : '0';
                });
            } else {
                updateCategoryDropdown();
                document.getElementById('design_category').value = design.category_id || '';
                document.getElementById('design_video').value = design.video_id || '';
                document.getElementById('design_is_inherited').value = design.is_inherited ? '1' : '0';
            }
        }

        function closeDesignModal() {
            document.getElementById('designModal').style.display = 'none';
        }

        function setInheritedField() {
            const select = document.getElementById('design_is_inherited');
            if (userRole === 'superadmin') {
                select.disabled = false;
            } else {
                select.value = '0';
                select.disabled = true;
            }
        }

        document.getElementById('designForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            // Validasi field required
            const title = document.getElementById('design_title').value.trim();
            const category_id = document.getElementById('design_category').value;

            if (!title) {
                showAlert('Judul desain harus diisi!', 'error');
                return;
            }

            if (!category_id) {
                showAlert('Kategori harus dipilih!', 'error');
                return;
            }

            const id = document.getElementById('design_id').value;
            const description = document.getElementById('design_description').value.trim();
            const video_id = document.getElementById('design_video').value;
            const is_inherited = document.getElementById('design_is_inherited').value === '1';
            const token = getAuthToken();

            // Handle file upload
            const imageInput = document.getElementById('design_image');
            const fileInput = document.getElementById('design_file');
            const formData = new FormData();

            formData.append('title', title);
            formData.append('description', description);
            formData.append('category_id', category_id);
            if (video_id) formData.append('video_id', video_id);
            formData.append('is_inherited', is_inherited ? '1' : '0');

            // Add user session data from Laravel session
            const userSiteId = '<?php echo e(session('auth.user.site_id') ?? ''); ?>';
            const userId = '<?php echo e(session('auth.user.id') ?? ''); ?>';

            let finalSiteId = '1'; // Default fallback
            let finalUserId = '1'; // Default fallback

            if (userSiteId && userSiteId.trim() !== '' && userSiteId !== 'not found') {
                finalSiteId = userSiteId.trim();
            }
            if (userId && userId.trim() !== '' && userId !== 'not found') {
                finalUserId = userId.trim();
            }

            formData.append('site_id', finalSiteId);
            formData.append('user_id', finalUserId);
            formData.append('status', '1'); // Default active status

            if (imageInput.files[0]) {
                formData.append('prototypeDesign_image', imageInput.files[0]);
            }
            if (fileInput.files[0]) {
                formData.append('prototypeDesign_file', fileInput.files[0]);
            }

            try {
                let res;
                const headers = {
                    'Authorization': `Bearer ${token}`,
                    'Accept': 'application/json'
                    // Note: Don't set Content-Type for FormData, browser will set it automatically
                };

                if (id) {
                    // UPDATE: Use PUT directly for update
                    res = await fetch(baseUrl + '/api/admin/prototype-design/' + id, {
                        method: 'PUT',
                        headers,
                        body: formData
                    });
                } else {
                    res = await fetch(baseUrl + '/api/admin/prototype-design', {
                        method: 'POST',
                        headers,
                        body: formData
                    });
                }

                // Try to parse response as JSON
                let responseData;
                const contentType = res.headers.get('content-type');
                if (contentType && contentType.includes('application/json')) {
                    responseData = await res.json();
                } else {
                    const responseText = await res.text();
                    throw new Error(`Server returned non-JSON response: ${responseText.substring(0, 200)}`);
                }

                if (!res.ok) {
                    const errorMessage = responseData.message || responseData.error || 'Gagal menyimpan data';
                    throw new Error(`HTTP ${res.status}: ${errorMessage}`);
                }

                showAlert('Desain berhasil disimpan!', 'success');
                closeDesignModal();
                loadDesigns();
            } catch (err) {
                showAlert('Gagal simpan: ' + err.message, 'error');
            }
        });

        // Event listeners untuk dropdown category
        document.addEventListener('DOMContentLoaded', function() {
            console.log('=== DOM CONTENT LOADED ===');

            // Event listener untuk dropdown focus/click
            const categoryDropdown = document.getElementById('design_category');
            if (categoryDropdown) {
                // Event ketika dropdown di-focus atau diklik
                categoryDropdown.addEventListener('focus', function() {
                    console.log('=== DROPDOWN FOCUSED ===');
                    forceDropdownStyle(this);
                });

                categoryDropdown.addEventListener('click', function() {
                    console.log('=== DROPDOWN CLICKED ===');
                    forceDropdownStyle(this);
                });

                categoryDropdown.addEventListener('mousedown', function() {
                    console.log('=== DROPDOWN MOUSEDOWN ===');
                    forceDropdownStyle(this);
                });

                // Force style function
                function forceDropdownStyle(element) {
                    element.disabled = false;
                    element.removeAttribute('disabled');
                    element.style.setProperty('background', '#ffffff', 'important');
                    element.style.setProperty('background-color', '#ffffff', 'important');
                    element.style.setProperty('color', '#000000', 'important');
                    element.style.setProperty('pointer-events', 'auto', 'important');
                    element.style.setProperty('cursor', 'pointer', 'important');
                    element.style.setProperty('border', '1px solid #d1d5db', 'important');
                    element.style.setProperty('opacity', '1', 'important');

                    // Reload categories jika kosong
                    if (element.options.length <= 1) {
                        console.log('Dropdown empty, reloading categories...');
                        loadCategories().then(() => updateCategoryDropdown());
                    }
                }

                console.log('Dropdown event listeners added');
            }
        });

        async function deleteDesign(id) {
            if (!confirm('Hapus desain ini?')) return;
            const token = getAuthToken();
            try {
                const res = await fetch(baseUrl + '/api/admin/prototype-design/' + id, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                if (!res.ok) throw new Error('Gagal hapus data');
                showAlert('Desain berhasil dihapus!', 'success');
                loadDesigns();
            } catch (err) {
                showAlert('Gagal hapus: ' + err.message, 'error');
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            loadDesigns();
            loadCategories();
            loadVideos();

            // FORCE WHITE BACKGROUND SETIAP DETIK - ALL DROPDOWNS
            setInterval(function() {
                const dropdowns = ['design_category', 'design_video', 'design_is_inherited'];
                dropdowns.forEach(function(id) {
                    const select = document.getElementById(id);
                    if (select) {
                        // Paksa styling setiap detik
                        select.disabled = false;
                        select.removeAttribute('disabled');
                        select.style.setProperty('background', '#ffffff', 'important');
                        select.style.setProperty('background-color', '#ffffff', 'important');
                        select.style.setProperty('color', '#000000', 'important');
                        select.style.setProperty('pointer-events', 'auto', 'important');
                        select.style.setProperty('cursor', 'pointer', 'important');
                        select.style.setProperty('opacity', '1', 'important');
                        select.style.setProperty('filter', 'none', 'important');
                        select.style.setProperty('border', '1px solid #d1d5db', 'important');
                        select.style.setProperty('box-shadow', 'none', 'important');
                        select.style.setProperty('display', 'block', 'important');
                        select.style.setProperty('visibility', 'visible', 'important');
                    }
                });

                // HAPUS NICE-SELECT SETIAP DETIK
                const niceSelects = document.querySelectorAll(
                    '.nice-select, div.nice-select, .nice-select-dropdown');
                if (niceSelects.length > 0) {
                    niceSelects.forEach(el => el.remove());
                    console.log('Nice-select elements removed:', niceSelects.length);
                }
            }, 1000);

            // IMMEDIATE FORCE pada load
            setTimeout(function() {
                // RESTORE ALL DROPDOWNS
                const dropdowns = ['design_category', 'design_video', 'design_is_inherited'];
                dropdowns.forEach(function(id) {
                    const select = document.getElementById(id);
                    if (select) {
                        console.log('=== RESTORING DROPDOWN:', id, '===');
                        select.disabled = false;
                        select.style.cssText =
                            'width:100% !important; padding:10px 14px !important; border-radius:8px !important; border:1px solid #d1d5db !important; background:#ffffff !important; background-color:#ffffff !important; color:#000000 !important; box-shadow:none !important; pointer-events:auto !important; cursor:pointer !important; opacity:1 !important; appearance:menulist !important; display:block !important; visibility:visible !important;';
                    }
                });

                // HAPUS NICE-SELECT PLUGIN
                const niceSelects = document.querySelectorAll(
                    '.nice-select, div.nice-select, .nice-select-dropdown');
                niceSelects.forEach(el => {
                    console.log('Removing nice-select element:', el);
                    el.remove();
                });

                console.log('All dropdowns restored, nice-select removed');
            }, 100);
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.layoutadmin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\laravel\krs-jawa3-template\krs-jawa3-web-template\resources\views/admin/designprototypeAdmin.blade.php ENDPATH**/ ?>