@extends('layouts.app')

@section('title', 'Edit Produk - Kei\'s Store')

@section('content')
<div class="container-fluid px-4 py-3">

    {{-- HEADER SECTION --}}
    <div class="hero-section mb-5">
        <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3">
            <div>
                <h1 class="display-6 fw-bold mb-2">
                    ✨ Edit Produk
                </h1>
                <p class="text-muted mb-0">Perbarui informasi produk di Kei's Store</p>
            </div>
            
            <div>
                <a href="{{ route('product.index') }}" class="btn-outline-modern">
                    <i class="bi bi-arrow-left"></i>
                    <span>Kembali ke Daftar Produk</span>
                </a>
            </div>
        </div>
    </div>

    {{-- ERROR ALERT --}}
    @if($errors->any())
        <div class="alert-modern alert-error-modern mb-4">
            <i class="bi bi-exclamation-triangle-fill"></i>
            <div class="alert-content">
                <strong>Terjadi Kesalahan!</strong>
                <ul class="mb-0 mt-1 ps-3">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            <button class="close-alert"><i class="bi bi-x-lg"></i></button>
        </div>
    @endif

       {{-- FORM CARD --}}
    <div class="form-card">
        <div class="form-card-header">
            <div class="header-icon">
                <i class="bi bi-plus-circle-fill"></i>
            </div>
            <div>
                <h3 class="header-title">Form Edit Produk</h3>
                <p class="header-subtitle">Isi data produk di bawah ini dengan lengkap</p>
            </div>
        </div>


        <div class="form-card-body">
            <form action="{{ route('product.update', $produk->produk_id) }}" method="POST" enctype="multipart/form-data" class="modern-form" id="productForm">
                @csrf
                @method('PUT')

                <div class="row">
                    {{-- Kategori --}}
                    <div class="col-md-6 mb-4">
                        <label for="kategori_id" class="form-label-modern">
                            <i class="bi bi-tags-fill"></i>
                            Kategori
                            <span class="required-badge">Wajib</span>
                        </label>
                        <div class="input-wrapper">
                            <span class="input-icon">
                                <i class="bi bi-list-ul"></i>
                            </span>
                            <select name="kategori_id" id="kategori_id" class="form-input-modern" required>
                                <option value="">-- Pilih Kategori --</option>
                                @foreach($kategori as $kat)
                                    <option value="{{ $kat->kategori_id }}" {{ $produk->kategori_id == $kat->kategori_id ? 'selected' : '' }}>
                                        {{ $kat->nama_kategori }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        @error('kategori_id')
                            <div class="form-hint text-danger">
                                <i class="bi bi-exclamation-circle"></i>
                                {{ $message }}
                            </div>
                        @enderror
                    </div>

                    {{-- Nama Produk --}}
                    <div class="col-md-6 mb-4">
                        <label for="nama_produk" class="form-label-modern">
                            <i class="bi bi-box-seam"></i>
                            Nama Produk
                            <span class="required-badge">Wajib</span>
                        </label>
                        <div class="input-wrapper">
                            <span class="input-icon">
                                <i class="bi bi-card-text"></i>
                            </span>
                            <input type="text" name="nama_produk" id="nama_produk"
                                   class="form-input-modern" 
                                   value="{{ old('nama_produk', $produk->nama_produk) }}"
                                   placeholder="Masukkan nama produk..."
                                   maxlength="50"
                                   required>
                            <span class="input-character-count" id="productCharCount">0/50</span>
                        </div>
                        <div class="form-hint">
                            <i class="bi bi-info-circle"></i>
                            Maksimal 50 karakter
                        </div>
                        @error('nama_produk')
                            <div class="form-hint text-danger">
                                <i class="bi bi-exclamation-circle"></i>
                                {{ $message }}
                            </div>
                        @enderror
                    </div>

                    {{-- Harga --}}
                    <div class="col-md-6 mb-4">
                        <label for="harga" class="form-label-modern">
                            <i class="bi bi-currency-dollar"></i>
                            Harga
                            <span class="required-badge">Wajib</span>
                        </label>
                        <div class="input-wrapper">
                            <span class="input-icon">
                                <i class="bi bi-tag"></i>
                            </span>
                            <input type="number" step="0.01" name="harga" id="harga"
                                   class="form-input-modern" 
                                   value="{{ old('harga', $produk->harga) }}"
                                   placeholder="0.00"
                                   required>
                        </div>
                        @error('harga')
                            <div class="form-hint text-danger">
                                <i class="bi bi-exclamation-circle"></i>
                                {{ $message }}
                            </div>
                        @enderror
                    </div>

                    {{-- Stok --}}
                    <div class="col-md-6 mb-4">
                        <label for="stok" class="form-label-modern">
                            <i class="bi bi-box"></i>
                            Stok
                            <span class="required-badge">Wajib</span>
                        </label>
                        <div class="input-wrapper">
                            <span class="input-icon">
                                <i class="bi bi-grid-3x3"></i>
                            </span>
                            <input type="number" name="stok" id="stok"
                                   class="form-input-modern" 
                                   value="{{ old('stok', $produk->stok) }}"
                                   placeholder="0"
                                   required>
                        </div>
                        @error('stok')
                            <div class="form-hint text-danger">
                                <i class="bi bi-exclamation-circle"></i>
                                {{ $message }}
                            </div>
                        @enderror
                    </div>

                    {{-- Tanggal Kadaluarsa --}}
                    <div class="col-md-6 mb-4">
                        <label for="tanggal_kadaluarsa" class="form-label-modern">
                            <i class="bi bi-calendar-date"></i>
                            Tanggal Kadaluarsa
                        </label>
                        <div class="input-wrapper">
                            <span class="input-icon">
                                <i class="bi bi-calendar-check"></i>
                            </span>
                            <input type="date" name="tanggal_kadaluarsa" id="tanggal_kadaluarsa"
                                   class="form-input-modern" 
                                   value="{{ old('tanggal_kadaluarsa', $produk->tanggal_kadaluarsa) }}">
                        </div>
                        <div class="form-hint">
                            <i class="bi bi-info-circle"></i>
                            Kosongkan jika tidak ada tanggal kadaluarsa
                        </div>
                        @error('tanggal_kadaluarsa')
                            <div class="form-hint text-danger">
                                <i class="bi bi-exclamation-circle"></i>
                                {{ $message }}
                            </div>
                        @enderror
                    </div>

                    {{-- Foto --}}
                    <div class="col-12 mb-4">
                        <label class="form-label-modern">
                            <i class="bi bi-image"></i>
                            Foto Produk
                        </label>
                        
                        {{-- Current Photo --}}
                        @if($produk->foto || ($produk->images && $produk->images->count() > 0))
                            <div class="current-photos mb-3">
                                <label class="form-label-modern small">Foto Saat Ini:</label>
                                <div class="current-photos-grid">
                                    @if($produk->images && $produk->images->count() > 0)
                                        @foreach($produk->images as $img)
                                            <div class="current-photo-item">
                                                @php
                                                    $photoUrl = $img->foto;
                                                    if (!$photoUrl) {
                                                        $photoUrl = asset('images/no-image.png');
                                                    } elseif (!filter_var($photoUrl, FILTER_VALIDATE_URL)) {
                                                        $cleanPath = ltrim($photoUrl, '/');
                                                        $photoUrl = asset('storage/' . $cleanPath);
                                                    }
                                                @endphp
                                                <img src="{{ $photoUrl }}" alt="Foto Produk">
                                                <span class="photo-order">{{ $img->order == 1 ? 'Utama' : 'Foto ' . $img->order }}</span>
                                            </div>
                                        @endforeach
                                    @elseif($produk->foto)
                                        <div class="current-photo-item">
                                            @php
                                                $photoUrl = $produk->foto;
                                                if (!$photoUrl) {
                                                    $photoUrl = asset('images/no-image.png');
                                                } elseif (!filter_var($photoUrl, FILTER_VALIDATE_URL)) {
                                                    $cleanPath = ltrim($photoUrl, '/');
                                                    $photoUrl = asset('storage/' . $cleanPath);
                                                }
                                            @endphp
                                            <img src="{{ $photoUrl }}" alt="Foto Produk">
                                            <span class="photo-order">Foto Utama</span>
                                        </div>
                                    @endif
                                </div>
                            </div>
                        @endif

                        <div class="file-upload-wrapper">
                            <div class="file-upload-area" onclick="document.getElementById('foto').click()">
                                <i class="bi bi-cloud-upload"></i>
                                <p>Klik atau drag & drop untuk upload foto baru</p>
                                <small>Format: JPG, PNG, JPEG | Maks: 2MB per file</small>
                            </div>
                            <input type="file" name="foto[]" id="foto"
                                   class="file-input-hidden"
                                   accept="image/jpeg,image/png,image/jpg"
                                   multiple
                                   onchange="previewMultipleImages(this)">
                        </div>
                        <div class="form-hint mt-2">
                            <i class="bi bi-info-circle"></i>
                            Kosongkan jika tidak ingin mengganti foto. Bisa upload multiple foto (maksimal 5)
                        </div>
                        @error('foto')
                            <div class="form-hint text-danger">
                                <i class="bi bi-exclamation-circle"></i>
                                {{ $message }}
                            </div>
                        @enderror
                        @error('foto.*')
                            <div class="form-hint text-danger">
                                <i class="bi bi-exclamation-circle"></i>
                                {{ $message }}
                            </div>
                        @enderror
                    </div>
                </div>

                {{-- Preview Multiple Foto --}}
                <div class="row mb-4" id="foto-preview-container" style="display: none;">
                    <div class="col-12">
                        <label class="form-label-modern">
                            <i class="bi bi-eye"></i>
                            Preview Foto Baru
                        </label>
                        <div class="preview-gallery" id="foto-previews"></div>
                    </div>
                </div>

                {{-- ACTION BUTTONS --}}
                <div class="form-actions">
                    <button type="submit" class="btn-submit-modern" id="submitBtn">
                        <i class="bi bi-check-lg"></i>
                        <span>Update Produk</span>
                        <div class="btn-spinner d-none">
                            <div class="spinner-border spinner-border-sm" role="status"></div>
                        </div>
                    </button>
                    <a href="{{ route('product.index') }}" class="btn-cancel-modern">
                        <i class="bi bi-x-lg"></i>
                        <span>Batal</span>
                    </a>
                </div>
            </form>
        </div>
    </div>

    {{-- INFO TIPS --}}
    <div class="info-tips mt-4">
        <div class="tips-content">
            <i class="bi bi-lightbulb-fill"></i>
            <div>
                <strong>Tips:</strong>
                Upload foto baru akan mengganti semua foto yang ada. Foto pertama yang diupload akan menjadi foto utama.
            </div>
        </div>
    </div>
</div>

<style>
/* MODERN CSS RESET & VARIABLES */
:root {
    --pink-primary: #ec4899;
    --pink-dark: #db2777;
    --pink-light: #fdf2f8;
    --pink-soft: #fce7f3;
    --pink-gradient: linear-gradient(135deg, #ec4899 0%, #db2777 100%);
    --pink-gradient-soft: linear-gradient(135deg, #fbcfe8 0%, #fce7f3 100%);
    --gray-50: #faf9fe;
    --gray-100: #f5f3ff;
    --gray-200: #ede9fe;
    --gray-600: #6b7280;
    --gray-800: #1f2937;
    --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
    --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1);
    --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1);
    --shadow-xl: 0 20px 25px -5px rgb(0 0 0 / 0.1);
    --shadow-pink: 0 4px 14px 0 rgba(236, 72, 153, 0.25);
    --shadow-pink-lg: 0 20px 25px -12px rgba(236, 72, 153, 0.3);
}

/* HERO SECTION */
.hero-section {
    background: linear-gradient(135deg, #fdf2f8 0%, #fce7f3 100%);
    padding: 2rem 2rem;
    border-radius: 28px;
    margin-bottom: 2rem;
}

.display-6 {
    font-size: 1.875rem;
    background: linear-gradient(135deg, #ec4899 0%, #db2777 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

/* BUTTON OUTLINE MODERN */
.btn-outline-modern {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    background: transparent;
    color: var(--pink-primary);
    border: 2px solid var(--pink-primary);
    border-radius: 60px;
    font-weight: 600;
    font-size: 0.875rem;
    text-decoration: none;
    transition: all 0.3s ease;
}

.btn-outline-modern:hover {
    background: var(--pink-primary);
    color: white;
    transform: translateY(-2px);
    box-shadow: var(--shadow-pink);
}

/* ALERT MODERN */
.alert-modern {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 16px 20px;
    border-radius: 16px;
    font-size: 0.875rem;
    position: relative;
    animation: slideDown 0.3s ease;
}

@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.alert-error-modern {
    background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
    border: 1px solid #fecaca;
    color: #991b1b;
}

.alert-content {
    flex: 1;
}

.alert-content strong {
    display: block;
    margin-bottom: 4px;
}

.alert-content ul {
    margin-top: 8px;
    padding-left: 20px;
}

.close-alert {
    margin-left: auto;
    background: none;
    border: none;
    cursor: pointer;
    color: inherit;
    opacity: 0.6;
    transition: opacity 0.2s;
}

.close-alert:hover {
    opacity: 1;
}

/* FORM CARD */
.form-card {
    background: white;
    border-radius: 24px;
    overflow: hidden;
    box-shadow: var(--shadow-lg);
    border: 1px solid rgba(236, 72, 153, 0.1);
}

.form-card-header {
    background: linear-gradient(135deg, #fdf2f8 0%, #fce7f3 100%);
    padding: 24px 32px;
    display: flex;
    align-items: center;
    gap: 16px;
    border-bottom: 1px solid rgba(236, 72, 153, 0.1);
}

.header-icon {
    width: 56px;
    height: 56px;
    background: var(--pink-gradient);
    border-radius: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.header-icon i {
    font-size: 28px;
    color: white;
}

.header-title {
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--gray-800);
    margin: 0 0 4px 0;
}

.header-subtitle {
    font-size: 0.875rem;
    color: var(--gray-600);
    margin: 0;
}

.form-card-body {
    padding: 32px;
}

/* FORM GROUP MODERN */
.form-label-modern {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: var(--gray-800);
    margin-bottom: 12px;
    font-size: 0.9rem;
}

.form-label-modern i {
    color: var(--pink-primary);
    font-size: 1rem;
}

.required-badge {
    background: var(--pink-soft);
    color: var(--pink-primary);
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 500;
    margin-left: 8px;
}

.input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
}

.input-icon {
    position: absolute;
    left: 16px;
    color: #9ca3af;
    font-size: 1rem;
    pointer-events: none;
    z-index: 1;
}

.form-input-modern {
    width: 100%;
    padding: 14px 16px 14px 44px;
    font-size: 1rem;
    border: 2px solid #e5e7eb;
    border-radius: 16px;
    transition: all 0.3s ease;
    background: white;
}

select.form-input-modern {
    appearance: none;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right 16px center;
    background-size: 16px;
    padding-right: 44px;
}

.form-input-modern:focus {
    outline: none;
    border-color: var(--pink-primary);
    box-shadow: 0 0 0 4px rgba(236, 72, 153, 0.1);
}

.form-input-modern.is-valid {
    border-color: #10b981;
}

.form-input-modern.is-invalid {
    border-color: #ef4444;
}

.input-character-count {
    position: absolute;
    right: 16px;
    font-size: 0.7rem;
    color: var(--gray-600);
    pointer-events: none;
}

.form-hint {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-top: 8px;
    font-size: 0.75rem;
    color: var(--gray-600);
}

.form-hint i {
    font-size: 0.7rem;
}

.form-hint.text-danger {
    color: #ef4444;
}

/* CURRENT PHOTOS */
.current-photos {
    margin-bottom: 20px;
}

.current-photos-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin-top: 12px;
}

.current-photo-item {
    position: relative;
    width: 120px;
    border-radius: 12px;
    overflow: hidden;
    border: 2px solid var(--pink-soft);
    background: var(--gray-100);
}

.current-photo-item img {
    width: 100%;
    height: 120px;
    object-fit: cover;
}

.current-photo-item .photo-order {
    display: block;
    font-size: 0.7rem;
    padding: 6px;
    text-align: center;
    background: white;
    color: var(--pink-primary);
    font-weight: 500;
}

/* FILE UPLOAD */
.file-upload-wrapper {
    position: relative;
}

.file-upload-area {
    border: 2px dashed var(--pink-primary);
    border-radius: 16px;
    padding: 40px 20px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background: var(--pink-light);
}

.file-upload-area:hover {
    background: var(--pink-soft);
    border-color: var(--pink-dark);
}

.file-upload-area i {
    font-size: 3rem;
    color: var(--pink-primary);
    margin-bottom: 12px;
}

.file-upload-area p {
    margin: 0;
    font-weight: 500;
    color: var(--gray-800);
}

.file-upload-area small {
    color: var(--gray-600);
}

.file-input-hidden {
    display: none;
}

/* PREVIEW GALLERY */
.preview-gallery {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin-top: 16px;
}

.preview-item {
    position: relative;
    width: 150px;
    border-radius: 12px;
    overflow: hidden;
    border: 2px solid var(--pink-soft);
    background: var(--gray-100);
}

.preview-item img {
    width: 100%;
    height: 150px;
    object-fit: cover;
}

.preview-item .remove-preview {
    position: absolute;
    top: 8px;
    right: 8px;
    width: 28px;
    height: 28px;
    background: #ef4444;
    border: none;
    border-radius: 50%;
    color: white;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
}

.preview-item .remove-preview:hover {
    transform: scale(1.1);
    background: #dc2626;
}

.preview-item .file-name {
    font-size: 0.7rem;
    padding: 8px;
    text-align: center;
    background: white;
    color: var(--gray-600);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* FORM ACTIONS */
.form-actions {
    display: flex;
    gap: 16px;
    padding-top: 24px;
    border-top: 1px solid #e5e7eb;
}

.btn-submit-modern {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    padding: 12px 28px;
    background: var(--pink-gradient);
    color: white;
    border: none;
    border-radius: 60px;
    font-weight: 600;
    font-size: 0.875rem;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: var(--shadow-pink);
    min-width: 160px;
}

.btn-submit-modern:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: var(--shadow-pink-lg);
}

.btn-submit-modern:disabled {
    opacity: 0.7;
    cursor: not-allowed;
}

.btn-cancel-modern {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 28px;
    background: transparent;
    color: var(--gray-600);
    border: 2px solid #e5e7eb;
    border-radius: 60px;
    font-weight: 600;
    font-size: 0.875rem;
    text-decoration: none;
    transition: all 0.3s ease;
}

.btn-cancel-modern:hover {
    border-color: var(--pink-primary);
    color: var(--pink-primary);
    transform: translateY(-1px);
}

/* INFO TIPS */
.info-tips {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border-radius: 16px;
    padding: 12px 20px;
    border: 1px solid #fcd34d;
}

.tips-content {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 0.8rem;
    color: #92400e;
}

.tips-content i {
    font-size: 1.25rem;
}

/* RESPONSIVE */
@media (max-width: 768px) {
    .hero-section {
        padding: 1.5rem;
    }
    
    .display-6 {
        font-size: 1.25rem;
    }
    
    .form-card-header {
        padding: 20px;
    }
    
    .form-card-body {
        padding: 20px;
    }
    
    .form-actions {
        flex-direction: column;
    }
    
    .btn-submit-modern,
    .btn-cancel-modern {
        width: 100%;
        justify-content: center;
    }
    
    .preview-item {
        width: calc(50% - 8px);
    }
    
    .current-photo-item {
        width: calc(50% - 8px);
    }
}

@media (max-width: 480px) {
    .header-icon {
        width: 48px;
        height: 48px;
    }
    
    .header-icon i {
        font-size: 24px;
    }
    
    .header-title {
        font-size: 1rem;
    }
    
    .header-subtitle {
        font-size: 0.75rem;
    }
    
    .preview-item {
        width: 100%;
    }
    
    .current-photo-item {
        width: 100%;
    }
}

/* LOADING SPINNER */
.btn-spinner {
    display: inline-flex;
}

/* ANIMATION FOR FORM */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.form-card {
    animation: fadeInUp 0.5s ease;
}
</style>

<script>
// Character counter for product name
const productNameField = document.getElementById('nama_produk');
const productCharCount = document.getElementById('productCharCount');

if (productNameField) {
    const currentLength = productNameField.value.length;
    productCharCount.textContent = `${currentLength}/50`;
    
    if (currentLength > 0 && currentLength <= 50) {
        productNameField.classList.add('is-valid');
    }
    
    productNameField.addEventListener('input', function() {
        const length = this.value.length;
        productCharCount.textContent = `${length}/50`;
        
        if (length > 0 && length <= 50) {
            this.classList.remove('is-invalid');
            this.classList.add('is-valid');
        } else if (length > 50) {
            this.classList.remove('is-valid');
            this.classList.add('is-invalid');
        } else {
            this.classList.remove('is-valid', 'is-invalid');
        }
    });
}

// Preview multiple images
function previewMultipleImages(input) {
    const container = document.getElementById('foto-preview-container');
    const previewWrapper = document.getElementById('foto-previews');
    previewWrapper.innerHTML = '';
    
    if (input.files && input.files.length > 0) {
        container.style.display = 'block';
        
        const files = Array.from(input.files).slice(0, 5);
        
        files.forEach((file, index) => {
            if (!file.type.match('image.*')) {
                alert(`File ${file.name} bukan gambar!`);
                return;
            }
            
            if (file.size > 2 * 1024 * 1024) {
                alert(`File ${file.name} melebihi 2MB!`);
                return;
            }
            
            const reader = new FileReader();
            
            reader.onload = function(e) {
                const previewDiv = document.createElement('div');
                previewDiv.className = 'preview-item';
                
                previewDiv.innerHTML = `
                    <img src="${e.target.result}" alt="${file.name}">
                    <button type="button" class="remove-preview" onclick="removePreviewImage(this, ${index})">
                        <i class="bi bi-x"></i>
                    </button>
                    <div class="file-name" title="${file.name}">${file.name.substring(0, 20)}${file.name.length > 20 ? '...' : ''}</div>
                `;
                
                previewWrapper.appendChild(previewDiv);
            };
            
            reader.readAsDataURL(file);
        });
    } else {
        container.style.display = 'none';
    }
}

function removePreviewImage(button, index) {
    button.closest('.preview-item').remove();
    
    const input = document.getElementById('foto');
    const dt = new DataTransfer();
    const files = Array.from(input.files);
    
    files.forEach((file, i) => {
        if (i !== index) {
            dt.items.add(file);
        }
    });
    
    input.files = dt.files;
    
    if (input.files.length === 0) {
        document.getElementById('foto-preview-container').style.display = 'none';
        document.getElementById('foto-previews').innerHTML = '';
    } else {
        previewMultipleImages(input);
    }
}

// Limit to 5 files
const fotoInput = document.getElementById('foto');
if (fotoInput) {
    fotoInput.addEventListener('change', function(e) {
        if (this.files.length > 5) {
            alert('Maksimal upload 5 foto!');
            const dt = new DataTransfer();
            const files = Array.from(this.files).slice(0, 5);
            files.forEach(file => dt.items.add(file));
            this.files = dt.files;
            previewMultipleImages(this);
        }
    });
}

// Form submit with loading state
const form = document.getElementById('productForm');
const submitBtn = document.getElementById('submitBtn');
const btnText = submitBtn ? submitBtn.querySelector('span') : null;
const btnSpinner = submitBtn ? submitBtn.querySelector('.btn-spinner') : null;

if (form && submitBtn) {
    form.addEventListener('submit', function(e) {
        const kategori = document.getElementById('kategori_id').value;
        const namaProduk = document.getElementById('nama_produk').value;
        const harga = document.getElementById('harga').value;
        const stok = document.getElementById('stok').value;
        
        if (!kategori) {
            e.preventDefault();
            alert('Silakan pilih kategori!');
            return false;
        }
        
        if (!namaProduk.trim()) {
            e.preventDefault();
            document.getElementById('nama_produk').classList.add('is-invalid');
            alert('Masukkan nama produk!');
            return false;
        }
        
        if (namaProduk.length > 50) {
            e.preventDefault();
            alert('Nama produk maksimal 50 karakter!');
            return false;
        }
        
        if (!harga || harga <= 0) {
            e.preventDefault();
            alert('Masukkan harga yang valid!');
            return false;
        }
        
        if (stok === '' || stok < 0) {
            e.preventDefault();
            alert('Masukkan stok yang valid!');
            return false;
        }
        
        if (btnText && btnSpinner) {
            btnText.classList.add('d-none');
            btnSpinner.classList.remove('d-none');
        }
        submitBtn.disabled = true;
    });
}

// Close alert functionality
document.querySelectorAll('.close-alert').forEach(button => {
    button.addEventListener('click', function() {
        this.closest('.alert-modern').style.display = 'none';
    });
});

// Auto hide alerts after 5 seconds
setTimeout(function() {
    document.querySelectorAll('.alert-modern').forEach(alert => {
        alert.style.display = 'none';
    });
}, 5000);
</script>
@endsection