/* public/css/style.css - Estilos personalizados */
:root {
    --primary-color: #0d6efd;
    --secondary-color: #6c757d;
    --success-color: #198754;
    --danger-color: #dc3545;
    --warning-color: #ffc107;
    --info-color: #0dcaf0;
    --dark-color: #212529;
    --light-color: #f8f9fa;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background-color: #f8f9fa;
}

/* Navigation */
.navbar-brand {
    font-weight: 700;
    font-size: 1.5rem;
}

/* Cards */
.card {
    border: none;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    transition: box-shadow 0.15s ease-in-out;
}

.card:hover {
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}

/* User type selection cards */
.user-type-card {
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid transparent;
}

.user-type-card:hover {
    border-color: var(--primary-color);
    transform: translateY(-2px);
}

.user-type-card.selected {
    border-color: var(--primary-color);
    background-color: var(--light-color);
}

/* Auction cards */
.auction-card {
    border-left: 4px solid var(--primary-color);
}

.auction-card.featured {
    border-left-color: var(--warning-color);
}

/* Bid cards */
.bid-card {
    border-left: 3px solid var(--success-color);
    margin-bottom: 1rem;
}

.bid-card.lowest-bid {
    border-left-color: var(--danger-color);
    background-color: rgba(220, 53, 69, 0.1);
}

/* Stats cards */
.stats-card {
    background: linear-gradient(135deg, var(--primary-color), #0a58ca);
    color: white;
    border-radius: 10px;
}

/* Buttons */
.btn {
    border-radius: 6px;
    font-weight: 500;
}

.btn-primary {
    background: linear-gradient(135deg, var(--primary-color), #0a58ca);
    border: none;
}

.btn-success {
    background: linear-gradient(135deg, var(--success-color), #146c43);
    border: none;
}

/* Forms */
.form-control:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
}

.form-label {
    font-weight: 600;
    color: var(--dark-color);
}

/* Tables */
.table th {
    border-top: none;
    font-weight: 600;
    color: var(--dark-color);
    background-color: var(--light-color);
}

/* Badges */
.badge {
    font-weight: 500;
}

/* Alerts */
.alert {
    border: none;
    border-radius: 8px;
}

/* Loading spinner */
.spinner-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
}

.spinner-border-custom {
    width: 3rem;
    height: 3rem;
    border-width: 0.3em;
}

/* Messages */
.message-item {
    border-left: 4px solid var(--info-color);
    background-color: white;
    border-radius: 0 8px 8px 0;
}

.message-item.unread {
    border-left-color: var(--warning-color);
    background-color: #fff3cd;
}

/* Auction status */
.auction-status {
    display: inline-flex;
    align-items: center;
}

.auction-status.active::before {
    content: '';
    width: 8px;
    height: 8px;
    background-color: var(--success-color);
    border-radius: 50%;
    margin-right: 5px;
}

.auction-status.closed::before {
    content: '';
    width: 8px;
    height: 8px;
    background-color: var(--secondary-color);
    border-radius: 50%;
    margin-right: 5px;
}

/* Price display */
.price-display {
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--success-color);
}

.price-display.lowest {
    color: var(--danger-color);
    font-size: 1.5rem;
}

/* Responsive */
@media (max-width: 768px) {
    .table-responsive {
        font-size: 0.9rem;
    }
    
    .card-body {
        padding: 1rem;
    }
    
    .btn {
        font-size: 0.9rem;
    }
}

/* Dark mode support */
@media (prefers-color-scheme: dark) {
    body {
        background-color: #1a1a1a;
        color: #ffffff;
    }
    
    .card {
        background-color: #2d2d2d;
        color: #ffffff;
    }
    
    .table {
        color: #ffffff;
    }
    
    .table th {
        background-color: #343a40;
        color: #ffffff;
    }
}

/* Animation classes */
.fade-in {
    animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

.slide-up {
    animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
    from {
        transform: translateY(20px);
        opacity: 0;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}

<script>
// public/js/app.js - JavaScript principal
class AuctionApp {
    constructor() {
        this.baseUrl = window.location.origin + '/auction-system';
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadUnreadCounts();
        this.initTooltips();
    }

    bindEvents() {
        // Form submissions
        document.addEventListener('submit', (e) => {
            if (e.target.classList.contains('ajax-form')) {
                e.preventDefault();
                this.handleAjaxForm(e.target);
            }
        });

        // Bid submission
        const bidForm = document.getElementById('bid-form');
        if (bidForm) {
            bidForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.submitBid(bidForm);
            });
        }

        // Message sending
        const messageForm = document.getElementById('message-form');
        if (messageForm) {
            messageForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.sendMessage(messageForm);
            });
        }

        // Real-time updates
        this.startRealTimeUpdates();
    }

    async handleAjaxForm(form) {
        const formData = new FormData(form);
        const url = form.action;
        const method = form.method || 'POST';

        try {
            this.showLoading();
            
            const response = await fetch(url, {
                method: method,
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });

            const result = await response.json();
            
            if (result.success) {
                this.showAlert(result.message, 'success');
                if (result.redirect) {
                    setTimeout(() => {
                        window.location.href = result.redirect;
                    }, 1000);
                }
            } else {
                this.showAlert(result.error || 'Error en la operación', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Error de conexión', 'danger');
        } finally {
            this.hideLoading();
        }
    }

    async submitBid(form) {
        const formData = new FormData(form);
        const auctionId = form.dataset.auctionId;

        try {
            this.showLoading();
            
            const response = await fetch(`${this.baseUrl}/auctions/${auctionId}/bid`, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });

            const result = await response.json();
            
            if (result.success) {
                this.showAlert('Oferta enviada correctamente', 'success');
                this.refreshBids(auctionId);
                form.reset();
            } else {
                this.showAlert(result.error, 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Error al enviar la oferta', 'danger');
        } finally {
            this.hideLoading();
        }
    }

    async sendMessage(form) {
        const formData = new FormData(form);

        try {
            const response = await fetch(`${this.baseUrl}/messages`, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });

            const result = await response.json();
            
            if (result.success) {
                this.appendMessage(result.message);
                form.reset();
            } else {
                this.showAlert(result.error, 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Error al enviar mensaje', 'danger');
        }
    }

    async refreshBids(auctionId) {
        try {
            const response = await fetch(`${this.baseUrl}/api/auctions/${auctionId}/bids`);
            const bids = await response.json();
            this.updateBidsDisplay(bids);
        } catch (error) {
            console.error('Error refreshing bids:', error);
        }
    }

    updateBidsDisplay(bids) {
        const bidsContainer = document.getElementById('bids-container');
        if (!bidsContainer) return;

        let html = '';
        bids.forEach((bid, index) => {
            const isLowest = index === 0;
            html += `
                <div class="bid-card card mb-2 ${isLowest ? 'lowest-bid' : ''}">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="price-display mb-1">€${this.formatPrice(bid.price)}</h6>
                                <p class="text-muted mb-0">
                                    ${bid.seller_anonymous ? 'Vendedor Anónimo' : bid.company_name}
                                </p>
                                ${bid.brand ? `<small class="text-info">Marca: ${bid.brand}</small>` : ''}
                            </div>
                            <div class="text-end">
                                ${isLowest ? '<span class="badge bg-danger">Mejor Oferta</span>' : ''}
                                <small class="d-block text-muted">${this.formatDate(bid.created_at)}</small>
                            </div>
                        </div>
                        ${bid.additional_info ? `<p class="mt-2 mb-0 small">${bid.additional_info}</p>` : ''}
                    </div>
                </div>
            `;
        });

        bidsContainer.innerHTML = html;
    }

    async loadUnreadCounts() {
        try {
            const response = await fetch(`${this.baseUrl}/api/messages/unread-count`);
            const data = await response.json();
            
            const badge = document.getElementById('unread-messages');
            if (badge) {
                badge.textContent = data.count;
                badge.style.display = data.count > 0 ? 'inline' : 'none';
            }
        } catch (error) {
            console.error('Error loading unread count:', error);
        }
    }

    startRealTimeUpdates() {
        // Update unread counts every 30 seconds
        setInterval(() => {
            this.loadUnreadCounts();
        }, 30000);

        // Update auction page every 60 seconds if viewing an auction
        const auctionId = document.body.dataset.auctionId;
        if (auctionId) {
            setInterval(() => {
                this.refreshBids(auctionId);
            }, 60000);
        }
    }

    initTooltips() {
        // Initialize Bootstrap tooltips
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }

    showLoading() {
        const overlay = document.createElement('div');
        overlay.className = 'spinner-overlay';
        overlay.innerHTML = `
            <div class="spinner-border spinner-border-custom text-primary" role="status">
                <span class="visually-hidden">Cargando...</span>
            </div>
        `;
        overlay.id = 'loading-overlay';
        document.body.appendChild(overlay);
    }

    hideLoading() {
        const overlay = document.getElementById('loading-overlay');
        if (overlay) {
            overlay.remove();
        }
    }

    showAlert(message, type = 'info') {
        const alertContainer = document.getElementById('alert-container') || this.createAlertContainer();
        
        const alert = document.createElement('div');
        alert.className = `alert alert-${type} alert-dismissible fade show`;
        alert.innerHTML = `
            <i class="fas fa-${this.getAlertIcon(type)} me-1"></i>${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        alertContainer.appendChild(alert);
        
        // Auto remove after 5 seconds
        setTimeout(() => {
            if (alert.parentNode) {
                alert.remove();
            }
        }, 5000);
    }

    createAlertContainer() {
        const container = document.createElement('div');
        container.id = 'alert-container';
        container.className = 'position-fixed top-0 end-0 p-3';
        container.style.zIndex = '9999';
        document.body.appendChild(container);
        return container;
    }

    getAlertIcon(type) {
        const icons = {
            'success': 'check-circle',
            'danger': 'exclamation-circle',
            'warning': 'exclamation-triangle',
            'info': 'info-circle'
        };
        return icons[type] || 'info-circle';
    }

    appendMessage(message) {
        const messagesContainer = document.getElementById('messages-container');
        if (!messagesContainer) return;

        const messageElement = document.createElement('div');
        messageElement.className = 'message-item p-3 mb-2';
        messageElement.innerHTML = `
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <strong>${message.sender_company || 'Usuario'}</strong>
                    <p class="mb-0 mt-1">${message.content}</p>
                </div>
                <small class="text-muted">${this.formatDate(message.created_at)}</small>
            </div>
        `;

        messagesContainer.appendChild(messageElement);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    formatPrice(price) {
        return parseFloat(price).toLocaleString('es-ES', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }

    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('es-ES', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    }
}

// Utility functions
function selectUserType(type) {
    document.querySelectorAll('.user-type-card').forEach(card => {
        card.classList.remove('border-primary', 'bg-light', 'selected');
    });
    
    const selectedCard = document.querySelector(`#${type}`).closest('.user-type-card');
    selectedCard.classList.add('border-primary', 'bg-light', 'selected');
    
    document.getElementById(type).checked = true;
}

function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        app.showAlert('Copiado al portapapeles', 'success');
    }).catch(() => {
        app.showAlert('Error al copiar', 'danger');
    });
}

// Initialize app when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    window.app = new AuctionApp();
});

// Export for use in other scripts
window.AuctionApp = AuctionApp;
</script>