class ShipSystem {
    constructor(game) {
        this.game = game;
        this.ships = [];
        this.currentShip = null;
        this.initializeShips();
    }

    initializeShips() {
        // Initialize with player's current ship instead of static data
        this.ships = [];
        
        // Wait for game systems to be ready, then sync with player ship
        setTimeout(() => {
            this.syncWithPlayerShip();
        }, 100);
    }
    
    syncWithPlayerShip() {
        const player = this.game.systems.player;
        if (!player || !player.ship) {
            return;
        }
        
        if (player && player.ship) {
            // Create ship object from player's current ship
            const playerShip = {
                id: 'current_ship',
                name: player.ship.name || 'Starter Cruiser',
                class: player.ship.class || 'Cruiser',
                level: player.ship.level || 1,
                health: player.ship.health || player.ship.maxHealth || 100,
                maxHealth: player.ship.maxHealth || 100,
                attack: player.ship.attack || player.attributes.attack || 10,
                defense: player.ship.defence || player.attributes.defense || 5,
                speed: player.ship.speed || player.attributes.speed || 10,
                image: player.ship.texture || 'assets/textures/ships/starter_cruiser.png',
                status: 'active',
                experience: 0,
                requiredExp: 100,
                rarity: 'Common'
            };
            
            this.ships = [playerShip];
            this.currentShip = playerShip;
            
            // Update the display immediately
            this.updateCurrentShipDisplay();
        }
    }

    renderShips() {
        const shipGrid = document.getElementById('shipGrid');
        if (!shipGrid) return;

        shipGrid.innerHTML = '';

        this.ships.forEach(ship => {
            const shipCard = this.createShipCard(ship);
            shipGrid.appendChild(shipCard);
        });
    }

    createShipCard(ship) {
        const card = document.createElement('div');
        card.className = `ship-card ${ship.status === 'active' ? 'active' : ''}`;
        card.dataset.shipId = ship.id;

        card.innerHTML = `
            <div class="ship-card-header">
                <img src="${ship.image}" alt="${ship.name}" class="ship-card-image">
                <div class="ship-card-info">
                    <div class="ship-card-rarity ${ship.rarity.toLowerCase()}">${ship.rarity}</div>
                </div>
            </div>
            <div class="ship-card-actions">
                <button class="btn-action btn-switch" onclick="game.systems.ship.switchShip('${ship.id}')" 
                        ${ship.status === 'active' ? 'disabled' : ''}>
                    ${ship.status === 'active' ? 'ACTIVE' : 'SWITCH'}
                </button>
            </div>
        `;

        return card;
    }

    updateCurrentShipDisplay() {
        // Use player's ship data instead of this.currentShip
        const player = this.game.systems.player;
        if (!player || !player.ship) {
            return;
        }

        const elements = {
            currentShipImage: document.getElementById('currentShipImage'),
            currentShipName: document.getElementById('currentShipName'),
            currentShipClass: document.getElementById('currentShipClass'),
            currentShipLevel: document.getElementById('currentShipLevel'),
            currentShipHealth: document.getElementById('currentShipHealth'),
            currentShipAttack: document.getElementById('currentShipAttack'),
            currentShipDefense: document.getElementById('currentShipDefense'),
            currentShipSpeed: document.getElementById('currentShipSpeed')
        };

        // Use player's ship data
        const ship = player.ship;
        
        if (elements.currentShipImage) {
            // Use the ship's texture if available, otherwise fallback
            const imagePath = ship.texture || `assets/textures/ships/starter_cruiser.png`;
            elements.currentShipImage.src = imagePath;
            elements.currentShipImage.alt = ship.name;
        }
        if (elements.currentShipName) elements.currentShipName.textContent = ship.name;
        if (elements.currentShipClass) elements.currentShipClass.textContent = ship.class || 'Unknown';
        if (elements.currentShipLevel) elements.currentShipLevel.textContent = ship.level || 1;
        if (elements.currentShipHealth) elements.currentShipHealth.textContent = `${ship.health}/${ship.maxHealth}`;
        if (elements.currentShipAttack) elements.currentShipAttack.textContent = ship.attack || 0;
        if (elements.currentShipDefense) elements.currentShipDefense.textContent = ship.defence || ship.defense || 0;
        if (elements.currentShipSpeed) elements.currentShipSpeed.textContent = ship.speed || 0;
    }

    switchShip(shipId) {
        const ship = this.ships.find(s => s.id === shipId);
        if (!ship || ship.status === 'active') return;

        // Deactivate current ship
        if (this.currentShip) {
            this.currentShip.status = 'inactive';
        }

        // Activate new ship
        ship.status = 'active';
        this.currentShip = ship;

        // Update displays
        this.renderShips();
        this.updateCurrentShipDisplay();

        // Show notification
        this.game.showNotification(`Switched to ${ship.name}!`, 'success', 3000);
    }

    upgradeShip(shipId) {
        const ship = this.ships.find(s => s.id === shipId);
        if (!ship) return;

        const upgradeCost = ship.level * 1000;
        
        if (this.game.systems.economy.getCredits() < upgradeCost) {
            this.game.showNotification(`Not enough credits! Need ${upgradeCost} credits.`, 'error', 3000);
            return;
        }

        // Upgrade ship
        this.game.systems.economy.removeCredits(upgradeCost);
        ship.level++;
        ship.maxHealth += 10;
        ship.health = ship.maxHealth; // Full heal on upgrade
        ship.attack += 2;
        ship.defense += 1;
        ship.speed += 1;
        ship.requiredExp = ship.level * 100;

        // Update displays
        this.renderShips();
        this.updateCurrentShipDisplay();

        this.game.showNotification(`${ship.name} upgraded to level ${ship.level}!`, 'success', 3000);
    }

    repairShip(shipId) {
        const ship = this.ships.find(s => s.id === shipId);
        if (!ship || ship.health >= ship.maxHealth) return;

        const repairCost = Math.floor((ship.maxHealth - ship.health) * 0.5);
        
        if (this.game.systems.economy.getCredits() < repairCost) {
            this.game.showNotification(`Not enough credits! Need ${repairCost} credits.`, 'error', 3000);
            return;
        }

        // Repair ship
        this.game.systems.economy.removeCredits(repairCost);
        ship.health = ship.maxHealth;

        // Update displays
        this.renderShips();
        this.updateCurrentShipDisplay();

        this.game.showNotification(`${ship.name} fully repaired!`, 'success', 3000);
    }

    addExperience(shipId, amount) {
        const ship = this.ships.find(s => s.id === shipId);
        if (!ship) return;

        ship.experience += amount;
        
        // Check for level up
        while (ship.experience >= ship.requiredExp) {
            ship.experience -= ship.requiredExp;
            this.upgradeShip(shipId);
        }

        this.renderShips();
        if (this.currentShip && this.currentShip.id === shipId) {
            this.updateCurrentShipDisplay();
        }
    }

    getShip(shipId) {
        return this.ships.find(s => s.id === shipId);
    }

    getCurrentShip() {
        return this.currentShip;
    }

    getAllShips() {
        return this.ships;
    }
}
