const unavailableClass = "purchased";
const actionEnabledClass = "enabled";
const actionInProgressClass = "inprogress";
var chosenPurchase = null;
var localizedBuyNowLabel;
var localizedStartTrialLabel;
var accessibilityText = null;

function setupLocalizedText(localizedText) {
    function updateLocalizedLabel(labelId) {
        const value = localizedText[labelId];
        if (value) {
            document.getElementById(labelId).innerText = value;
        }
    }

    updateLocalizedLabel("loadingBlock");
    updateLocalizedLabel("localizedPageTitle");
    updateLocalizedLabel("localizedUpgradePricingHeader");
    updateLocalizedLabel("localizedUpgradePricingExplanation");
    updateLocalizedLabel("localizedVerifyDiscountExplanation");
    updateLocalizedLabel("localizedCheckForDiscount");
    updateLocalizedLabel("localizedStandardLearnMore");
    updateLocalizedLabel("localizedProLearnMore");
    updateLocalizedLabel("localizedVerifyLearnMore");
    updateLocalizedLabel("localizedVerifyPreviousApp");
    updateLocalizedLabel("restorePurchaseAction");
    localizedBuyNowLabel = localizedText["buyNowAction"];
    localizedStartTrialLabel = localizedText["startTrialAction"];
    updateBuyNowActionLabel();

    document.getElementById("padding").style.visibility = "inherit";
    document.getElementById("bottomRow").style.visibility = "inherit";
}

function setupAccessibilityText(text) {
    accessibilityText = text;
}

function showProducts(products) {
    function updateLabel(labelId, value) {
        document.getElementById(labelId).innerText = value;
    }

    function updateTrialDetails(targetPurchase, details) {
        const trialBlock = document.getElementById(targetPurchase + "Block")
        trialBlock.className = details.isAvailable ? null : unavailableClass;
        trialBlock.setAttribute("aria-labelledby", targetPurchase + "Label");
        trialBlock.setAttribute("aria-describedby", targetPurchase + "Description");
        
        updateLabel(targetPurchase + "Label", details.title);
        updateLabel(targetPurchase + "Description", details.description);
        updateLabel(targetPurchase + "Message", products.trialMessage);
    }

    function updatePrice(listPriceLabelId, listPriceValue, priceLabelId, priceValue) {
        updateLabel(listPriceLabelId, listPriceValue);
        updateLabel(priceLabelId, priceValue);
        const listPriceDisplay = (listPriceValue != priceValue) ? "block" : "none";
        document.getElementById(listPriceLabelId).style.display = listPriceDisplay;
    }

    function updatePurchaseDetails(targetPurchase, details) {
        const targetBlock = document.getElementById(targetPurchase + "Block")
        targetBlock.className = details.isAvailable ? null : unavailableClass;
        targetBlock.setAttribute("aria-labelledby", targetPurchase + "Label");
        targetBlock.setAttribute("aria-describedby", targetPurchase + "Description");

        updateLabel(targetPurchase + "Label", details.title);
        updateLabel(targetPurchase + "Description", details.description);
        const price = details.price;
        const listPrice = details.listPrice;
        updatePrice(
            targetPurchase + "ListPrice", listPrice,
            targetPurchase + "ActualPrice", price
        );
    }

    updateTrialDetails("trial", products.trial);
    updatePurchaseDetails("standard", products.standard);
    updatePurchaseDetails("pro", products.pro);

    updateLabel("discountExplanation", products.discountExplanation);
    document.getElementById("getDiscountBlock").style.display = !products.discountExplanation ? "block" : "none";
    document.getElementById("verifyDiscountBlock").style.display = "none";
    document.getElementById("gotDiscountBlock").style.display = products.discountExplanation ? "block" : "none";
    document.getElementById("productsBlock").style.display = "block";
    document.getElementById("discountBlock").style.display = products.pro.isAvailable ? "block" : "none";

    // If we've successfully loaded everything, get rid of our loading block and enable our actions

    document.getElementById("loadingBlock").style.display = "none";

    chosenPurchase = null;
    enableAction("buyNowAction", false);
    enableAction("restorePurchaseAction", true);
}

function updateBuyNowActionLabel() {
    const localizedLabel = chosenPurchase == "trial" ? localizedStartTrialLabel : localizedBuyNowLabel;
    document.getElementById("buyNowAction").innerText = localizedLabel;
    
    var localizedAccessibilityLabel = localizedLabel;
    if (accessibilityText != null && chosenPurchase != null) {
        localizedAccessibilityLabel = accessibilityText.buyNowActionLabels[chosenPurchase];
    }
    document.getElementById("buyNowAction").setAttribute("aria-label", localizedAccessibilityLabel);
}

function updateActionState(actionName, state) {
    document.getElementById(actionName).className = state;
    document.getElementById(actionName).setAttribute("aria-disabled", (state == null));
}

function enableAction(actionName, shouldEnable) {
    updateActionState(actionName, shouldEnable ? actionEnabledClass : null);
}

function triggeredAction(actionName) {
    enableAction("restorePurchaseAction", false);
    enableAction("buyNowAction", false);
    updateActionState(actionName, actionInProgressClass);

    for (var block of ["trial", "standard", "pro"]) {
        if (block != chosenPurchase) {
            const blockId = block + "Block";
            document.getElementById(blockId).className = unavailableClass;
        }
    }
}

function choosePurchase(targetPurchase) {
    const targetPurchaseClassName = document.getElementById(targetPurchase + "Block").className;
    if (targetPurchaseClassName == unavailableClass) {
        targetPurchase = null; // Can't choose something that's unavailable
    }

    if (chosenPurchase != targetPurchase) {
        chosenPurchase = targetPurchase
    } else {
        chosenPurchase = null
    }

    for (var block of ["trial", "standard", "pro"]) {
        const blockId = block + "Block";
        const currentClass = document.getElementById(blockId).className;
        if (currentClass != unavailableClass) {
            // Can't unpurchase something that's unavailable
            const blockClass = (block == chosenPurchase) ? "buythis" : null;
            const blockElement = document.getElementById(blockId);
            blockElement.className = blockClass;
            blockElement.setAttribute("aria-pressed", (blockClass == "buythis"));
        }
    }

    updateBuyNowActionLabel();
    enableAction("buyNowAction", chosenPurchase != null);
}

function chooseTrial() {
    choosePurchase("trial");
}

function chooseStandard() {
    choosePurchase("standard");
}

function choosePro() {
    choosePurchase("pro");
}

function restorePurchaseAction() {
    chosenPurchase = null;
    triggeredAction("restorePurchaseAction");
    callback("restorePurchases");
}

function buyNowAction() {
    if (chosenPurchase != null) {
        triggeredAction("buyNowAction");
        callback("buy:" + chosenPurchase);
    }
}

function standardLearnMoreAction() {
    callback("learnMore:standard")
    return false
}

function proLearnMoreAction() {
    callback("learnMore:pro")
    return false
}

function verifyLearnMoreAction() {
    callback("learnMore:verifyPreviousApp")
    return false
}

function startDiscountValidationAction() {
    document.getElementById("getDiscountBlock").style.display = "none";
    document.getElementById("verifyDiscountBlock").style.display = "block";
    return false
}

function checkForDiscountAction() {
    callback("verifyEligibility");
    return false
}

function callback(parameter) {
    if (typeof hero == 'string') {
        // iOS
        window.location = "callback:" + parameter;
    } else if (typeof hero !== 'undefined') {
        // macOS
        hero.callback = parameter;
    } else {
        // Testing in Safari
        console.log("hero.callback(\"" + parameter + "\")");
    }
}

function setupWindow() {
    if (typeof hero == 'string') {
        // iOS
    } else if (typeof hero !== 'undefined') {
        // macOS
        hero.width = 665;
        hero.height = 665;
    } else {
        // Uncomment for testing in Safari. This case gets hit when the IAP window first shows (and is in an uninitialized state) in the iOS apps. In that case, we do eventually get everything up to speed and all the proper data displays, so we should just do nothing in this case. But, if you want to test the IAP window in Safari, you need this case to execute and fill the UI with the default behavior below.
//        document.getElementById('appStyleSheetLink').href = "AppStyleSheet.css";
//        setupLocalizedText({"localizedStandardLearnMore":"Learn More","localizedUpgradePricingExplanation":"If you've purchased an earlier version of OmniOutliner from the Mac App Store, you may be eligible for a discount.","localizedVerifyDiscountExplanation":"To verify discount eligibility, OmniOutliner needs you to tell it where your copy of OmniOutliner 4 is installed. (If it is not currently installed, you'll need to download it again from the App Store's purchased apps.)","localizedPageTitle":"Déverrouiller OmniOutliner","restorePurchaseAction":"Restore Purchase","startTrialAction":"Start Trial","localizedUpgradePricingHeader":"Upgrade Pricing","localizedCheckForDiscount":"Check for Discount","localizedProLearnMore":"Learn More","localizedVerifyLearnMore":"Learn More","localizedVerifyPreviousApp":"Verify Previous App","loadingBlock":"Contacting the App Store…","buyNowAction":"Buy Now"});
//        showProducts({"standard":{"listPrice":"$9.99","purchaseDate":"","sku":"MASOO5_IAP1_STD_DISCOUNT","price":"$4.99","title":"Upgrade to v5 Essentials","isAvailable":1,"description":"OmniOutliner Essentials is a svelte, focused, and extremely affordable outlining app. (This discounted price is available because you've purchased an earlier version of OmniOutliner from the Mac App Store.)"},"trial":{"listPrice":"$0.00","purchaseDate":"","sku":"MASOO5_IAP1_TRIAL","price":"$0.00","title":"Free Trial","isAvailable":1,"description":"With the free two week trial, you can try all of the features of Standard and Pro without buying anything. After the trial, you can continue to use OmniOutliner to view documents for free."},"discountExplanation":"Thank you for being a loyal customer. Enjoy your upgrade discount!","pro":{"listPrice":"$59.99","purchaseDate":"","sku":"MASOO5_IAP1_PRO_DISCOUNT","price":"$29.99","title":"Upgrade to v5 Pro","isAvailable":1,"description":"Whenever you're ready for more power, unlock the Pro edition of OmniOutliner. (This discounted price is available because you've purchased an earlier version of OmniOutliner from the Mac App Store.)"},"trialMessage":"$0.00"})
//        showProducts({"standard":{"listPrice":"$9.99","purchaseDate":"","sku":"MASOO5_IAP1_STD","price":"$9.99","title":"Unlock Essentials","isAvailable":1,"description":"OmniOutliner Essentials is a svelte, focused, and extremely affordable outlining app. <THIS IS A TEST>"},"trial":{"listPrice":"$0.00","purchaseDate":"","sku":"MASOO5_IAP1_TRIAL","price":"$0.00","title":"Free Trial","isAvailable":1,"description":"With the free two week trial, you can try all of the features of Essentials and Pro without buying anything. After the trial, you can continue to use OmniOutliner to view documents for free. <THIS IS A TEST>"},"pro":{"listPrice":"$59.99","purchaseDate":"","sku":"MASOO5_IAP1_PRO","price":"$59.99","title":"Unlock Pro","isAvailable":1,"description":"Whenever you're ready for more power, unlock the Pro edition of OmniOutliner. (If you're not sure, no pressure: you can upgrade at any time.) <THIS IS A TEST>"},"trialMessage":"$0.00"})
    }
}
