@model StoryIntelligenceProgressViewModel
@{
    ViewData["Title"] = "Review knowledge";
}

<section class="onboarding-shell" aria-labelledby="story-knowledge-title">
    <div class="onboarding-panel onboarding-review-panel story-review-page">
        <partial name="_StoryIntelligencePipelineHeader" model="@(new StoryIntelligencePipelineHeaderViewModel { CurrentStage = "Review Knowledge" })" />
        <div class="onboarding-copy story-review-heading">
            <p class="eyebrow">Phase 3</p>
            <p class="story-review-heading__phase">Review Story Intelligence</p>
            <p class="story-review-heading__stage">Stage 6 of 6</p>
            <h1 id="story-knowledge-title">Review Knowledge</h1>
            <p>Approve the facts, discoveries, beliefs and suspicions PlotDirector should add to the existing Knowledge Explorer.</p>
        </div>

        @if (TempData["OnboardingStoryIntelligenceError"] is string error)
        {
            <div class="alert alert-danger">@error</div>
        }
        @if (TempData["OnboardingStoryIntelligenceMessage"] is string message)
        {
            <div class="alert alert-success">@message</div>
        }

        <partial name="_StoryIntelligencePipelineSummary" model="Model.PipelineDashboard" />

        <section class="story-review-chapter-list" aria-label="Knowledge review">
            @if (Model.KnowledgeReview.Candidates.Count == 0)
            {
                <div class="story-review-note">
                    <strong>No knowledge decisions are waiting.</strong>
                    <p class="mb-0">Knowledge is already up to date, or there were no knowledge changes ready to import from the stored scene analysis.</p>
                </div>
                <div class="story-future-stage-grid">
                    @FutureStage("Review Continuity")
                    @FutureStage("Timeline Events")
                </div>
                <div class="onboarding-actions">
                    <a class="btn btn-outline-secondary" asp-action="StoryIntelligenceRelationships" asp-route-batchId="@Model.BatchID">Back to relationships</a>
                    <form asp-action="ImportStoryIntelligenceKnowledge" method="post">
                        <input type="hidden" name="BatchID" value="@Model.BatchID" />
                        <button class="btn btn-primary" type="submit">Continue</button>
                    </form>
                </div>
            }
            else
            {
                <div class="story-review-card-actions">
                    <button class="btn btn-outline-primary btn-sm" type="button" data-knowledge-bulk="create-all">Create all</button>
                    <button class="btn btn-outline-secondary btn-sm" type="button" data-knowledge-bulk="link-existing">Link existing matches</button>
                    <button class="btn btn-outline-secondary btn-sm" type="button" data-knowledge-bulk="ignore-all">Ignore all</button>
                    <button class="btn btn-outline-secondary btn-sm" type="button" data-knowledge-bulk="expand">Expand all</button>
                    <button class="btn btn-outline-secondary btn-sm" type="button" data-knowledge-bulk="collapse">Collapse all</button>
                </div>

                <form asp-action="ImportStoryIntelligenceKnowledge" method="post" data-knowledge-review-form>
                    <input type="hidden" name="BatchID" value="@Model.BatchID" />
                    <div class="story-character-card-grid">
                        @for (var i = 0; i < Model.KnowledgeReview.Candidates.Count; i++)
                        {
                            var candidate = Model.KnowledgeReview.Candidates[i];
                            <details class="story-character-card" open data-knowledge-card>
                                <summary>
                                    <span>
                                        <strong>@candidate.CharacterName</strong>
                                        <small>@candidate.KnowledgeStateName - @candidate.KnowledgeStatement</small>
                                    </span>
                                    <em>@candidate.Confidence</em>
                                </summary>

                                <input type="hidden" name="Knowledge[@i].Key" value="@candidate.Key" />

                                <div class="story-character-card__body" data-knowledge-key="@candidate.Key">
                                    <dl>
                                        <div><dt>Character</dt><dd>@candidate.CharacterName</dd></div>
                                        <div><dt>Knowledge statement</dt><dd>@candidate.KnowledgeStatement</dd></div>
                                        <div><dt>First scene</dt><dd>@Display(candidate.FirstScene)</dd></div>
                                        <div><dt>Existing match</dt><dd>@(candidate.ExistingKnowledgeLabel ?? "None")</dd></div>
                                    </dl>

                                    @if (!string.IsNullOrWhiteSpace(candidate.ExampleScene))
                                    {
                                        <div class="story-review-note">
                                            <strong>Example scene</strong>
                                            <p>@candidate.ExampleScene</p>
                                        </div>
                                    }

                                    @if (!string.IsNullOrWhiteSpace(candidate.Evidence))
                                    {
                                        <div class="story-review-note">
                                            <strong>Evidence</strong>
                                            <p>@candidate.Evidence</p>
                                        </div>
                                    }

                                    @if (candidate.IsExistingMatch)
                                    {
                                        <div class="story-review-note">
                                            <strong>Possible existing knowledge</strong>
                                            <p>This fact may already exist in PlotDirector. Choose whether to link it or create a separate knowledge record.</p>
                                        </div>
                                    }

                                    <fieldset class="story-character-actions">
                                        <legend>Decision</legend>
                                        <label>
                                            <input type="radio" name="Knowledge[@i].Action" value="@StoryIntelligenceKnowledgeImportActions.CreateNew" checked data-knowledge-action />
                                            Create new knowledge
                                        </label>
                                        <label>
                                            <input type="radio" name="Knowledge[@i].Action" value="@StoryIntelligenceKnowledgeImportActions.LinkExisting" data-knowledge-action @(candidate.IsExistingMatch ? string.Empty : "disabled") />
                                            Link existing knowledge
                                        </label>
                                        <label>
                                            <input type="radio" name="Knowledge[@i].Action" value="@StoryIntelligenceKnowledgeImportActions.Alias" data-knowledge-action />
                                            Merge with another knowledge item
                                        </label>
                                        <label>
                                            <input type="radio" name="Knowledge[@i].Action" value="@StoryIntelligenceKnowledgeImportActions.Ignore" data-knowledge-action />
                                            Ignore
                                        </label>
                                    </fieldset>

                                    <div data-knowledge-state-panel>
                                        <label class="form-label" for="knowledge-state-@i">Knowledge state</label>
                                        <select id="knowledge-state-@i" class="form-select" name="Knowledge[@i].KnowledgeStateID">
                                            @foreach (var option in Model.KnowledgeReview.KnowledgeStateOptions)
                                            {
                                                <option value="@option.Value" selected="@(option.Value == candidate.KnowledgeStateID.ToString())">@option.Text</option>
                                            }
                                        </select>
                                    </div>

                                    <div data-knowledge-alias-panel hidden>
                                        <label class="form-label" for="knowledge-alias-target-@i">Merge target</label>
                                        <select id="knowledge-alias-target-@i" class="form-select" name="Knowledge[@i].AliasTargetKey" data-knowledge-alias-target>
                                            <option value="">Choose knowledge item...</option>
                                            @foreach (var target in Model.KnowledgeReview.Candidates.Where(target => !string.Equals(target.Key, candidate.Key, StringComparison.OrdinalIgnoreCase)))
                                            {
                                                <option value="@target.Key">@target.CharacterName - @target.KnowledgeStatement@(target.IsExistingMatch ? $" -> {target.ExistingKnowledgeLabel}" : string.Empty)</option>
                                            }
                                        </select>
                                    </div>
                                </div>
                            </details>
                        }
                    </div>

                    <div class="onboarding-actions">
                        <a class="btn btn-outline-secondary" asp-action="StoryIntelligenceRelationships" asp-route-batchId="@Model.BatchID">Back to relationships</a>
                        <button class="btn btn-primary" type="submit">Create knowledge</button>
                    </div>
                </form>
            }
        </section>
    </div>
</section>

@section Scripts {
    <script>
        (() => {
            const form = document.querySelector("[data-knowledge-review-form]");
            if (!form) return;

            const cards = () => Array.from(form.querySelectorAll("[data-knowledge-card]"));
            const setAction = (card, action) => {
                const input = card.querySelector(`[data-knowledge-action][value="${action}"]`);
                if (input) {
                    input.checked = true;
                    updateCard(card);
                }
            };
            const actionFor = (card) => card.querySelector("[data-knowledge-action]:checked")?.value || "@StoryIntelligenceKnowledgeImportActions.CreateNew";
            const isCanonicalTarget = (card) => {
                const action = actionFor(card);
                return action !== "@StoryIntelligenceKnowledgeImportActions.Ignore" && action !== "@StoryIntelligenceKnowledgeImportActions.Alias";
            };
            const updateAliasTargets = () => {
                const allCards = cards();
                for (const card of allCards) {
                    const body = card.querySelector("[data-knowledge-key]");
                    const ownKey = body?.getAttribute("data-knowledge-key") || "";
                    const select = card.querySelector("[data-knowledge-alias-target]");
                    if (!select) continue;

                    const previous = select.value;
                    for (const option of Array.from(select.options)) {
                        if (!option.value) continue;
                        const targetCard = allCards.find(item => item.querySelector("[data-knowledge-key]")?.getAttribute("data-knowledge-key") === option.value);
                        option.disabled = option.value === ownKey || !targetCard || !isCanonicalTarget(targetCard);
                    }
                    if (select.selectedOptions[0]?.disabled) {
                        select.value = "";
                    } else {
                        select.value = previous;
                    }
                }
            };
            const updateCard = (card) => {
                const action = actionFor(card);
                const statePanel = card.querySelector("[data-knowledge-state-panel]");
                const aliasPanel = card.querySelector("[data-knowledge-alias-panel]");
                if (statePanel) statePanel.hidden = action === "@StoryIntelligenceKnowledgeImportActions.Ignore" || action === "@StoryIntelligenceKnowledgeImportActions.Alias";
                if (aliasPanel) aliasPanel.hidden = action !== "@StoryIntelligenceKnowledgeImportActions.Alias";
                updateAliasTargets();
            };
            document.querySelectorAll("[data-knowledge-bulk]").forEach(button => {
                button.addEventListener("click", () => {
                    const action = button.getAttribute("data-knowledge-bulk");
                    if (action === "create-all") cards().forEach(card => setAction(card, "@StoryIntelligenceKnowledgeImportActions.CreateNew"));
                    if (action === "link-existing") cards().forEach(card => {
                        if (card.querySelector(`[data-knowledge-action][value="@StoryIntelligenceKnowledgeImportActions.LinkExisting"]:not(:disabled)`)) {
                            setAction(card, "@StoryIntelligenceKnowledgeImportActions.LinkExisting");
                        }
                    });
                    if (action === "ignore-all") cards().forEach(card => setAction(card, "@StoryIntelligenceKnowledgeImportActions.Ignore"));
                    if (action === "expand") cards().forEach(card => card.open = true);
                    if (action === "collapse") cards().forEach(card => card.open = false);
                });
            });
            form.querySelectorAll("[data-knowledge-action]").forEach(input => {
                input.addEventListener("change", () => updateCard(input.closest("[data-knowledge-card]")));
            });
            cards().forEach(updateCard);
        })();
    </script>
}

@functions {
    private static string Display(string? value) => string.IsNullOrWhiteSpace(value) ? "Not detected" : value;

    private static Microsoft.AspNetCore.Html.IHtmlContent FutureStage(string label)
        => new Microsoft.AspNetCore.Html.HtmlString($"<article class=\"story-future-stage\"><strong>{System.Net.WebUtility.HtmlEncode(label)}</strong><span>Coming Soon</span></article>");
}
