"use strict";

// worldScripts.WitchBank

this.name = "WitchBank";

    this.playerWillSaveGame = function () {
        if (this.WitchBank_transactionLog) {
            missionVariables.WitchBank_transactionLog = JSON.stringify(this.WitchBank_transactionLog);
        } else {
            delete missionVariables.WitchBank_transactionLog;
        }
    };

this._firstRun = function () {
    if (player.ship.awardEquipment("EQ_WB_WALLET")) {             // Dummy equipment to represent wallet
        missionVariables.WitchBank_cashAtBank = 0;                // Default starting value
        missionVariables.WitchBank_cashInWallet = player.credits; // Initial wallet balance equals total credits
    } else {
        log(this.name, "Error: EQ_WB_WALLET could not be awarded to player ship.");
    }
};

this.startUp = function () {
    if (!missionVariables.WitchBank_cashAtBank || 
        !missionVariables.WitchBank_cashInWallet) {
        this._firstRun();
    }
    // Initialize transaction log
    this.WitchBank_transactionLog = JSON.parse(missionVariables.WitchBank_transactionLog) || [];
    delete this.startUp;
};

/* ====================================================================================
        equipmentDamaged & equipmentRepaired for EQ_WB_WALLET
======================================================================================= */

// The equipmentDamaged handler is called when equipment gets damaged.
this.equipmentDamaged = function (equipment) {
    if (equipment === "EQ_WB_WALLET") {
        player.credits = missionVariables.WitchBank_cashAtBank;
        missionVariables.WitchBank_trappedInDamagedWallet = missionVariables.WitchBank_cashInWallet;
        missionVariables.WitchBank_cashInWallet = 0;
        player.consoleMessage("Your wallet has been damaged. " + missionVariables.WitchBank_trappedInDamagedWallet + " credits are inaccessible.", 6);
        log(this.name, "Wallet damaged. Trapped credits: " + missionVariables.WitchBank_trappedInDamagedWallet);
    }
};

// The equipmentRepaired handler is called when equipment gets repaired.
this.equipmentRepaired = function (equipment) {
    if (equipment === "EQ_WB_WALLET") {
        if (missionVariables.WitchBank_trappedInDamagedWallet > 0) {
            missionVariables.WitchBank_cashInWallet = missionVariables.WitchBank_trappedInDamagedWallet;
            player.credits = missionVariables.WitchBank_cashAtBank + missionVariables.WitchBank_cashInWallet;
            player.consoleMessage("Your wallet has been repaired. " + missionVariables.WitchBank_cashInWallet + " credits are restored.", 6);
            missionVariables.WitchBank_trappedInDamagedWallet = 0;
            log(this.name, "Wallet repaired. Restored credits: " + missionVariables.WitchBank_cashInWallet);
        } else {
            player.consoleMessage("No trapped credits to restore.", 6);
        }
    }
};

/* ====================================================================================
            SETTING THE STATION INTERFACE
======================================================================================= */

this.startUpComplete = function () {
    if (player.ship.docked) {
        this._applyInterface(player.ship.dockedStation);
    }
    delete this.startUpComplete;
};

this.shipDockedWithStation = function (station) {
    this._applyInterface(station);
};

this._applyInterface = function (station) {
    if (station.isMainStation) {
        station.setInterface("witch_bank", {
            title: "Witch Bank",
            category: expandDescription("[interfaces-category-organisations]"),
            summary: "Witch Bank is the trusted name in interstellar banking. Current balance: " + missionVariables.WitchBank_cashAtBank + " credits.",
            callback: this._showBankingScreen.bind(this)
        });
    }
};

/* ====================================================================================
            SHOW BANKING SCREEN
======================================================================================= */

this._pendingTransaction = null; // "deposit", "auto_deposit" or "withdrawal" - anything else is ignored

this._showBankingScreen = function (caller, to) {
    // If _pendingTransaction is set, process the caller as an amount
    if (this._pendingTransaction) {
        // Check if caller is a positive integer
        var amount = parseInt(caller, 10);
        if (!isNaN(amount) && amount > 0) {
            // Process the transaction
            this._performTransaction(this._pendingTransaction, amount);

            // Reset the pending transaction flag
            this._pendingTransaction = null;

            // Update text on interfaces screen with new balance
            this._applyInterface(player.ship.dockedStation);
        } else {
            player.consoleMessage("Invalid amount entered.", 6);
            this._pendingTransaction = null; // Reset on invalid input
        }
    }

    // Compose the default starting screen message
    var message = "Welcome to Witch Bank, the trusted name in interstellar banking. Your current balances are: " +
                  missionVariables.WitchBank_cashAtBank + " credits in bank, " +
                  missionVariables.WitchBank_cashInWallet + " credits in wallet.\n\n" +
                  "Recent Transactions:\n" +
                  this._getTransactionLog();

    var optionsMenu = {
        "1_DEPOSIT": "Make a DEPOSIT",
        "2_WITHDRAWAL": "Make a WITHDRAWAL",
        "3_AUTOBANK": "AUTOBANK service",
        "4_blank": "",
        "9_EXIT": "EXIT secure banking"
    };

    var parameters = {
        screenID: "BANKING_SCREEN",
        allowInterrupt: true,
        exitScreen: "GUI_SCREEN_INTERFACES",
        background: { name: "witch_bank_background.png", height: 480 },
        title: "Witch Bank",
        message: message,
        choices: optionsMenu
    };

    if (to) {
        parameters.exitScreen = to;
    }

    // Adjust parameters for deposit/withdrawal screens
    switch (caller) {
        case "deposit":
            this._pendingTransaction = "deposit";
            parameters.music = "dt_anticipating_deposit.ogg";
            parameters.title = "Wallet to Witch Bank";
            parameters.message = "Enter the amount you wish to deposit:";
            parameters.textEntry = true; // Replaces "choices" menu with a text entry field
            break;

        case "withdrawal":
            this._pendingTransaction = "withdrawal";
            parameters.music = "dt_anticipating_withdrawal.ogg";
            parameters.title = "Witch Bank to Wallet";
            parameters.message = "Enter the amount you wish to withdraw:";
            parameters.textEntry = true; // Replaces "choices" menu with a text entry field
            break;

        case "autobank":
            parameters.music = "dt_automatic_banking.ogg";
            parameters.background = { name: "witch_bank_profit_background.png", height: 480 };
            parameters.title = "Automatic Banking Service";
            parameters.message = "AutoBank is a convenient service that automatically deposits your trading profits into your bank account, ensuring your earnings are safely stored and ready to earn interest. By enabling AutoBank, you’ll no longer need to manually transfer credits after each trade—simply focus on maximizing your profits, and let us handle the rest. This service is perfect for traders who want to streamline their operations while taking full advantage of our interest-bearing accounts. Enable AutoBank today and experience hassle-free financial management!";
            parameters.choices = {
                "1_DEPOSIT": "Make a DEPOSIT",
                "2_WITHDRAWAL": "Make a WITHDRAWAL",
                "3_AUTOBANK_TOGGLE": "Toggle AUTOBANK on or off",
                "4_blank": "",
                "9_EXIT": "EXIT secure banking"
            };
            break;

        default:
            // No changes to the starting screen
            break;
    }

    // Run the banking screen
    mission.runScreen(parameters, this._handleBankingChoice.bind(this));
};

/* ====================================================================================
            HANDLE BANKING CHOICE
======================================================================================= */

this._handleBankingChoice = function (choice) {
    switch (choice) {
        case "9_EXIT":
            return; // Exit the banking screen

        case "1_DEPOSIT":
            this._showBankingScreen("deposit");
            break;

        case "2_WITHDRAWAL":
            this._showBankingScreen("withdrawal");
            break;

        case "3_AUTOBANK_TOGGLE":
            this._toggleAutoBankProfits();
            // no break
        case "3_AUTOBANK":
            this._showBankingScreen("autobank");
            break;

        default:
            // Redisplay the banking screen
            this._showBankingScreen(choice);
            break;
    }
};

/* ====================================================================================
            PERFORM TRANSACTION
======================================================================================= */

this._performTransaction = function (transactionType, amount) {
    var transaction = "";
    switch (transactionType) {
        case "auto_deposit":
        case "deposit":
            // Transfer credits from wallet to bank
            if (amount > 0 && amount <= missionVariables.WitchBank_cashInWallet) {
                missionVariables.WitchBank_cashAtBank += amount;
                missionVariables.WitchBank_cashInWallet -= amount;
                player.consoleMessage("Deposited " + amount + " credits.", 6);
                log(this.name, "Deposited " + amount + " credits. New balances: Bank=" +
                    missionVariables.WitchBank_cashAtBank + ", Wallet=" +
                    missionVariables.WitchBank_cashInWallet);

                // Log the transaction
                if (transactionType === "deposit") {
                    transaction = "Deposited " + amount + " credits.";
                } else {
                    transaction = "Autobanked " + amount + " credits.";
                }
            } else {
                player.consoleMessage("Invalid deposit amount.", 6);
            }
            break;

        case "withdrawal":
            // Transfer credits from bank to wallet
            if (amount > 0 && amount <= missionVariables.WitchBank_cashAtBank) {
                missionVariables.WitchBank_cashAtBank -= amount;
                missionVariables.WitchBank_cashInWallet += amount;
                player.consoleMessage("Withdrew " + amount + " credits.", 6);
                log(this.name, "Withdrew " + amount + " credits. New balances: Bank=" +
                    missionVariables.WitchBank_cashAtBank + ", Wallet=" +
                    missionVariables.WitchBank_cashInWallet);

                // Log the transaction
                transaction = "Withdrew " + amount + " credits.";
            } else {
                player.consoleMessage("Invalid withdrawal amount.", 6);
            }
            break;

        default:
            player.consoleMessage("Invalid banking operation.", 6);
            break;
    }

    // Add the transaction to the log
    if (transaction) {
        this._logTransaction(transaction);
    }
};

/* ====================================================================================
            TRANSACTION LOGGING FUNCTIONS
======================================================================================= */

this._logTransaction = function (transaction) {
    // Add the transaction to the log
    var timestamp = clock.days + " days, " + clock.seconds + " seconds";
    this.WitchBank_transactionLog.unshift(timestamp + ": " + transaction);

    // Limit the log to the last 10 transactions
    if (this.WitchBank_transactionLog.length > 10) {
        this.WitchBank_transactionLog.pop();
    }
};

this._getTransactionLog = function () {
    if (this.WitchBank_transactionLog.length === 0) {
        return "No recent transactions.";
    }

    // Join the log entries into a single string
    return this.WitchBank_transactionLog.join("\n");
};

/* ====================================================================================
            FUNCTIONS TO AUTO-BANK PROFITS FROM TRADING
======================================================================================= */

this._toggleAutoBankProfits = function () {
    this._autoBankProfits = !this._autoBankProfits;
    player.consoleMessage("Auto-banking of profits is now " + (this._autoBankProfits ? "enabled" : "disabled") + ".", 6);
};

/* Only customers using auto-bank earn interest.
   Will need a day counter to call _applyInterest once every 30 days
   Will need to keep track of lowest _cashAtBank throughout the month.
*/

this._interestPaymentFrequency = 30; // Interest paid once every 30 days
this._daysSinceInterestPaid = 0;
this._lowestBalance = missionVariables.WitchBank_cashAtBank;

this.dayChanged = function (newday) {
    this._daysSinceInterestPaid++;
    
    // Update the lowest balance for the month
    if (missionVariables.WitchBank_cashAtBank < this._lowestBalance) {
        this._lowestBalance = Math.max(missionVariables.WitchBank_cashAtBank, 0);
    }

    // Check if interest should be applied
    if (this._autoBankProfits === true) {
        if (this._daysSinceInterestPaid >= this._interestPaymentFrequency) {
            this._applyInterest(this._lowestBalance);

            // Reset for the new month
            this._daysSinceInterestPaid = 0;
            this._lowestBalance = missionVariables.WitchBank_cashAtBank;
        }
    }
};

this._applyInterest = function (balance) {
    var interestRate = 0.01; // 1% per month
    var interest = Math.floor(balance * interestRate);
    missionVariables.WitchBank_cashAtBank += interest;

    // Notify the player
    player.consoleMessage("You earned " + interest + " credits in interest.", 6);

    // Log the transaction
    log(this.name, "Applied interest: " + interest + " credits. New balance: " +
        missionVariables.WitchBank_cashAtBank);
};

/* ====================================================================================
    The two trading screens are "GUI_SCREEN_MARKET" AND "GUI_SCREEN_MARKETINFO"
    Ignore screen changes between those two.

    When the player enters the trading screens, record player.credits .

    When the player leaves the trading screens, compare player.credits to previous recorded.

    If player.credits <= this.previousCredits (lost money trading), then do nothing

    If player.credits > this.previousCredits (made a profit trading), then send profit to bank:

    this._pendingTransaction = "auto_deposit";
    this._showBankingScreen(profit, to); // If _pendingTransaction is set, process the caller as an amount
    
======================================================================================= */

// Player has entered the market screens.
      this.guiScreenChanged = function (to, from) {
          if ( (to === "GUI_SCREEN_MARKET" &&
              from !== "GUI_SCREEN_MARKETINFO") ||
              (to === "GUI_SCREEN_MARKETINFO" &&
              from !== "GUI_SCREEN_MARKET") ) {
          


              this.previousCredits = player.credits;
          }
      };

// The playerBoughtCargo handler is called when cargo is bought at the market screens.
this.playerBoughtCargo = function (commodity, units, price) {
     // Your code here
     // price is price per unit in tenths of a credit.
}

// The playerSoldCargo handler is called when cargo is sold at the market screens.
this.playerSoldCargo = function (commodity, units, price) {
     // Your code here
     // price is price per unit in tenths of a credit.
}

// Player is leaving the market screens.
      this.guiScreenWillChange = function (to, from) {
          if ( (to !== "GUI_SCREEN_MARKET" &&
              from === "GUI_SCREEN_MARKETINFO") ||
              (to !== "GUI_SCREEN_MARKETINFO" &&
              from === "GUI_SCREEN_MARKET") ) {
              if (player.credits <= this.previousCredits) { // no profit to bank
                  delete this.previousCredits;

              } else { // made a profit trading, so send profit to bank
                  var profit = player.credits - this.previousCredits;
                  this._pendingTransaction = "auto_deposit";
                  this._showBankingScreen(profit, to);
               // this._showBankingScreen.bind(this)
              }
         }
     };





