@using BTCPayServer.Abstractions.Extensions
@using BTCPayServer.Abstractions.TagHelpers
@using Microsoft.AspNetCore.Mvc.TagHelpers
@using BTCPayServer.Abstractions.Contracts
@model BTCPayServer.Plugins.NIP05.Nip5StoreSettings
@inject IScopeProvider ScopeProvider
@{
    ViewData.SetActivePage("Nostr", "Nostr", "Nostr");
}

<form method="post">

    <div class="sticky-header-setup"></div>
    <div class="sticky-header d-sm-flex align-items-center justify-content-between">
        <h2 class="mb-0">@ViewData["Title"]</h2>
        <div class="d-flex gap-3 mt-3 mt-sm-0">
            <button name="command" type="submit" value="save" class="btn btn-primary">Submit</button>
            <button name="command" type="button" class="btn btn-primary" style="display: none" id="import">Import wth Nostr extension</button>
            @if (!string.IsNullOrEmpty(Model.Name))
            {
                <button name="command" type="submit" value="remove" class="btn btn-danger">Clear</button>
            }
        </div>
    </div>


    <partial name="_StatusMessage"/>

    <p class="alert alert-info">For Zaps, just <a class="alert-link" asp-action="EditLightningAddress" asp-controller="UILNURL" asp-route-storeId="@ScopeProvider.GetCurrentStoreId()">enable a lightning address</a>. At least one lightning address must exist to receive zaps, even when nostr enabled here. None of the nostr settings on this page are needed for zaps anymore.</p>

    <div class="row">
        <div class="col-xl-8 col-xxl-constrain">
            <div class="form-group">
                <div class="form-group pt-2">
                    <label asp-for="Name" class="form-label">Name (does not need to be same as for a lightning address)</label>
                    <div class="input-group">
                        <input asp-for="Name" class="form-control"/>
                        <span class="input-group-text">@@@Context.Request.Host.ToUriComponent()@Context.Request.PathBase</span>
                    </div>
                    <span asp-validation-for="Name" class="text-danger"></span>
                </div>
            </div>
            <div class="form-group">
                <label asp-for="PubKey" class="form-label">Nostr Public Key</label>
                <input asp-for="PubKey" class="form-control"/>
                <span asp-validation-for="PubKey" class="text-danger"></span>
                <p class="text-muted pt-2">Supports hex, npub or nprofile. Will be converted to hex once saved. If nprofile is provided, the relays will be added as well.</p>

            </div>
            <div class="form-group">
                <label asp-for="PrivateKey" class="form-label">Private key for zaps, if you want to prove you issued a receipt</label>
                <input asp-for="PrivateKey" class="form-control" type="password" value="@Model.PrivateKey"/>
                <span asp-validation-for="PrivateKey" class="text-danger"></span>
                <p class="text-muted pt-2">OPTIONALLY, provide the private key to your pubkey so that zaps are signed directly by you as proof of receipt. Otherwise receipts are signed by a random private key that you cannot prove you signed. Supports hex and nsec. Will be converted to hex once saved.</p>
            </div>
            <table class="table table-responsive col-12">
                <thead>
                <tr>
                    <th>
                        Relay
                    </th>
                    <th class="text-end">
                        Actions
                    </th>
                </tr>
                </thead>
                <tbody id="relay-list">
                @if (Model.Relays is not null)
                {
                    @for (var index = 0; index < Model.Relays.Length; index++)
                    {
                        <tr data-index="@index">
                            <td>
                                <input class="form-control" type="text" asp-for="Relays[index]">
                            </td>
                            <td class="text-end">
                                <button class="btn btn-link" type="button" data-remove>Remove</button>
                            </td>
                        </tr>
                    }
                }
                </tbody>
                <tfoot>
                <tr>
                    <td colspan="2">
                        
            <button type="button" id="add-relay" class="btn btn-link w-100">Add Relay</button>
                    </td>
                </tr>
                </tfoot>
            </table>
        </div>
    </div>

</form>
<template id="row">
    <tr data-index="-1">
        <td>
            <input type="text" class="form-control">
        </td>
        <td class="text-end">
            <button class="btn btn-link" type="button" data-remove>Remove</button>
        </td>
    </tr>
</template>

<script>
    document.addEventListener("DOMContentLoaded", ()=>{
        const importbtn = document.getElementById("import");
        importbtn.style.display = "block";
        importbtn.addEventListener("click", async ()=>{
            document.getElementById("PubKey").value = await window.nostr.getPublicKey();
            const relays = await window.nostr.getRelays();

            Object.entries(relays).forEach(entry => {
                const [key, value] = entry;

                if (!document.querySelector(`[value='${key}']`)){

                    const template = document.querySelector('#row');
                    const clone = template.content.cloneNode(true);
                    clone.querySelector("input").value = key;
                    clone.querySelector("input").setAttribute("value", key);
                    document.getElementById("relay-list").appendChild(clone);
                    setIndex();
                    setupRemoveBtn();
                }
            });
        });


    setupRemoveBtn();

    document.getElementById("add-relay").addEventListener("click", ()=>{
        const template = document.querySelector('#row');
        const clone = template.content.cloneNode(true);
        document.getElementById("relay-list").appendChild(clone);
        setIndex();
    setupRemoveBtn();

    });

    function setupRemoveBtn(){
        document.querySelectorAll("[data-remove]").forEach(value =>{
                value.removeEventListener("click",onRemoveRelay )
                 value.addEventListener("click",onRemoveRelay );

            });
    }

    function onRemoveRelay(evt){
        evt.target.parentElement.parentElement.remove();
        setIndex();

    }

    function setIndex(){
         document.querySelectorAll("[data-index]").forEach((value, key) => {
                        value.setAttribute("data-index", key);
                        value.querySelector("input").name = `Relays[${key}]`;
                    })
    }
});
</script>