@model LocationEditViewModel
@{
    ViewData["Title"] = Model.LocationID == 0 ? "New Location" : "Edit Location";
    ViewData["ProjectSection"] = "Locations";
}

@if (Model.Project is not null)
{
    <nav class="breadcrumb-trail" aria-label="Breadcrumb">
        <a asp-controller="Projects" asp-action="Index">Projects</a>
        <a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
        <a asp-action="Index" asp-route-projectId="@Model.ProjectID">Locations</a>
        <span>@ViewData["Title"]</span>
    </nav>

    <partial name="_ProjectSectionNav" model="Model.Project" />
}

<div class="page-heading compact">
    <div>
        <p class="eyebrow">Location</p>
        <h1>@ViewData["Title"] <help-icon key="locations.edit" /></h1>
    </div>
</div>

<form asp-action="Save" method="post" class="edit-panel">
    <input asp-for="LocationID" type="hidden" />
    <input asp-for="ProjectID" type="hidden" />

    <div class="row g-3">
        <div class="col-md-8">
            <label asp-for="LocationName" class="form-label"></label>
            <input asp-for="LocationName" class="form-control" />
            <span asp-validation-for="LocationName" class="text-danger"></span>
        </div>
        <div class="col-12">
            <label class="form-label">Aliases</label>
            <div class="d-flex flex-wrap gap-2 mb-2" data-alias-list>
                @for (var i = 0; i < Model.Aliases.Count; i++)
                {
                    <span class="badge rounded-pill text-bg-light border d-inline-flex align-items-center gap-2">
                        <span>@Model.Aliases[i]</span>
                        <button class="btn-close btn-close-sm" type="button" aria-label="Remove @Model.Aliases[i]" data-remove-alias></button>
                        <input type="hidden" name="Aliases" value="@Model.Aliases[i]" />
                    </span>
                }
            </div>
            <div class="input-group">
                <input class="form-control" type="text" maxlength="200" placeholder="Add an alias" data-alias-input />
                <button class="btn btn-outline-secondary" type="button" data-add-alias>Add</button>
            </div>
        </div>
        <div class="col-md-4">
            <label asp-for="LocationTypeID" class="form-label">Location type <help-icon key="locations.fields.locationType" mode="inline" /></label>
            <select asp-for="LocationTypeID" asp-items="Model.LocationTypeOptions" class="form-select">
                <option value="">Not set</option>
            </select>
        </div>
        <div class="col-12">
            <label asp-for="ParentLocationID" class="form-label">Parent location <help-icon key="locations.fields.parentLocation" mode="inline" /></label>
            <select asp-for="ParentLocationID" asp-items="Model.ParentLocationOptions" class="form-select">
                <option value="">Top level</option>
            </select>
        </div>
        <div class="col-12">
            <div class="form-check">
                <input asp-for="ShowInQuickAddBar" class="form-check-input" />
                <label asp-for="ShowInQuickAddBar" class="form-check-label">Show in Quick Add Bar <help-icon key="locations.fields.quickAdd" mode="inline" /></label>
                <div class="form-text">Makes this item available as a draggable shortcut on the Timeline page.</div>
            </div>
        </div>
        <div class="col-12">
            <section class="list-section p-3">
                <h2 class="h5">Companion Detection</h2>
                <div class="form-check mb-3">
                    <input asp-for="ExcludeFromCompanionDetection" class="form-check-input" />
                    <label asp-for="ExcludeFromCompanionDetection" class="form-check-label"></label>
                    <div class="form-text">Use this for generic places that would create noisy suggestions, such as Home, Kitchen, Road or Shop.</div>
                </div>
                <label asp-for="DetectionPriority" class="form-label"></label>
                <input asp-for="DetectionPriority" class="form-control form-control-sm" type="number" min="0" max="1000" />
                <span asp-validation-for="DetectionPriority" class="text-danger"></span>
                <div class="form-text">Higher values make this location stronger evidence in future Word Companion detection. The default is 50.</div>
            </section>
        </div>
        <div class="col-12">
            <label asp-for="Description" class="form-label"></label>
            <textarea asp-for="Description" class="form-control" rows="5"></textarea>
        </div>
    </div>

    <div class="button-row mt-3">
        <button class="btn btn-primary" type="submit">Save location</button>
        <a class="btn btn-outline-secondary" asp-action="Index" asp-route-projectId="@Model.ProjectID">Cancel</a>
    </div>
</form>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
    <script>
        (() => {
            const list = document.querySelector("[data-alias-list]");
            const input = document.querySelector("[data-alias-input]");
            const add = document.querySelector("[data-add-alias]");
            if (!list || !input || !add) return;

            const aliases = () => [...list.querySelectorAll("input[name='Aliases']")].map(x => x.value.toLowerCase());
            const appendAlias = (value) => {
                const alias = value.trim();
                if (!alias || aliases().includes(alias.toLowerCase())) return;

                const chip = document.createElement("span");
                chip.className = "badge rounded-pill text-bg-light border d-inline-flex align-items-center gap-2";
                const text = document.createElement("span");
                text.textContent = alias;
                const remove = document.createElement("button");
                remove.className = "btn-close btn-close-sm";
                remove.type = "button";
                remove.setAttribute("aria-label", `Remove ${alias}`);
                remove.dataset.removeAlias = "";
                const hidden = document.createElement("input");
                hidden.type = "hidden";
                hidden.name = "Aliases";
                hidden.value = alias;
                chip.append(text, remove, hidden);
                list.append(chip);
                input.value = "";
            };

            add.addEventListener("click", () => appendAlias(input.value));
            input.addEventListener("keydown", event => {
                if (event.key === "Enter") {
                    event.preventDefault();
                    appendAlias(input.value);
                }
            });
            list.addEventListener("click", event => {
                if (event.target instanceof HTMLElement && event.target.matches("[data-remove-alias]")) {
                    event.target.closest(".badge")?.remove();
                }
            });
        })();
    </script>
}
