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

{% block extra_css %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/css/select2.min.css"
      integrity="sha512-aD9ophpFQ61nFZP6hXYu4Q/b/USW7rpLCQLX6Bi0WJHXNO7Js/fUENpBQf/+P4NtpzNX0jSgR5zVvPOJp+W2Kg=="
      crossorigin="anonymous" referrerpolicy="no-referrer">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css"
      integrity="sha512-z/90a5SWiu4MWVelb5+ny7sAayYUfMmdXKEAbpj27PfdkamNdyI3hcjxPxkOPbrXoKIm7r9V2mElt5f1OtVhqA=="
      crossorigin="anonymous" referrerpolicy="no-referrer">
<link rel="stylesheet" href="{% static 'shop/backoffice.css' %}">
{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-3">
    <h2 class="m-0">{% blocktrans with name=shop.name %}Manage “{{ name }}”{% endblocktrans %}</h2>
    <a href="{% url 'backoffice:index' %}" class="btn btn-outline-theme">
        <i class="fa-solid fa-arrow-left fa-fw"></i> {% trans "Back" %}</a>
</div>

<div class="d-flex justify-content-between align-items-center mt-4 mb-2">
    <h4 class="m-0">{% trans "Hull stockrooms" %}</h4>
    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addStockroomModal">
        <i class="fa-solid fa-plus me-1"></i>{% trans "Add stockroom" %}
    </button>
</div>
<table class="table table-striped align-middle">
    <thead><tr>
        <th>{% trans "Character" %}</th><th>{% trans "Station" %}</th><th>{% trans "Container" %}</th><th>{% trans "Default price" %}</th><th></th>
    </tr></thead>
    <tbody>
    {% for s in hull_sources %}
        <tr>
            <td>{{ s.character.eve_character.character_name }}</td>
            <td>{{ s.location.name }}</td>
            <td>{% if s.container_name %}{{ s.container_name }}{% elif s.container_item_id %}#{{ s.container_item_id }}{% else %}<span class="text-muted">{% trans "Whole station" %}</span>{% endif %}</td>
            <td><span class="badge bg-secondary">{{ s.price_rule_display }}</span></td>
            <td class="text-end">
                <button type="button" class="btn btn-sm btn-outline-theme edit-sr-btn"
                        data-url="{% url 'backoffice:edit_stockroom' shop.pk s.pk %}"
                        data-price-mode="{{ s.price_mode }}"
                        data-price-pct="{{ s.price_pct|default_if_none:'' }}">
                    <i class="fa-solid fa-pen-to-square fa-fw"></i> {% trans "Edit" %}
                </button>
                <form method="post" action="{% url 'backoffice:remove_stockroom' shop.pk s.pk %}" class="d-inline">
                    {% csrf_token %}
                    <button class="btn btn-sm btn-outline-danger">{% trans "Remove" %}</button>
                </form>
            </td>
        </tr>
    {% empty %}
        <tr><td colspan="5" class="text-muted">{% trans "No stockrooms yet — hull stock will be 0 (build to order)." %}</td></tr>
    {% endfor %}
    </tbody>
</table>

<div class="d-flex justify-content-between align-items-center mt-4 mb-2">
    <h4 class="m-0">{% trans "Hull listings" %}</h4>
    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addHullModal">
        <i class="fa-solid fa-plus me-1"></i>{% trans "Add hull" %}
    </button>
</div>
{% include 'shop/_hull_listings.html' %}

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

<div class="modal fade" id="addHullModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" action="{% url 'backoffice:add_hull' shop.pk %}">
                {% csrf_token %}
                <div class="modal-header">
                    <h5 class="modal-title">{% trans "Add hull" %}</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">{% trans "Hull" %}</label>
                    {{ add_hull_form.eve_type }}
                    <div class="form-text">{% trans "Any ship in the game can be listed." %}</div>
                    <hr>
                    <label class="form-label d-block">{% trans "Stock" %}</label>
                    <div class="btn-group mb-2" role="group">
                        <input type="radio" class="btn-check" name="stock_mode" id="ah-sm-auto" value="auto" autocomplete="off" checked>
                        <label class="btn btn-outline-theme btn-sm" for="ah-sm-auto">{% trans "Auto" %}</label>
                        <input type="radio" class="btn-check" name="stock_mode" id="ah-sm-fixed" value="fixed" autocomplete="off">
                        <label class="btn btn-outline-theme btn-sm" for="ah-sm-fixed">{% trans "Fixed" %}</label>
                    </div>
                    <input type="number" min="0" name="stock" data-stock-input class="form-control mb-3" placeholder="{% trans 'Stock quantity' %}">

                    <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="ah-pm-fixed" value="fixed" autocomplete="off" checked>
                        <label class="btn btn-outline-theme btn-sm" for="ah-pm-fixed">{% trans "Fixed" %}</label>
                        <input type="radio" class="btn-check" name="price_mode" id="ah-pm-buy" value="jita_buy_pct" autocomplete="off">
                        <label class="btn btn-outline-theme btn-sm" for="ah-pm-buy">{% trans "% Jita Buy" %}</label>
                        <input type="radio" class="btn-check" name="price_mode" id="ah-pm-sell" value="jita_sell_pct" autocomplete="off">
                        <label class="btn btn-outline-theme btn-sm" for="ah-pm-sell">{% trans "% Jita Sell" %}</label>
                    </div>
                    <div data-price-fixed>
                        <input type="number" min="0" name="price" class="form-control" placeholder="{% trans 'ISK (0 = Ask)' %}">
                        <div class="form-text" data-price-preview></div>
                    </div>
                    <div data-price-pct>
                        <div class="input-group">
                            <input type="number" min="0" step="0.01" name="price_pct" class="form-control" placeholder="{% trans 'Percent, e.g. 90' %}">
                            <span class="input-group-text">%</span>
                        </div>
                    </div>
                    <div class="form-check mt-3">
                        <input class="form-check-input" type="checkbox" name="persist" id="ah-persist">
                        <label class="form-check-label" for="ah-persist">{% trans "Keep listed when out of stock" %}</label>
                        <div class="form-text">{% trans "If unchecked, this hull is removed automatically when its stock reaches 0." %}</div>
                    </div>
                    <div class="mt-3">
                        <label class="form-label">{% trans "Description" %}</label>
                        <textarea name="description" rows="4" class="form-control" placeholder="{% trans 'Markdown supported' %}"></textarea>
                    </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 "Add hull" %}</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="editHullModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" id="editHullForm">
                {% csrf_token %}
                <div class="modal-header">
                    <h5 class="modal-title">{% trans "Edit" %} <span id="edit-hull-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 "Stock" %}</label>
                    <div class="btn-group mb-2" role="group">
                        <input type="radio" class="btn-check" name="stock_mode" id="sm-auto" value="auto" autocomplete="off">
                        <label class="btn btn-outline-theme btn-sm" for="sm-auto">{% trans "Auto" %}</label>
                        <input type="radio" class="btn-check" name="stock_mode" id="sm-fixed" value="fixed" autocomplete="off">
                        <label class="btn btn-outline-theme btn-sm" for="sm-fixed">{% trans "Fixed" %}</label>
                    </div>
                    <input type="number" min="0" name="stock" id="edit-stock" data-stock-input class="form-control mb-3" placeholder="{% trans 'Stock quantity' %}">

                    <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-check mt-3">
                        <input class="form-check-input" type="checkbox" name="persist" id="edit-persist">
                        <label class="form-check-label" for="edit-persist">{% trans "Keep listed when out of stock" %}</label>
                        <div class="form-text">{% trans "If unchecked, this hull is removed automatically when its stock reaches 0." %}</div>
                    </div>
                    <div class="mt-3">
                        <label class="form-label">{% trans "Description" %}</label>
                        <textarea name="description" id="edit-desc" rows="4" class="form-control" placeholder="{% trans 'Markdown supported' %}"></textarea>
                    </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 hulls" %}</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 hulls added later; existing hulls 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>
// Show/hide the stock and price inputs of a hull-mode modal based on the
// selected radios. Targets are found by data-attribute so this works for the
// Edit, Add-hull and Add-stockroom modals (missing sections are skipped).
// Mirror of shop/formatting.py:format_isk — abbreviate ISK K/M/B/T, 2 decimals,
// trailing zeros stripped. 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";
}

function wireHullModeToggles(modalEl) {
    if (!modalEl) return;
    // Live "= 200M ISK" preview under the fixed-price field (0 = Ask, like the store).
    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() {
        // Show/hide each conditional field AND toggle `required` to match, so the
        // browser validates only the visible ones (a hidden required field can't be
        // focused and would block submit silently).
        const sm = modalEl.querySelector("input[name=stock_mode]:checked");
        const stockInput = modalEl.querySelector("[data-stock-input]");
        if (sm && stockInput) {
            const fixedStock = sm.value === "fixed";
            stockInput.style.display = fixedStock ? "" : "none";
            stockInput.required = fixedStock;
        }
        const pm = modalEl.querySelector("input[name=price_mode]:checked");
        if (pm) {
            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 === "stock_mode" || e.target.name === "price_mode") sync();
    });
    modalEl.__syncModes = sync;
    sync();
}

(function () {
    ["editHullModal", "addHullModal", "addStockroomModal", "editStockroomModal"].forEach(function (id) {
        wireHullModeToggles(document.getElementById(id));
    });

    const modalEl = document.getElementById("editHullModal");
    if (modalEl) {
        const form = document.getElementById("editHullForm");
        const $ = (id) => document.getElementById(id);
        document.querySelectorAll(".edit-hull-btn").forEach(function (btn) {
            btn.addEventListener("click", function () {
                const d = btn.dataset;
                form.action = d.url;
                $("edit-hull-name").textContent = d.name;
                modalEl.querySelector(`input[name=stock_mode][value="${d.stockMode}"]`).checked = true;
                $("edit-stock").value = d.stock;
                modalEl.querySelector(`input[name=price_mode][value="${d.priceMode}"]`).checked = true;
                $("edit-price").value = d.price;
                $("edit-price-pct-val").value = d.pricePct;
                $("edit-persist").checked = d.persist === "1";
                $("edit-desc").value = d.description || "";
                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="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/js/select2.min.js"
        integrity="sha512-4MvcHwcbqXKUHB6Lx3Zb5CEAVoE9u84qN+ZSMM6s7z8IeJriExrV3ND5zRze9mxNlABJ6k864P/Vl8m0Sd3DtQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
(function () {
    const modal = document.getElementById("addHullModal");
    if (!modal || !window.jQuery) return;
    jQuery(modal).on("shown.bs.modal", function () {
        const $sel = jQuery("#id_eve_type");
        if (!$sel.hasClass("select2-hidden-accessible")) {
            $sel.select2({
                theme: "bootstrap-5",
                dropdownParent: jQuery(modal),
                width: "100%",
                placeholder: "{% trans 'Search for a ship…' %}"
            });
        }
        $sel.select2("open");
    });
})();
</script>
{% endblock %}
