/**
 * Hostiva API Client (FIXED - no redirect loops)
 */

class HostivaAPI {
    constructor(baseURL = '/hostiva/api') {
        this.baseURL = baseURL;
        this.token = localStorage.getItem('authToken');
    }

    async request(endpoint, method = 'GET', data = null) {
        const url = this.baseURL + endpoint;
        const options = {
            method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': this.token ? 'Bearer ' + this.token : ''
            }
        };

        if (data && ['POST', 'PUT', 'DELETE'].includes(method)) {
            options.body = JSON.stringify(data);
        }

        try {
            const response = await fetch(url, options);
            const result = await response.json();
            // Do NOT auto-redirect on 401 - let pages handle it themselves
            return result;
        } catch (error) {
            console.error('API Error:', error);
            return { success: false, message: 'Network error' };
        }
    }

    // ===== AUTHENTICATION =====
    async login(email, password) {
        const result = await this.request('/auth/login', 'POST', { email, password });
        if (result.success && result.token) {
            this.token = result.token;
            localStorage.setItem('authToken', result.token);
            localStorage.setItem('currentUser', JSON.stringify(result.user));
        }
        return result;
    }

    async register(name, email, password, password_confirm) {
        return this.request('/auth/register', 'POST', { name, email, password, password_confirm });
    }

    async logout() {
        const result = await this.request('/auth/logout', 'POST');
        localStorage.removeItem('authToken');
        localStorage.removeItem('currentUser');
        this.token = null;
        return result;
    }

    async verifyToken() { return this.request('/auth/verify', 'GET'); }

    // ===== BOOKINGS =====
    async getBookings(f = {}) { return this.request('/bookings?' + new URLSearchParams(f)); }
    async getBooking(id) { return this.request('/bookings/' + id); }
    async createBooking(d) { return this.request('/bookings', 'POST', d); }
    async updateBooking(id, d) { return this.request('/bookings/' + id, 'PUT', d); }
    async cancelBooking(id, reason) { return this.request('/bookings/' + id, 'DELETE', { reason }); }
    async generateGuestLink(id) { return this.request('/bookings/' + id + '/guest-link', 'POST'); }
    async getGuestBooking(token) { return this.request('/bookings/guest/' + token); }
    async checkAvailability(property_id, room_id, check_in, check_out) { return this.request('/bookings/availability', 'POST', { property_id, room_id, check_in, check_out }); }

    // ===== INVOICES =====
    async getInvoices(f = {}) { return this.request('/invoices?' + new URLSearchParams(f)); }
    async getInvoice(id) { return this.request('/invoices/' + id); }
    async generateInvoice(booking_id) { return this.request('/invoices', 'POST', { booking_id }); }
    async markInvoicePaid(id, d) { return this.request('/invoices/' + id + '/payment', 'POST', d); }

    // ===== PAYMENTS =====
    async getStripePublicKey() { return this.request('/payments/stripe-key'); }
    async createPaymentIntent(invoice_id) { return this.request('/payments/create-intent', 'POST', { invoice_id }); }

    // ===== EMAILS =====
    async sendBookingConfirmation(id) { return this.request('/emails/booking-confirmation/' + id, 'POST'); }
    async sendInvoice(id) { return this.request('/emails/invoice/' + id, 'POST'); }

    // ===== OTA =====
    async syncAirbnbBookings(id) { return this.request('/ota/sync-airbnb', 'POST', { property_id: id }); }
    async getOTAConnections(id) { return this.request('/ota/connections/' + id); }
    async connectAirbnb(id, key) { return this.request('/ota/connect-airbnb', 'POST', { property_id: id, api_key: key }); }

    // ===== HOUSEKEEPING =====
    async getDashboardStats(id) { return this.request('/dashboard/stats' + (id ? '?property_id=' + id : '')); }
    async getTasks(f = {}) { return this.request('/housekeeping?' + new URLSearchParams(f)); }
    async createTask(d) { return this.request('/housekeeping', 'POST', d); }
    async updateTaskStatus(id, status, notes) { return this.request('/housekeeping/' + id + '/status', 'PUT', { status, notes }); }

    // ===== SERVICE TICKETS =====
    async getServiceTickets(f = {}) { return this.request('/service-tickets?' + new URLSearchParams(f)); }
    async createServiceTicket(d) { return this.request('/service-tickets', 'POST', d); }
    async updateTicketStatus(id, status, notes) { return this.request('/service-tickets/' + id + '/status', 'PUT', { status, notes }); }
    async assignTicket(id, uid) { return this.request('/service-tickets/' + id + '/assign', 'POST', { user_id: uid }); }
    async rateTicket(id, rating, feedback) { return this.request('/service-tickets/' + id + '/rate', 'POST', { rating, feedback }); }
    async getTicketStats(id) { return this.request('/service-tickets/stats' + (id ? '?property_id=' + id : '')); }

    // ===== AI CONCIERGE =====
    async askConcierge(message, session_token) { return this.request('/ai-concierge', 'POST', { message, session_token }); }

    // ===== WHATSAPP =====
    async getWaSettings(property_id = 1) { return this.request('/whatsapp/settings?property_id=' + property_id); }
    async saveWaSettings(d) { return this.request('/whatsapp/settings', 'POST', d); }
    async getWaMessages(f = {}) { return this.request('/whatsapp/messages?' + new URLSearchParams(f)); }
    async sendWaMessage(d) { return this.request('/whatsapp/send', 'POST', d); }
    async getWaStats() { return this.request('/whatsapp/stats'); }
}

// Initialize
const API = new HostivaAPI();

function isAuthenticated() { return !!localStorage.getItem('authToken'); }

function getCurrentUser() {
    try { return JSON.parse(localStorage.getItem('currentUser')); }
    catch(e) { return null; }
}

async function logout() {
    await API.logout();
    window.location.href = '/hostiva/login.html';
}

function showNotification(msg, type = 'success') {
    const n = document.createElement('div');
    n.style.cssText = 'position:fixed;top:20px;right:20px;background:' + (type === 'success' ? '#1cc88a' : '#e74a3b') + ';color:white;padding:16px 24px;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,0.15);z-index:9999;font-weight:600;';
    n.textContent = msg;
    document.body.appendChild(n);
    setTimeout(() => n.remove(), 4000);
}

function formatCurrency(a) { return '$' + parseFloat(a).toFixed(2); }
function formatDate(d) { return new Date(d).toLocaleDateString('en-US', { year:'numeric', month:'short', day:'numeric' }); }
