@page "/assistant"
@attribute [Authorize]
@inject IOllamaService OllamaService
@inject ISettingsService SettingsService
@inject NavigationManager Navigation

@rendermode InteractiveServer

<PageTitle>@T("Assistent - Author Buddy", "Assistant - Author Buddy")</PageTitle>

<div class="assistant-page">
    <div class="assistant-toolbar">
        <select @bind="selectedMode">
            <option value="lektorat">@T("Lektorat", "Editing")</option>
            <option value="advocatus">@T("Advocatus Diaboli", "Advocatus Diaboli")</option>
            <option value="hookfinder">@T("Hook-Finder", "Hook finder")</option>
            <option value="eli5">@T("ELI5-Vereinfachung", "ELI5 simplification")</option>
        </select>
        <button @onclick="RunAssistant" disabled="@(() => isRunning || string.IsNullOrWhiteSpace(inputText))">@T("Ausführen", "Execute")</button>
        @if (!string.IsNullOrEmpty(outputText))
        {
            <button @onclick="SendToEditor" class="primary">@T("An Editor übermitteln", "Send to editor")</button>
        }
        <span style="flex:1;font-size:12px;color:var(--border-color);text-align:right;">@statusText</span>
        @if (isRunning)
        {
            <progress value="@progress" max="100"></progress>
        }
    </div>

    <div class="assistant-panels">
        <div class="assistant-input-panel">
            <h4>@T("Eingabetext", "Input text")</h4>
            <textarea class="assistant-textarea" @bind="inputText" placeholder="@T("Füge hier deinen Text ein...", "Paste your text here...")"></textarea>
        </div>
        <div class="assistant-output-panel">
            <h4>@T("Ergebnis", "Result")</h4>
            <div class="assistant-output">
                @if (!string.IsNullOrEmpty(outputText))
                {
                    <pre>@outputText</pre>
                }
                else if (!string.IsNullOrEmpty(errorMessage))
                {
                    <div class="assistant-error">@errorMessage</div>
                }
                else
                {
                    <span class="assistant-hint">@T("Ergebnis erscheint hier nach der Ausführung.", "Result appears here after execution.")</span>
                }
            </div>
        </div>
    </div>
</div>

@code {
    private string _language = "de";
    private string selectedMode = "lektorat";
    private string inputText = string.Empty;
    private string outputText = string.Empty;
    private string errorMessage = string.Empty;
    private string statusText = string.Empty;
    private bool isRunning;
    private double progress;

    private string T(string de, string en) => _language == "en" ? en : de;

    protected override async Task OnInitializedAsync()
    {
        _language = await SettingsService.GetLanguageAsync() ?? "de";
        statusText = T("Bereit", "Ready");

        var pending = SettingsService.PendingAssistantInput;
        if (!string.IsNullOrEmpty(pending))
        {
            inputText = pending;
            SettingsService.PendingAssistantInput = null;
        }
    }

    private async Task RunAssistant()
    {
        if (string.IsNullOrWhiteSpace(inputText)) return;

        isRunning = true;
        progress = 50;
        outputText = string.Empty;
        errorMessage = string.Empty;
        statusText = T("Verarbeite...", "Processing...");

        try
        {
            var systemPrompt = selectedMode switch
            {
                "lektorat" => await SettingsService.GetLektorSystemPromptAsync() ?? string.Empty,
                "advocatus" => await SettingsService.GetAdvocatusDiaboliPromptAsync() ?? string.Empty,
                "hookfinder" => await SettingsService.GetHookFinderPromptAsync() ?? string.Empty,
                "eli5" => await SettingsService.GetEli5PromptAsync() ?? string.Empty,
                _ => string.Empty
            };

            if (string.IsNullOrEmpty(systemPrompt))
            {
                errorMessage = T("Kein System-Prompt für diesen Modus konfiguriert. Bitte in den Einstellungen hinterlegen.", "No system prompt configured for this mode. Please configure in settings.");
                return;
            }

            var model = await SettingsService.GetStyleModelAsync() ?? "llama3.2";
            outputText = await OllamaService.Chat(model, inputText, systemPrompt);
            statusText = T("Fertig.", "Done.");
        }
        catch (Exception ex)
        {
            errorMessage = $"{T("Fehler:", "Error:")} {ex.Message}";
            statusText = T("Fehler", "Error");
        }
        finally
        {
            isRunning = false;
            progress = 0;
        }
    }

    private void SendToEditor()
    {
        SettingsService.PendingAssistantOutput = outputText;
        Navigation.NavigateTo("/editor");
    }
}
