{*
    KI tab — connect this shop to an LLM.

    Tailwind only (the plugin's own build, scoped to the `.tailwind` wrapper the controller adds).
    Never `bg-white`: the shop admin ships `.bg-white{background-color:#fff!important}`, which beats
    every `dark:` variant. Every surface below is stated for BOTH themes.

    The API key is never rendered — only its last four characters, which the controller supplies.
*}
<div class="mx-auto max-w-3xl py-4">

    {if $flash}
        <div class="mb-4 rounded-lg border px-4 py-3 text-sm
            {if $flash.type === 'success'}border-emerald-500/30 bg-emerald-500/10 text-emerald-800 dark:text-emerald-300
            {else}border-red-500/30 bg-red-500/10 text-red-800 dark:text-red-300{/if}">
            {$flash.text|escape}
        </div>
    {/if}

    {* ---- Setup link: only present when the merchant arrived from their assistant's link ---- *}
    {if $entryNote}
        <div class="mb-4 rounded-lg border px-4 py-3 text-sm
            {if $entryNote.type === 'note'}border-sky-500/30 bg-sky-500/10 text-sky-800 dark:text-sky-300
            {else}border-amber-500/30 bg-amber-500/10 text-amber-800 dark:text-amber-300{/if}">
            {$entryNote.text|escape}
        </div>
    {/if}

    {* ---- Status banner: the first thing the tab answers is "does this work right now?" ---- *}
    <div class="mb-6 rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800/60">
        <div class="flex flex-wrap items-start justify-between gap-3">
            <div class="flex items-start gap-3">
                <span class="mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full
                    {if $aiStatus->state === 'active'}bg-emerald-500
                    {elseif $aiStatus->state === 'degraded'}bg-amber-500
                    {elseif $aiStatus->state === 'down'}bg-red-500
                    {else}bg-gray-400{/if}"></span>
                <div>
                    <div class="font-semibold text-gray-900 dark:text-gray-100">{$aiText.label|escape}</div>

                    {if $aiStatus->state === 'none'}
                        <div class="mt-1 flex flex-wrap gap-1.5">
                            {foreach $aiText.missing as $missing}
                                <span class="inline-flex items-center rounded bg-gray-500/10 px-1.5 py-0.5
                                             text-xs font-medium text-gray-700 dark:text-gray-300">
                                    {$missing|escape}
                                </span>
                            {/foreach}
                        </div>
                    {else}
                        <div class="mt-1 text-sm text-gray-600 dark:text-gray-400">{$aiText.detail|escape}</div>
                    {/if}

                    {if $aiText.error}
                        <div class="mt-2 text-sm text-red-700 dark:text-red-300">{$aiText.error|escape}</div>
                    {/if}

                    {foreach $aiText.notices as $notice}
                        <div class="mt-1 text-sm text-amber-700 dark:text-amber-300">{$notice|escape}</div>
                    {/foreach}

                    <div class="mt-2 flex flex-wrap gap-x-4 text-xs text-gray-500 dark:text-gray-400">
                        {if $aiText.checked}<span>{$aiText.checked|escape}</span>{/if}
                        {if $aiText.spend}<span>{$aiText.spend|escape}</span>{/if}
                    </div>
                </div>
            </div>

            {if $aiStatus->state !== 'none'}
                <form method="post" action="{$formUrl}">
                    <input type="hidden" name="jtl_token" value="{$jtlToken|escape}">
                    <input type="hidden" name="tntMcpAiAction" value="test">
                    <button type="submit"
                            class="rounded-md border border-gray-300 px-3 py-1.5 text-sm font-medium text-gray-700
                                   hover:bg-gray-500/10 dark:border-gray-600 dark:text-gray-200">
                        {__('ai.status.recheck')}
                    </button>
                </form>
            {/if}
        </div>
    </div>

    <form method="post" action="{$formUrl}" autocomplete="off">
        <input type="hidden" name="jtl_token" value="{$jtlToken|escape}">

        <div class="rounded-lg border border-gray-200 bg-gray-50 p-5 dark:border-gray-700 dark:bg-gray-800/60">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-gray-100">{__('ai.heading')}</h2>
            <p class="mt-1 max-w-2xl text-sm text-gray-600 dark:text-gray-400">{__('ai.intro')}</p>

            {* ---- Gruppe 1: provider & key, always open ---- *}
            <h3 class="mt-6 text-sm font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
                {__('ai.group.provider')}
            </h3>

            <div class="mt-3">
                <label for="tntMcpAiProvider"
                       class="block text-sm font-medium text-gray-800 dark:text-gray-200">{__('ai.field.provider')}</label>
                {* `form-select`/`form-input` are required: the forms plugin is built with
                   strategy:'class', so an input without one inherits the admin's own styling and
                   renders as an invisible box. *}
                <select id="tntMcpAiProvider" name="aiProvider"
                        class="form-select mt-1 block w-full rounded-md border-gray-300 bg-gray-50 text-sm text-gray-900
                               dark:border-gray-600 dark:bg-gray-900 dark:text-gray-100">
                    {* Without this the banner says "Anbieter fehlt" while the select already shows
                       "OpenAI" — the page contradicting itself in its most common state (U30). *}
                    {if $aiConfig->provider === null}
                        <option value="" disabled selected>{__('ai.field.provider.placeholder')}</option>
                    {/if}
                    {foreach $providers as $provider}
                        <option value="{$provider.value|escape}"
                                {if $aiConfig->provider !== null && $aiConfig->provider->value === $provider.value}selected{/if}>
                            {$provider.label|escape}
                        </option>
                    {/foreach}
                </select>
                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">{__('ai.field.provider.help')}</p>
            </div>

            <div class="mt-4">
                <label for="tntMcpAiKey"
                       class="block text-sm font-medium text-gray-800 dark:text-gray-200">{__('ai.field.key')}</label>
                {* The one field a setup link exists for, so the cursor starts here when one was used. *}
                <input type="password" id="tntMcpAiKey" name="aiApiKey" autocomplete="off" spellcheck="false"
                       {if $entryNote && $entryNote.type === 'note'}autofocus{/if}
                       placeholder="{if $aiConfig->apiKeyConfigured}••••{$aiConfig->apiKeyLast4|escape}{/if}"
                       class="form-input mt-1 block w-full rounded-md border-gray-300 bg-gray-50 font-mono text-sm text-gray-900
                              dark:border-gray-600 dark:bg-gray-900 dark:text-gray-100">
                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">{$aiText.keyHelp|escape}</p>
            </div>

            <div class="mt-4">
                <label for="tntMcpAiModel"
                       class="block text-sm font-medium text-gray-800 dark:text-gray-200">{__('ai.field.model')}</label>
                <input type="text" id="tntMcpAiModel" name="aiModel" value="{$aiConfig->model|escape}"
                       list="tntMcpAiModels" spellcheck="false"
                       class="form-input mt-1 block w-full rounded-md border-gray-300 bg-gray-50 font-mono text-sm text-gray-900
                              dark:border-gray-600 dark:bg-gray-900 dark:text-gray-100">
                {if $modelHints}
                    <datalist id="tntMcpAiModels">
                        {foreach $modelHints as $hint}<option value="{$hint|escape}"></option>{/foreach}
                    </datalist>
                    {* A datalist alone is invisible until the field is focused, and the one moment
                       the merchant has no idea what to type is right after the first save, when the
                       list has just arrived and the field is still empty. Then the models are shown
                       as plain buttons that fill the field — no typing, no guessing. *}
                    {if $aiConfig->model === ''}
                        <div class="mt-2 flex flex-wrap gap-2" id="tntMcpAiModelPicks">
                            {foreach $modelHints as $hint}
                                <button type="button" data-model="{$hint|escape}"
                                        class="rounded-md border border-gray-300 px-2 py-1 font-mono text-xs
                                               text-gray-700 hover:bg-gray-100 dark:border-gray-600
                                               dark:text-gray-200 dark:hover:bg-gray-800">{$hint|escape}</button>
                            {/foreach}
                        </div>
                    {/if}
                {/if}
                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">{__('ai.field.model.help')}</p>
            </div>

            {*
                Rendered for every provider so the form is correct without JavaScript; the script at
                the bottom only hides it where the provider has its own default API root, and the
                controller ignores the value for those providers.
            *}
            <div class="mt-4" id="tntMcpAiBaseUrlRow" data-compatible="{$compatible|escape}">
                <label for="tntMcpAiBaseUrl"
                       class="block text-sm font-medium text-gray-800 dark:text-gray-200">{__('ai.field.baseurl')}</label>
                <input type="text" id="tntMcpAiBaseUrl" name="aiBaseUrl" value="{$aiConfig->baseUrl|escape}"
                       spellcheck="false"
                       class="form-input mt-1 block w-full rounded-md border-gray-300 bg-gray-50 font-mono text-sm text-gray-900
                              dark:border-gray-600 dark:bg-gray-900 dark:text-gray-100">
                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">{__('ai.field.baseurl.help')}</p>
            </div>

            {* ---- Gruppe 2: the ceilings, collapsed until one is set ---- *}
            {* The chevron matches integrations.tpl — the browser's default marker made this the
               plugin's second disclosure language, and it renders differently per browser (U33). *}
            <details class="group mt-6 rounded-md border border-gray-200 p-3 dark:border-gray-700"
                     {if $spendDay !== '' && $spendDay !== '0'}open{elseif $runsHour !== '' && $runsHour !== '0'}open{/if}>
                <summary class="flex cursor-pointer list-none items-center gap-2 text-sm font-semibold
                                uppercase tracking-wide text-gray-500 dark:text-gray-400">
                    <svg class="h-4 w-4 shrink-0 transition-transform group-open:rotate-90"
                         viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                         stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                        <path d="m9 18 6-6-6-6"></path>
                    </svg>
                    {__('ai.group.budget')}
                </summary>
                <p class="mt-2 text-xs text-gray-500 dark:text-gray-400">{__('ai.group.budget.help')}</p>

                <div class="mt-3 grid gap-4 sm:grid-cols-2">
                    <div>
                        <label for="tntMcpAiSpendDay"
                               class="block text-sm font-medium text-gray-800 dark:text-gray-200">
                            {__('ai.field.budget.daily')}
                        </label>
                        <input type="text" inputmode="decimal" id="tntMcpAiSpendDay" name="aiSpendDay"
                               value="{$spendDay|escape}"
                               class="form-input mt-1 block w-full rounded-md border-gray-300 bg-gray-50 text-sm text-gray-900
                                      dark:border-gray-600 dark:bg-gray-900 dark:text-gray-100">
                        <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">{__('ai.field.budget.daily.help')}</p>
                    </div>
                    <div>
                        <label for="tntMcpAiRunsHour"
                               class="block text-sm font-medium text-gray-800 dark:text-gray-200">
                            {__('ai.field.budget.hourly')}
                        </label>
                        <input type="text" inputmode="numeric" id="tntMcpAiRunsHour" name="aiRunsHour"
                               value="{$runsHour|escape}"
                               class="form-input mt-1 block w-full rounded-md border-gray-300 bg-gray-50 text-sm text-gray-900
                                      dark:border-gray-600 dark:bg-gray-900 dark:text-gray-100">
                        <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">{__('ai.field.budget.hourly.help')}</p>
                    </div>
                </div>
            </details>

            {* One primary action that saves AND tests — testing must not be a second, skippable click. *}
            <div class="mt-6 flex flex-wrap items-center gap-4">
                <button type="submit" name="tntMcpAiAction" value="saveTest"
                        class="rounded-md bg-sky-600 px-4 py-2 text-sm font-semibold text-gray-50 hover:bg-sky-500">
                    {__('ai.btn.save_test')}
                </button>
                <button type="submit" name="tntMcpAiAction" value="save"
                        class="text-sm text-gray-600 underline hover:text-gray-900
                               dark:text-gray-400 dark:hover:text-gray-200">
                    {__('ai.btn.save_only')}
                </button>
            </div>
        </div>
    </form>

    {if $aiConfig->apiKeyConfigured}
        <form method="post" action="{$formUrl}" class="mt-4"
              onsubmit="return confirm('{__('ai.btn.disconnect.confirm')|escape:'javascript'}');">
            <input type="hidden" name="jtl_token" value="{$jtlToken|escape}">
            <input type="hidden" name="tntMcpAiAction" value="clear">
            <button type="submit"
                    class="text-sm text-red-700 underline hover:text-red-800 dark:text-red-400 dark:hover:text-red-300">
                {__('ai.btn.disconnect')}
            </button>
        </form>
    {/if}
</div>

{literal}
<script>
    // Progressive disclosure only: the API-address field is server-rendered for every provider, so
    // a merchant with JavaScript off sees one field too many rather than a form that cannot be
    // completed. The value is ignored on save for providers that have their own default root.
    (function () {
        var select = document.getElementById('tntMcpAiProvider');
        var row = document.getElementById('tntMcpAiBaseUrlRow');
        if (!select || !row) {
            return;
        }
        var compatible = row.getAttribute('data-compatible');
        var sync = function () {
            row.style.display = select.value === compatible ? '' : 'none';
        };
        select.addEventListener('change', sync);
        sync();
    })();

    // The model buttons only fill the field — with JavaScript off they are still readable as the
    // list of model ids this key may use, which is exactly what the merchant needs to type.
    (function () {
        var picks = document.getElementById('tntMcpAiModelPicks');
        var field = document.getElementById('tntMcpAiModel');
        if (!picks || !field) {
            return;
        }
        picks.addEventListener('click', function (event) {
            var button = event.target.closest('button[data-model]');
            if (button) {
                field.value = button.getAttribute('data-model');
                field.focus();
            }
        });
    })();
</script>
{/literal}
