{% extends 'shop/base.html' %}
{% load i18n static %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'shop/backoffice.css' %}">
{% endblock %}

{% block content %}
{% include 'shop/_manage_header.html' with active='manage' %}
{% include 'shop/_section_tabs.html' %}

{% include 'shop/_stockrooms.html' %}

<div class="d-flex justify-content-between align-items-center mt-4 mb-2">
    <h4 class="m-0">{% trans "Module listings" %}</h4>
</div>
{% trans "Search modules…" as list_search_placeholder %}
<div data-table data-page-size="25">
    {% include 'shop/_list_search.html' with placeholder=list_search_placeholder %}
    {% include 'shop/_module_listings.html' %}
    <nav data-table-pager class="mt-2"></nav>
</div>

{% include 'shop/_source_picker.html' %}

<div class="modal fade" id="editModuleModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" id="editModuleForm">
                {% csrf_token %}
                <div class="modal-header">
                    <h5 class="modal-title">{% trans "Edit" %} <span id="edit-module-name"></span></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans 'Close' %}"></button>
                </div>
                <div class="modal-body">
                    <label class="form-label d-block">{% trans "Price" %}</label>
                    <div class="btn-group mb-2" role="group">
                        <input type="radio" class="btn-check" name="price_mode" id="pm-fixed" value="fixed" autocomplete="off">
                        <label class="btn btn-outline-theme btn-sm" for="pm-fixed">{% trans "Fixed" %}</label>
                        <input type="radio" class="btn-check" name="price_mode" id="pm-buy" value="jita_buy_pct" autocomplete="off">
                        <label class="btn btn-outline-theme btn-sm" for="pm-buy">{% trans "% Jita Buy" %}</label>
                        <input type="radio" class="btn-check" name="price_mode" id="pm-sell" value="jita_sell_pct" autocomplete="off">
                        <label class="btn btn-outline-theme btn-sm" for="pm-sell">{% trans "% Jita Sell" %}</label>
                    </div>
                    <div id="edit-price-fixed" data-price-fixed>
                        <input type="number" min="0" name="price" id="edit-price" class="form-control" placeholder="{% trans 'ISK (0 = Ask)' %}">
                        <div class="form-text" data-price-preview></div>
                    </div>
                    <div id="edit-price-pct" data-price-pct>
                        <div class="input-group">
                            <input type="number" min="0" step="0.01" name="price_pct" id="edit-price-pct-val" class="form-control" placeholder="{% trans 'Percent, e.g. 90' %}">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                    <div class="form-text">{% trans "% Jita is thin for officer/faction mods — set a fixed price for those." %}</div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% trans "Cancel" %}</button>
                    <button type="submit" class="btn btn-primary">{% trans "Save" %}</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="editStockroomModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" id="editStockroomForm">
                {% csrf_token %}
                <div class="modal-header">
                    <h5 class="modal-title">{% trans "Edit stockroom price" %}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans 'Close' %}"></button>
                </div>
                <div class="modal-body">
                    <label class="form-label d-block">{% trans "Default price for new modules" %}</label>
                    <div class="btn-group mb-2" role="group">
                        <input type="radio" class="btn-check" name="price_mode" id="esr-pm-ask" value="fixed" autocomplete="off">
                        <label class="btn btn-outline-theme btn-sm" for="esr-pm-ask">{% trans "Ask" %}</label>
                        <input type="radio" class="btn-check" name="price_mode" id="esr-pm-buy" value="jita_buy_pct" autocomplete="off">
                        <label class="btn btn-outline-theme btn-sm" for="esr-pm-buy">{% trans "% Jita Buy" %}</label>
                        <input type="radio" class="btn-check" name="price_mode" id="esr-pm-sell" value="jita_sell_pct" autocomplete="off">
                        <label class="btn btn-outline-theme btn-sm" for="esr-pm-sell">{% trans "% Jita Sell" %}</label>
                    </div>
                    <div data-price-pct>
                        <div class="input-group">
                            <input type="number" min="0" step="0.01" name="price_pct" id="esr-price-pct-val" class="form-control" placeholder="{% trans 'Percent, e.g. 90' %}">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                    <div class="form-text">{% trans "Applies to modules added later; existing modules keep their price." %}</div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% trans "Cancel" %}</button>
                    <button type="submit" class="btn btn-primary">{% trans "Save" %}</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Mirror of shop/formatting.py:format_isk — keep in sync with the Python version.
function formatIsk(amount) {
    amount = Math.floor(amount);
    const units = [[1e12, "T"], [1e9, "B"], [1e6, "M"], [1e3, "K"]];
    for (const [unit, suffix] of units) {
        if (amount >= unit) {
            const value = (amount / unit).toFixed(2).replace(/0+$/, "").replace(/\.$/, "");
            return value + suffix + " ISK";
        }
    }
    return amount.toLocaleString("en-US") + " ISK";
}

// Show/hide the fixed vs pct price inputs based on the selected radio, toggling
// `required` to match so the browser validates only the visible field. Works for
// the Edit-module, Add-stockroom and Edit-stockroom modals (no stock fields here).
function wireModeToggles(modalEl) {
    if (!modalEl) return;
    const priceInput = modalEl.querySelector("[data-price-fixed] input[name=price]");
    const pricePreview = modalEl.querySelector("[data-price-fixed] [data-price-preview]");
    if (priceInput && pricePreview) {
        const updatePreview = function () {
            const raw = priceInput.value.trim();
            const n = parseInt(raw, 10);
            if (raw === "" || isNaN(n)) pricePreview.textContent = "";
            else if (n === 0) pricePreview.textContent = "= Ask";
            else pricePreview.textContent = "= " + formatIsk(n);
        };
        priceInput.addEventListener("input", updatePreview);
        modalEl.__updatePricePreview = updatePreview;
        updatePreview();
    }
    function sync() {
        const pm = modalEl.querySelector("input[name=price_mode]:checked");
        if (!pm) return;
        const isFixed = pm.value === "fixed";
        const fixed = modalEl.querySelector("[data-price-fixed]");
        const pct = modalEl.querySelector("[data-price-pct]");
        if (fixed) {
            fixed.style.display = isFixed ? "" : "none";
            const fi = fixed.querySelector("input");
            if (fi) fi.required = isFixed;
        }
        if (pct) {
            pct.style.display = isFixed ? "none" : "";
            const pi = pct.querySelector("input");
            if (pi) pi.required = !isFixed;
        }
    }
    modalEl.addEventListener("change", function (e) {
        if (e.target.name === "price_mode") sync();
    });
    modalEl.__syncModes = sync;
    sync();
}

(function () {
    ["editModuleModal", "addStockroomModal", "editStockroomModal"].forEach(function (id) {
        wireModeToggles(document.getElementById(id));
    });

    const modalEl = document.getElementById("editModuleModal");
    if (modalEl) {
        const form = document.getElementById("editModuleForm");
        const $ = (id) => document.getElementById(id);
        document.querySelectorAll(".edit-module-btn").forEach(function (btn) {
            btn.addEventListener("click", function () {
                const d = btn.dataset;
                form.action = d.url;
                $("edit-module-name").textContent = d.name;
                modalEl.querySelector(`input[name=price_mode][value="${d.priceMode}"]`).checked = true;
                $("edit-price").value = d.price;
                $("edit-price-pct-val").value = d.pricePct;
                if (modalEl.__updatePricePreview) modalEl.__updatePricePreview();
                modalEl.__syncModes();
                bootstrap.Modal.getOrCreateInstance(modalEl).show();
            });
        });
    }

    const srModalEl = document.getElementById("editStockroomModal");
    if (srModalEl) {
        const srForm = document.getElementById("editStockroomForm");
        document.querySelectorAll(".edit-sr-btn").forEach(function (btn) {
            btn.addEventListener("click", function () {
                const d = btn.dataset;
                srForm.action = d.url;
                srModalEl.querySelector(`input[name=price_mode][value="${d.priceMode}"]`).checked = true;
                document.getElementById("esr-price-pct-val").value = d.pricePct;
                srModalEl.__syncModes();
                bootstrap.Modal.getOrCreateInstance(srModalEl).show();
            });
        });
    }
})();
</script>
{% endblock %}

{% block extra_javascript %}
<script src="{% static 'shop/backoffice_tables.js' %}"></script>
{% endblock %}
