@extends('layouts.app')

@section('title', 'จัดการคลังสินค้า - ระบบจัดการค่าคอมมิชชั่น')

@section('content')
<div class="content-container">
    <!-- Enhanced Page Header -->
    <div class="page-header">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="page-title">
                    <i class="fas fa-warehouse text-blue-500 mr-3"></i>
                    จัดการคลังสินค้า
                </h1>
                <p class="page-subtitle">จัดการข้อมูลคลังสินค้าและอัตราค่าคอมมิชชั่น</p>
            </div>
            <div class="flex space-x-3">
                <button onclick="exportWarehouses()" class="btn btn-info">
                    <i class="fas fa-download"></i>Export CSV
                </button>
                <a href="{{ route('admin.warehouses.create') }}" class="btn btn-primary">
                    <i class="fas fa-plus"></i>เพิ่มคลังใหม่
                </a>
            </div>
        </div>
    </div>

    <!-- Enhanced Stats Cards -->
    <div class="dashboard-grid">
        <div class="dashboard-card dashboard-card-blue">
            <div class="dashboard-card-hover"></div>
            <div class="dashboard-card-main">
                <div class="dashboard-card-row">
                    <div class="dashboard-card-icon dashboard-card-icon-blue">
                        <i class="fas fa-warehouse"></i>
                    </div>
                    <div class="dashboard-card-info">
                        <div class="dashboard-card-num">{{ number_format($stats['total'] ?? 0) }}</div>
                        <div class="dashboard-card-label">คลังทั้งหมด</div>
                    </div>
                </div>
                <div class="dashboard-card-row2">
                    <div class="dashboard-card-status dashboard-card-status-blue">
                        <i class="fas fa-chart-line"></i>
                        <span>ทั้งระบบ</span>
                    </div>
                    <a href="#" class="dashboard-card-link">ดูรายละเอียด</a>
                </div>
            </div>
        </div>

        <div class="dashboard-card dashboard-card-green">
            <div class="dashboard-card-hover"></div>
            <div class="dashboard-card-main">
                <div class="dashboard-card-row">
                    <div class="dashboard-card-icon dashboard-card-icon-green">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="dashboard-card-info">
                        <div class="dashboard-card-num">{{ number_format($stats['active'] ?? 0) }}</div>
                        <div class="dashboard-card-label">ใช้งานอยู่</div>
                    </div>
                </div>
                <div class="dashboard-card-row2">
                    <div class="dashboard-card-status dashboard-card-status-green">
                        <i class="fas fa-check"></i>
                        <span>Active</span>
                    </div>
                    <a href="#" onclick="filterByStatus('active')" class="dashboard-card-link">กรองดู</a>
                </div>
            </div>
        </div>

        <div class="dashboard-card dashboard-card-purple">
            <div class="dashboard-card-hover"></div>
            <div class="dashboard-card-main">
                <div class="dashboard-card-row">
                    <div class="dashboard-card-icon dashboard-card-icon-purple">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="dashboard-card-info">
                        <div class="dashboard-card-num">{{ number_format($stats['with_users'] ?? 0) }}</div>
                        <div class="dashboard-card-label">มีผู้ใช้งาน</div>
                    </div>
                </div>
                <div class="dashboard-card-row2">
                    <div class="dashboard-card-status dashboard-card-status-purple">
                        <i class="fas fa-user-check"></i>
                        <span>Active Users</span>
                    </div>
                    <a href="#" class="dashboard-card-link">ดูรายชื่อ</a>
                </div>
            </div>
        </div>

        <div class="dashboard-card dashboard-card-orange">
            <div class="dashboard-card-hover"></div>
            <div class="dashboard-card-main">
                <div class="dashboard-card-row">
                    <div class="dashboard-card-icon dashboard-card-icon-orange">
                        <i class="fas fa-percentage"></i>
                    </div>
                    <div class="dashboard-card-info">
                        <div class="dashboard-card-num">{{ number_format($stats['with_rates'] ?? 0) }}</div>
                        <div class="dashboard-card-label">มีอัตราค่าคอมมิชชั่น</div>
                    </div>
                </div>
                <div class="dashboard-card-row2">
                    <div class="dashboard-card-status">
                        <i class="fas fa-calculator"></i>
                        <span>Commission</span>
                    </div>
                    <a href="#" class="dashboard-card-link">จัดการอัตรา</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Enhanced Filters -->
    <div class="modern-card">
        <div class="modern-card-header">
            <h3 class="modern-card-title">
                <i class="fas fa-filter text-blue-500"></i>
                ตัวกรองและค้นหา
            </h3>
        </div>
        <div class="modern-card-body">
            <form method="GET" action="{{ route('admin.warehouses.index') }}" class="filter-form">
                <div class="filter-grid">
                    <div class="form-group">
                        <label class="form-label">ค้นหา</label>
                        <div class="input-with-icon">
                            <i class="fas fa-search input-icon"></i>
                            <input type="text" name="search" value="{{ request('search') }}" 
                                   class="form-control" placeholder="รหัสคลัง, ชื่อ หรือที่อยู่">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">สถานะ</label>
                        <div class="input-with-icon">
                            <i class="fas fa-toggle-on input-icon"></i>
                            <select name="status" class="form-control">
                                <option value="">ทั้งหมด</option>
                                <option value="active" {{ request('status') === 'active' ? 'selected' : '' }}>
                                    ✅ ใช้งานอยู่
                                </option>
                                <option value="inactive" {{ request('status') === 'inactive' ? 'selected' : '' }}>
                                    ❌ ปิดใช้งาน
                                </option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">ประเภท</label>
                        <div class="input-with-icon">
                            <i class="fas fa-layer-group input-icon"></i>
                            <select name="type" class="form-control">
                                <option value="">ทั้งหมด</option>
                                <option value="with_users" {{ request('type') === 'with_users' ? 'selected' : '' }}>
                                    👥 มีผู้ใช้งาน
                                </option>
                                <option value="with_rates" {{ request('type') === 'with_rates' ? 'selected' : '' }}>
                                    💰 มีอัตราค่าคอมมิชชั่น
                                </option>
                                <option value="empty" {{ request('type') === 'empty' ? 'selected' : '' }}>
                                    📦 ว่าง
                                </option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">การดำเนินการ</label>
                        <div class="filter-actions">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i>ค้นหา
                            </button>
                            <a href="{{ route('admin.warehouses.index') }}" class="btn btn-secondary">
                                <i class="fas fa-times"></i>ล้าง
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Bulk Actions -->
    <div class="modern-card" id="bulkActions" style="display: none;">
        <div class="modern-card-body">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-3">
                    <div class="text-lg font-semibold text-blue-600">
                        <i class="fas fa-check-circle"></i>
                        เลือกแล้ว <span id="selectedCount">0</span> รายการ
                    </div>
                </div>
                <div class="flex space-x-2">
                    <button onclick="bulkAction('activate')" class="btn btn-success">
                        <i class="fas fa-check"></i>เปิดใช้งาน
                    </button>
                    <button onclick="bulkAction('deactivate')" class="btn btn-warning">
                        <i class="fas fa-ban"></i>ปิดใช้งาน
                    </button>
                    <button onclick="clearSelection()" class="btn btn-secondary">
                        <i class="fas fa-times"></i>ยกเลิก
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Enhanced Warehouses Table -->
    <div class="modern-card">
        <div class="modern-card-header">
            <div class="flex items-center justify-between">
                <h3 class="modern-card-title">
                    <i class="fas fa-list text-green-500"></i>
                    รายการคลังสินค้า
                </h3>
                <div class="text-sm text-gray-600">
                    ทั้งหมด {{ ($warehouses ?? collect())->total() ?? 0 }}รายการ
                </div>
            </div>
        </div>
        
        <div class="modern-card-body p-0">
            <div class="table-responsive">
                <table class="modern-table">
                    <thead>
                        <tr>
                            <th style="width: 50px;">
                                <input type="checkbox" id="selectAll" class="modern-checkbox">
                            </th>
                            <th>คลังสินค้า</th>
                            <th>สถานะ</th>
                            <th>ผู้ใช้งาน</th>
                            <th>อัตราค่าคอมมิชชั่น</th>
                            <th>สร้างเมื่อ</th>
                            <th style="width: 150px;">การดำเนินการ</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($warehouses ?? [] as $warehouse)
                        <tr class="table-row">
                            <td>
                                <input type="checkbox" class="warehouse-checkbox modern-checkbox" 
                                       value="{{ $warehouse->id }}">
                            </td>
                            <td>
                                <div class="warehouse-info">
                                    <div class="warehouse-avatar">
                                        {{ strtoupper(substr($warehouse->code ?? 'W', 0, 2)) }}
                                    </div>
                                    <div class="warehouse-details">
                                        <div class="warehouse-code">{{ $warehouse->code ?? 'ไม่ระบุรหัส' }}</div>
                                        <div class="warehouse-name">{{ $warehouse->name ?? 'ไม่ระบุชื่อ' }}</div>
                                        @if($warehouse->location)
                                            <div class="warehouse-location">{{ Str::limit($warehouse->location, 50) }}</div>
                                        @endif
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="status-badge status-{{ ($warehouse->is_active ?? false) ? 'active' : 'inactive' }}">
                                    @if($warehouse->is_active ?? false)
                                        <i class="fas fa-check-circle"></i>
                                        ใช้งานอยู่
                                    @else
                                        <i class="fas fa-times-circle"></i>
                                        ปิดใช้งาน
                                    @endif
                                </span>
                            </td>
                            <td>
                                <div class="text-center">
                                    <div class="count-badge count-users">
                                        <i class="fas fa-users"></i>
                                        {{ $warehouse->users_count ?? 0 }}
                                    </div>
                                    @if(($warehouse->users_count ?? 0) > 0)
                                        <div class="count-detail">{{ $warehouse->active_users_count ?? 0 }} ใช้งาน</div>
                                    @endif
                                </div>
                            </td>
                            <td>
                                <div class="text-center">
                                    <div class="count-badge count-rates">
                                        <i class="fas fa-percentage"></i>
                                        {{ $warehouse->commission_rates_count ?? 0 }}
                                    </div>
                                    @if(($warehouse->commission_rates_count ?? 0) > 0)
                                        <div class="count-detail">{{ $warehouse->active_rates_count ?? 0 }} ใช้งาน</div>
                                    @endif
                                </div>
                            </td>
                            <td>
                                <div class="date-info">
                                    {{ $warehouse->created_at ? $warehouse->created_at->format('d/m/Y') : '-' }}
                                    @if($warehouse->created_at)
                                        <div class="time-info">{{ $warehouse->created_at->format('H:i') }}</div>
                                    @endif
                                </div>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <a href="{{ route('admin.warehouses.edit', $warehouse) }}" 
                                       class="action-btn action-edit" title="แก้ไข">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <button onclick="toggleWarehouseStatus({{ $warehouse->id }})" 
                                            class="action-btn action-toggle" 
                                            title="{{ ($warehouse->is_active ?? false) ? 'ปิดใช้งาน' : 'เปิดใช้งาน' }}">
                                        <i class="fas fa-{{ ($warehouse->is_active ?? false) ? 'eye-slash' : 'eye' }}"></i>
                                    </button>
                                    <a href="{{ route('admin.commission-rates.index', ['warehouse' => $warehouse->code]) }}" 
                                       class="action-btn action-commission" title="จัดการอัตราค่าคอมมิชชั่น">
                                        <i class="fas fa-percentage"></i>
                                    </a>
                                    @if(($warehouse->users_count ?? 0) === 0)
                                        <button onclick="deleteWarehouse({{ $warehouse->id }})" 
                                                class="action-btn action-delete" title="ลบคลัง">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    @endif
                                </div>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="7" class="empty-state">
                                <div class="empty-content">
                                    <i class="fas fa-warehouse text-6xl text-gray-300 mb-4"></i>
                                    <h3 class="text-xl font-semibold text-gray-500 mb-2">ไม่มีคลังสินค้า</h3>
                                    <p class="text-gray-400 mb-4">ยังไม่มีคลังสินค้าในระบบ หรือไม่พบผลการค้นหา</p>
                                    <a href="{{ route('admin.warehouses.create') }}" class="btn btn-primary">
                                        <i class="fas fa-plus"></i>เพิ่มคลังแรก
                                    </a>
                                </div>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Enhanced Pagination -->
        @if(isset($warehouses) && $warehouses->hasPages())
        <div class="modern-card-footer">
            <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    แสดง {{ $warehouses->firstItem() ?? 0 }} ถึง {{ $warehouses->lastItem() ?? 0 }} 
                    จากทั้งหมด {{ $warehouses->total() ?? 0 }} รายการ
                </div>
                <div class="pagination-wrapper">
                    {{ $warehouses->links() }}
                </div>
            </div>
        </div>
        @endif
    </div>
</div>

<!-- Enhanced Styles -->
<style>
/* Fix Horizontal Scrollbar */
* {
    box-sizing: border-box;
}

body {
    overflow-x: hidden;
}

.content-container {
    max-width: 100vw;
    overflow-x: hidden;
    padding-left: 1rem;
    padding-right: 1rem;
    box-sizing: border-box;
}

.page-header,
.modern-card,
.dashboard-grid {
    max-width: 100%;
    overflow-x: auto;
    box-sizing: border-box;
}

.page-header .flex {
    flex-wrap: wrap;
    gap: 1rem;
}

.dashboard-grid {
    width: 100%;
    min-width: 0;
}

/* Enhanced Filter Form Styles */
.filter-form {
    width: 100%;
    overflow-x: auto;
}

.filter-grid {
    display: grid;
    grid-template-columns: minmax(200px, 2fr) minmax(150px, 1.5fr) minmax(150px, 1.5fr) minmax(180px, 1.8fr);
    gap: 1rem;
    align-items: end;
    width: 100%;
    min-width: 0;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.form-label {
    font-weight: 500;
    color: var(--dark-gray);
    font-size: 0.9rem;
    margin-bottom: 0.25rem;
}

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

.input-icon {
    position: absolute;
    left: 0.75rem;
    color: var(--gray);
    font-size: 0.9rem;
    z-index: 1;
}

.form-control {
    width: 100%;
    padding: 0.75rem 1rem 0.75rem 2.5rem;
    border: 2px solid var(--medium-gray);
    border-radius: var(--radius-md);
    font-family: inherit;
    font-size: 0.95rem;
    transition: var(--transition-fast);
    background: var(--white);
}

.form-control:focus {
    outline: none;
    border-color: var(--primary-orange);
    box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.1);
}

.form-control::placeholder {
    color: var(--gray);
    opacity: 0.7;
}

.filter-actions {
    display: flex;
    gap: 0.5rem;
}

.filter-actions .btn {
    flex: 1;
    min-width: 0;
}

/* Modern Table Styles */
.table-responsive {
    overflow-x: auto;
    max-width: 100%;
    -webkit-overflow-scrolling: touch;
}

.modern-table {
    width: 100%;
    min-width: 800px;
    border-collapse: collapse;
    background: white;
    table-layout: auto;
}

.modern-table th {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    padding: 1rem 1.5rem;
    text-align: left;
    font-weight: 600;
    font-size: 0.875rem;
    color: var(--dark-gray);
    text-transform: uppercase;
    letter-spacing: 0.05em;
    border-bottom: 2px solid var(--medium-gray);
}

.modern-table td {
    padding: 1.25rem 1.5rem;
    border-bottom: 1px solid #f1f5f9;
    vertical-align: middle;
}

.table-row {
    transition: var(--transition-fast);
    cursor: pointer;
}

.table-row:hover {
    background: linear-gradient(135deg, rgba(59, 130, 246, 0.02) 0%, rgba(147, 197, 253, 0.02) 100%);
}

/* Warehouse Info Styles */
.warehouse-info {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.warehouse-avatar {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: 600;
    font-size: 1.1rem;
    flex-shrink: 0;
    box-shadow: var(--shadow-sm);
}

.warehouse-details {
    flex: 1;
    min-width: 0;
}

.warehouse-code {
    font-weight: 600;
    color: var(--primary-orange);
    font-size: 1rem;
    margin-bottom: 0.25rem;
}

.warehouse-name {
    font-weight: 500;
    color: var(--dark-gray);
    font-size: 0.95rem;
    margin-bottom: 0.25rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.warehouse-location {
    color: var(--gray);
    font-size: 0.8rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* Status Badge Styles */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    border-radius: var(--radius-full);
    font-size: 0.875rem;
    font-weight: 500;
    white-space: nowrap;
}

.status-active {
    background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
    color: #059669;
    border: 1px solid #6ee7b7;
}

.status-inactive {
    background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
    color: #dc2626;
    border: 1px solid #fca5a5;
}

/* Count Badge Styles */
.count-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.4rem 0.8rem;
    border-radius: var(--radius-md);
    font-size: 0.875rem;
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.count-users {
    background: linear-gradient(135deg, #ddd6fe 0%, #c4b5fd 100%);
    color: #7c3aed;
}

.count-rates {
    background: linear-gradient(135deg, #fed7aa 0%, #fdba74 100%);
    color: #ea580c;
}

.count-detail {
    font-size: 0.75rem;
    color: var(--gray);
}

/* Date Info Styles */
.date-info {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
}

.time-info {
    color: var(--gray);
    font-size: 0.8rem;
}

/* Action Buttons */
.action-buttons {
    display: flex;
    gap: 0.5rem;
    opacity: 0;
    transition: var(--transition-fast);
}

.table-row:hover .action-buttons {
    opacity: 1;
}

.action-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: var(--radius-sm);
    border: none;
    cursor: pointer;
    transition: var(--transition-fast);
    text-decoration: none;
    font-size: 0.875rem;
}

.action-edit {
    background: #dbeafe;
    color: #2563eb;
}

.action-edit:hover {
    background: #2563eb;
    color: white;
    transform: scale(1.1);
}

.action-toggle {
    background: #f3f4f6;
    color: #6b7280;
}

.action-toggle:hover {
    background: #6b7280;
    color: white;
    transform: scale(1.1);
}

.action-commission {
    background: #fef3c7;
    color: #d97706;
}

.action-commission:hover {
    background: #d97706;
    color: white;
    transform: scale(1.1);
}

.action-delete {
    background: #fee2e2;
    color: #dc2626;
}

.action-delete:hover {
    background: #dc2626;
    color: white;
    transform: scale(1.1);
}

/* Modern Checkbox */
.modern-checkbox {
    width: 18px;
    height: 18px;
    border: 2px solid var(--medium-gray);
    border-radius: 4px;
    cursor: pointer;
    transition: var(--transition-fast);
}

.modern-checkbox:checked {
    background: var(--primary-orange);
    border-color: var(--primary-orange);
}

/* Empty State */
.empty-state {
    padding: 4rem 2rem;
    text-align: center;
}

.empty-content {
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* Modern Card Footer */
.modern-card-footer {
    padding: 1rem 1.5rem;
    border-top: 1px solid var(--medium-gray);
    background: #f8fafc;
}

/* Pagination Wrapper */
.pagination-wrapper .pagination {
    display: flex;
    gap: 0.25rem;
}

.pagination-wrapper .page-link {
    padding: 0.5rem 0.75rem;
    border: 1px solid var(--medium-gray);
    border-radius: var(--radius-sm);
    color: var(--dark-gray);
    text-decoration: none;
    transition: var(--transition-fast);
}

.pagination-wrapper .page-link:hover {
    background: var(--primary-orange);
    color: white;
    border-color: var(--primary-orange);
}

.pagination-wrapper .page-item.active .page-link {
    background: var(--primary-orange);
    color: white;
    border-color: var(--primary-orange);
}

/* Button Variants */
.btn-info {
    background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%);
    color: white;
}

.btn-info:hover {
    background: linear-gradient(135deg, #0284c7 0%, #0369a1 100%);
    transform: translateY(-1px);
}

.btn-success {
    background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
    color: white;
}

.btn-success:hover {
    background: linear-gradient(135deg, #16a34a 0%, #15803d 100%);
    transform: translateY(-1px);
}

.btn-warning {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    color: white;
}

.btn-warning:hover {
    background: linear-gradient(135deg, #d97706 0%, #b45309 100%);
    transform: translateY(-1px);
}

.btn-secondary {
    background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
    color: white;
}

.btn-secondary:hover {
    background: linear-gradient(135deg, #4b5563 0%, #374151 100%);
    transform: translateY(-1px);
}

/* Responsive Design for Filter */
@media (max-width: 1200px) {
    .filter-grid {
        grid-template-columns: minmax(180px, 1fr) minmax(120px, 1fr) minmax(120px, 1fr) minmax(160px, 1fr);
        gap: 0.75rem;
    }
    
    .content-container {
        padding-left: 0.75rem;
        padding-right: 0.75rem;
    }
}

@media (max-width: 992px) {
    .filter-grid {
        grid-template-columns: 1fr 1fr;
        gap: 1rem;
    }
    
    .modern-table {
        min-width: 700px;
    }
}

@media (max-width: 768px) {
    .content-container {
        padding-left: 0.5rem;
        padding-right: 0.5rem;
    }
    
    .filter-grid {
        grid-template-columns: 1fr;
        gap: 1rem;
    }
    
    .filter-actions {
        flex-direction: row;
    }
    
    .filter-actions .btn {
        flex: 1;
        text-align: center;
    }
    
    .modern-table th:nth-child(n+5),
    .modern-table td:nth-child(n+5) {
        display: none;
    }
    
    .modern-table {
        min-width: 500px;
    }
    
    .action-buttons {
        opacity: 1;
    }
    
    .warehouse-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.5rem;
    }
    
    .warehouse-avatar {
        width: 40px;
        height: 40px;
        font-size: 1rem;
    }
    
    .dashboard-grid {
        grid-template-columns: 1fr;
    }
    
    .page-header .flex {
        flex-direction: column;
        align-items: stretch;
    }
}

@media (max-width: 480px) {
    .content-container {
        padding-left: 0.25rem;
        padding-right: 0.25rem;
    }
    
    .form-control {
        padding: 0.6rem 0.8rem 0.6rem 2.2rem;
        font-size: 0.9rem;
    }
    
    .input-icon {
        left: 0.6rem;
        font-size: 0.85rem;
    }
    
    .filter-actions {
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .modern-table th,
    .modern-table td {
        padding: 0.75rem 0.5rem;
        font-size: 0.875rem;
    }
    
    .modern-table th:nth-child(n+4),
    .modern-table td:nth-child(n+4) {
        display: none;
    }
    
    .modern-table {
        min-width: 400px;
    }
    
    .page-header,
    .modern-card {
        margin-left: 0;
        margin-right: 0;
        border-radius: 8px;
    }
}

/* Hide horizontal scrollbar but keep functionality */
::-webkit-scrollbar:horizontal {
    height: 0px;
    background: transparent;
}

.table-responsive::-webkit-scrollbar {
    height: 6px;
}

.table-responsive::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.table-responsive::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.table-responsive::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* Additional overflow fixes */
.main-content {
    overflow-x: hidden;
}

.modern-card-body {
    overflow-x: auto;
}

.flex {
    min-width: 0;
}

.flex > * {
    min-width: 0;
}
</style>

<!-- Enhanced JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// Enhanced functionality
document.addEventListener('DOMContentLoaded', function() {
    initializeCheckboxes();
    initializeTableInteractions();
});

// Initialize checkboxes
function initializeCheckboxes() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.warehouse-checkbox');
    
    selectAll?.addEventListener('change', function() {
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        updateBulkActions();
    });
    
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateBulkActions);
    });
}

// Initialize table interactions
function initializeTableInteractions() {
    const rows = document.querySelectorAll('.table-row');
    
    rows.forEach(row => {
        row.addEventListener('click', function(e) {
            // Don't trigger row click when clicking on buttons or checkboxes
            if (e.target.closest('.action-btn, .modern-checkbox')) {
                return;
            }
            
            // Toggle checkbox when clicking on row
            const checkbox = this.querySelector('.warehouse-checkbox');
            if (checkbox) {
                checkbox.checked = !checkbox.checked;
                updateBulkActions();
            }
        });
    });
}

// Update bulk actions visibility
function updateBulkActions() {
    const selectedCheckboxes = document.querySelectorAll('.warehouse-checkbox:checked');
    const bulkActions = document.getElementById('bulkActions');
    const selectedCount = document.getElementById('selectedCount');
    const selectAll = document.getElementById('selectAll');
    
    if (selectedCheckboxes.length > 0) {
        bulkActions.style.display = 'block';
        selectedCount.textContent = selectedCheckboxes.length;
        
        // Add slide down animation
        if (!bulkActions.classList.contains('show')) {
            bulkActions.style.opacity = '0';
            bulkActions.style.transform = 'translateY(-10px)';
            bulkActions.classList.add('show');
            
            setTimeout(() => {
                bulkActions.style.transition = 'all 0.3s ease';
                bulkActions.style.opacity = '1';
                bulkActions.style.transform = 'translateY(0)';
            }, 50);
        }
    } else {
        bulkActions.style.display = 'none';
        bulkActions.classList.remove('show');
    }
    
    // Update select all checkbox state
    const allCheckboxes = document.querySelectorAll('.warehouse-checkbox');
    if (selectAll) {
        selectAll.checked = allCheckboxes.length > 0 && selectedCheckboxes.length === allCheckboxes.length;
        selectAll.indeterminate = selectedCheckboxes.length > 0 && selectedCheckboxes.length < allCheckboxes.length;
    }
}

// Clear selection
function clearSelection() {
    document.querySelectorAll('.warehouse-checkbox').forEach(checkbox => {
        checkbox.checked = false;
    });
    document.getElementById('selectAll').checked = false;
    updateBulkActions();
    
    // Show feedback
    const toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 2000,
        timerProgressBar: true
    });
    
    toast.fire({
        icon: 'info',
        title: 'ยกเลิกการเลือกแล้ว'
    });
}

// Filter functions
function filterByStatus(status) {
    const url = new URL(window.location);
    url.searchParams.set('status', status);
    window.location.href = url.toString();
}

// Export warehouses
function exportWarehouses() {
    const params = new URLSearchParams(window.location.search);
    const exportUrl = `/admin/warehouses/export?${params.toString()}`;
    
    // Show loading
    Swal.fire({
        title: 'กำลังเตรียมข้อมูล',
        text: 'กรุณารอสักครู่...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    // Create temporary link for download
    const link = document.createElement('a');
    link.href = exportUrl;
    link.download = `warehouses_${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // Close loading
    setTimeout(() => {
        Swal.close();
        
        const toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000
        });
        
        toast.fire({
            icon: 'success',
            title: 'ส่งออกข้อมูลสำเร็จ!'
        });
    }, 1000);
}

// Bulk actions
function bulkAction(action) {
    const selectedIds = Array.from(document.querySelectorAll('.warehouse-checkbox:checked')).map(cb => cb.value);
    
    if (selectedIds.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'ยังไม่ได้เลือกคลัง',
            text: 'กรุณาเลือกคลังอย่างน้อย 1 แห่ง',
            confirmButtonColor: '#FF6B35'
        });
        return;
    }

    const actionConfig = {
        activate: {
            title: 'เปิดใช้งานคลัง',
            text: `คุณต้องการเปิดใช้งานคลัง ${selectedIds.length} แห่งที่เลือกหรือไม่?`,
            icon: 'question',
            confirmButtonText: 'เปิดใช้งาน',
            color: '#22C55E'
        },
        deactivate: {
            title: 'ปิดใช้งานคลัง',
            text: `คุณต้องการปิดใช้งานคลัง ${selectedIds.length} แห่งที่เลือกหรือไม่?`,
            icon: 'warning',
            confirmButtonText: 'ปิดใช้งาน',
            color: '#F59E0B'
        }
    };
    
    const config = actionConfig[action];
    
    Swal.fire({
        title: config.title,
        text: config.text,
        icon: config.icon,
        showCancelButton: true,
        confirmButtonColor: config.color,
        cancelButtonColor: '#6B7280',
        confirmButtonText: config.confirmButtonText,
        cancelButtonText: 'ยกเลิก',
        showLoaderOnConfirm: true,
        preConfirm: () => {
            return fetch(`/admin/warehouses/bulk`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify({
                    action: action,
                    warehouse_ids: selectedIds
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (!data.success) {
                    throw new Error(data.message || 'เกิดข้อผิดพลาด');
                }
                return data;
            })
            .catch(error => {
                Swal.showValidationMessage(`เกิดข้อผิดพลาด: ${error.message}`);
            });
        },
        allowOutsideClick: () => !Swal.isLoading()
    }).then((result) => {
        if (result.isConfirmed && result.value) {
            Swal.fire({
                icon: 'success',
                title: 'สำเร็จ!',
                text: result.value.message,
                confirmButtonColor: '#FF6B35'
            }).then(() => {
                location.reload();
            });
        }
    });
}

// Individual warehouse actions
function toggleWarehouseStatus(warehouseId) {
    Swal.fire({
        title: 'ยืนยันการเปลี่ยนสถานะ',
        text: 'คุณต้องการเปลี่ยนสถานะการใช้งานของคลังนี้หรือไม่?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#FF6B35',
        cancelButtonColor: '#6B7280',
        confirmButtonText: 'ยืนยัน',
        cancelButtonText: 'ยกเลิก',
        showLoaderOnConfirm: true,
        preConfirm: () => {
            return fetch(`/admin/warehouses/${warehouseId}/toggle`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    throw new Error(data.message || 'เกิดข้อผิดพลาด');
                }
                return data;
            })
            .catch(error => {
                Swal.showValidationMessage(`เกิดข้อผิดพลาด: ${error.message}`);
            });
        }
    }).then((result) => {
        if (result.isConfirmed && result.value) {
            Swal.fire({
                icon: 'success',
                title: 'สำเร็จ!',
                text: result.value.message,
                confirmButtonColor: '#FF6B35'
            }).then(() => {
                location.reload();
            });
        }
    });
}

function deleteWarehouse(warehouseId) {
    Swal.fire({
        title: 'ยืนยันการลบคลัง',
        text: 'คุณต้องการลบคลังนี้หรือไม่? การดำเนินการนี้ไม่สามารถยกเลิกได้',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#EF4444',
        cancelButtonColor: '#6B7280',
        confirmButtonText: 'ลบคลัง',
        cancelButtonText: 'ยกเลิก',
        showLoaderOnConfirm: true,
        preConfirm: () => {
            return fetch(`/admin/warehouses/${warehouseId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    throw new Error(data.message || 'เกิดข้อผิดพลาด');
                }
                return data;
            })
            .catch(error => {
                Swal.showValidationMessage(`เกิดข้อผิดพลาด: ${error.message}`);
            });
        }
    }).then((result) => {
        if (result.isConfirmed && result.value) {
            Swal.fire({
                icon: 'success',
                title: 'ลบคลังสำเร็จ!',
                text: result.value.message,
                confirmButtonColor: '#FF6B35'
            }).then(() => {
                location.reload();
            });
        }
    });
}

// Show success/error messages from session
@if(session('success'))
    document.addEventListener('DOMContentLoaded', function() {
        const toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 4000,
            timerProgressBar: true
        });
        
        toast.fire({
            icon: 'success',
            title: '{{ session('success') }}'
        });
    });
@endif

@if(session('error'))
    document.addEventListener('DOMContentLoaded', function() {
        Swal.fire({
            icon: 'error',
            title: 'เกิดข้อผิดพลาด!',
            text: '{{ session('error') }}',
            confirmButtonColor: '#FF6B35'
        });
    });
@endif

// Enhanced search functionality
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.querySelector('input[name="search"]');
    let searchTimeout;
    
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            
            // Add visual feedback
            this.style.borderColor = '#FF6B35';
            
            searchTimeout = setTimeout(() => {
                this.style.borderColor = '';
            }, 1000);
        });
    }
    
    // Auto-submit form on select changes
    document.querySelectorAll('select[name="status"], select[name="type"]').forEach(select => {
        select.addEventListener('change', function() {
            this.closest('form').submit();
        });
    });
});

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + A to select all
    if ((e.ctrlKey || e.metaKey) && e.key === 'a' && !e.target.matches('input, textarea')) {
        e.preventDefault();
        const selectAll = document.getElementById('selectAll');
        if (selectAll) {
            selectAll.checked = true;
            selectAll.dispatchEvent(new Event('change'));
        }
    }
    
    // Escape to clear selection
    if (e.key === 'Escape') {
        clearSelection();
    }
    
    // Delete key for bulk delete (when items are selected)
    if (e.key === 'Delete') {
        const selectedIds = Array.from(document.querySelectorAll('.warehouse-checkbox:checked')).map(cb => cb.value);
        if (selectedIds.length > 0) {
            e.preventDefault();
            bulkAction('deactivate');
        }
    }
});
</script>

@endsection