@extends('layouts.app')

@section('title', __('aiCore::lang.ai_settings'))

@section('content')
<section class="content-header">
    <h1><i class="fas fa-robot"></i> @lang('aiCore::lang.ai_settings')
        <small>Shared AI engine — provider, business type &amp; budget</small>
    </h1>
</section>

<section class="content">
    <div class="row">
        <div class="col-md-8">
            @component('components.widget', ['class' => 'box-primary'])
                <form method="POST" action="{{ route('aicore.settings.save') }}">
                    @csrf

                    {{-- ── Business type (the "smart" layer) ─────────────────── --}}
                    <div class="form-group">
                        <label>@lang('aiCore::lang.business_type') <span class="text-danger">*</span></label>
                        <select name="business_vertical" id="business_vertical" class="form-control">
                            @foreach($verticals as $key => $label)
                                <option value="{{ $key }}" {{ $settings->business_vertical == $key ? 'selected' : '' }}>{{ $label }}</option>
                            @endforeach
                        </select>
                        <small class="text-muted">
                            Picks a pre-tuned persona, grounding rules and suggested actions so the AI behaves
                            like a domain expert for your business out of the box. Leave the custom persona blank to use it.
                        </small>
                    </div>

                    <hr style="margin:14px 0;">

                    {{-- ── Active primary (read-only) ──────────────────────────
                         Credentials live ONLY in the AI services library below;
                         this line just shows which service backs the primary. --}}
                    <div class="row">
                        <div class="col-md-6 form-group">
                            <label>@lang('aiCore::lang.active_primary')</label>
                            <p class="form-control-static" style="margin:0;padding-top:2px;">
                                @if($defaultServiceKey && isset($presets[$defaultServiceKey]))
                                    <i class="fa fa-star" style="color:#f59e0b;"></i>
                                    <strong>{{ $presets[$defaultServiceKey]['label'] }}</strong>
                                    @if($settings->model) <small class="text-muted">— {{ $settings->model }}</small>@endif
                                @elseif($defaultConfigured)
                                    <strong>{{ $settings->provider }}</strong>
                                    @if($settings->model) <small class="text-muted">— {{ $settings->model }}</small>@endif
                                    <small class="text-muted">@lang('aiCore::lang.active_primary_manual')</small>
                                @else
                                    <span class="text-warning"><i class="fa fa-exclamation-triangle"></i> @lang('aiCore::lang.no_primary_yet')</span>
                                @endif
                            </p>
                        </div>
                        <div class="col-md-6 form-group" style="padding-top:25px;">
                            <label>
                                <input type="checkbox" name="enabled" value="1" {{ $settings->enabled ? 'checked' : '' }}>
                                @lang('aiCore::lang.enabled')
                            </label>
                            <small class="text-muted" style="display:block;">Turn AI on once configured.</small>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4 form-group">
                            <label>@lang('aiCore::lang.temperature')</label>
                            <input type="number" name="temperature" class="form-control" step="0.1" min="0" max="1"
                                   value="{{ $settings->temperature }}">
                            <small class="text-muted">0 = focused, 1 = creative.</small>
                        </div>
                        <div class="col-md-4 form-group">
                            <label>@lang('aiCore::lang.max_tokens')</label>
                            <input type="number" name="max_tokens" class="form-control" min="256" max="8192"
                                   value="{{ $settings->max_tokens }}">
                        </div>
                        <div class="col-md-4 form-group">
                            <label>@lang('aiCore::lang.monthly_token_budget')</label>
                            <input type="number" name="monthly_token_budget" class="form-control" min="0"
                                   value="{{ $settings->monthly_token_budget }}" placeholder="(unlimited)">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>@lang('aiCore::lang.system_prompt')
                            <small class="text-muted">(optional — overrides the business-type persona)</small>
                        </label>
                        <textarea name="system_prompt" class="form-control" rows="3"
                                  placeholder="Leave blank to use the built-in persona for the selected business type.">{{ $settings->system_prompt }}</textarea>
                    </div>

                    {{-- ── Voice transcription ─────────────────────────────────── --}}
                    {{-- Only relevant for clinical verticals whose consultation
                         screens have dictation buttons; hidden (but still submitted)
                         for everyone else. Toggled by the Business Type select. --}}
                    @php $voiceVisible = in_array($settings->business_vertical, config('aicore.voice_verticals', []), true); @endphp
                    <div id="voice-section" style="display:{{ $voiceVisible ? 'block' : 'none' }};">
                    <hr style="margin:18px 0;">
                    <h4 style="margin-bottom:12px;">
                        <i class="fa fa-microphone" style="color:#ef4444;"></i> Voice transcription
                        <small class="text-muted">— used by 🎤 dictation buttons (e.g. the clinic consultation tab)</small>
                    </h4>

                    <div class="form-group">
                        <label style="font-weight:normal;cursor:pointer;">
                            <input type="checkbox" name="use_separate_transcription" value="1" id="t_separate"
                                   {{ $settings->use_separate_transcription ? 'checked' : '' }}>
                            <strong>Use a different AI agent for voice</strong>
                            <small class="text-muted">— off = same provider/key as the main engine above
                            (only OpenAI / OpenAI-compatible can transcribe). On = pick a dedicated voice engine.</small>
                        </label>
                    </div>

                    <div class="row">
                        <div class="col-md-6 form-group">
                            <label>Silence tolerance (seconds)</label>
                            <input type="number" name="t_silence_limit_sec" class="form-control"
                                   min="5" max="300" step="1"
                                   value="{{ $settings->t_silence_limit_sec ?: 30 }}">
                            <small class="text-muted">
                                How long the mic keeps listening through silent gaps before auto-closing.
                                Chrome's Web Speech engine cuts off after ~5–8s by itself; we restart it underneath
                                up to this budget so users can pause mid-sentence. Range 5–300s, default 30.
                            </small>
                        </div>
                        <div class="col-md-6 form-group" style="padding-top:25px;">
                            <label style="font-weight:normal;cursor:pointer;">
                                <input type="checkbox" name="t_clean_non_medical" value="1"
                                       {{ $settings->t_clean_non_medical ? 'checked' : '' }}>
                                <strong>Strip non-medical side-talk from voice transcripts</strong>
                            </label>
                            <small class="text-muted" style="display:block;">
                                AI post-processing pass that removes small talk, asides, filler words and
                                background chatter from transcripts before they reach the textarea. Uses the
                                main engine LLM (1 extra call per dictation). Falls back to the raw transcript
                                if AI is unconfigured or errors. Recommended on.
                            </small>
                        </div>
                    </div>

                    <div id="t_block" style="display:{{ $settings->use_separate_transcription ? 'block' : 'none' }};
                                              padding:12px 14px;border-left:3px solid #ef4444;background:#fef2f2;border-radius:5px;">
                        <div class="row">
                            <div class="col-md-6"><div class="form-group">
                                <label>Voice provider</label>
                                <select name="t_provider" id="t_provider" class="form-control">
                                    @foreach(\Modules\AiCore\Entities\AiProvider::transcriptionProviders() as $k => $label)
                                        <option value="{{ $k }}" {{ ($settings->t_provider ?? 'webspeech') === $k ? 'selected' : '' }}>{{ $label }}</option>
                                    @endforeach
                                </select>
                                <small class="text-muted">Web Speech runs entirely in the browser — no API key, no cost.
                                Whisper drivers send audio to the chosen API.</small>
                            </div></div>
                            <div class="col-md-3"><div class="form-group">
                                <label>Model</label>
                                <input type="text" name="t_model" class="form-control"
                                       value="{{ $settings->t_model }}" placeholder="whisper-large-v3-turbo">
                            </div></div>
                            <div class="col-md-3"><div class="form-group">
                                <label>Language hint <span class="text-danger">*</span></label>
                                <small class="text-muted" style="display:block;margin-bottom:4px;font-size:11px;line-height:1.3;">
                                    <i class="fa fa-exclamation-triangle" style="color:#d97706;"></i>
                                    Auto-detect can mis-identify language on short or noisy clips.
                                    <strong>Pick the language users actually speak in.</strong>
                                </small>
                                <select name="t_language_hint" class="form-control">
                                    <option value="auto" {{ ($settings->t_language_hint ?? 'auto') === 'auto' ? 'selected' : '' }}>Auto-detect</option>
                                    <option value="en"   {{ $settings->t_language_hint === 'en'   ? 'selected' : '' }}>English</option>
                                    <option value="ar"   {{ $settings->t_language_hint === 'ar'   ? 'selected' : '' }}>Arabic</option>
                                </select>
                            </div></div>
                        </div>

                        <div class="row">
                            <div class="col-md-6" id="t_baseurl_row" style="display:{{ ($settings->t_provider ?? '') === 'whisper_openai_compat' ? 'block' : 'none' }};">
                                <div class="form-group">
                                    <label>Endpoint base URL <span class="text-danger">*</span></label>
                                    <input type="text" name="t_base_url" class="form-control"
                                           value="{{ $settings->t_base_url }}" placeholder="http://localhost:8080/v1">
                                </div>
                            </div>
                            <div class="col-md-6" id="t_apikey_row">
                                <div class="form-group">
                                    <label>API key</label>
                                    <input type="password" name="t_api_key" class="form-control"
                                           value="{{ $settings->t_api_key ? '••••••••' : '' }}" autocomplete="new-password"
                                           placeholder="Leave unchanged to keep the saved key">
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label style="font-weight:normal;cursor:pointer;">
                                <input type="checkbox" name="auto_structure_soap" value="1"
                                       {{ $settings->auto_structure_soap ? 'checked' : '' }}>
                                Auto-structure the transcript into Subjective / Objective / Assessment / Plan via the main engine LLM
                            </label>
                            <label style="font-weight:normal;cursor:pointer;display:block;">
                                <input type="checkbox" name="consent_warning" value="1"
                                       {{ $settings->consent_warning ? 'checked' : '' }}>
                                Show the user an "audio will be sent to {provider}" notice before the mic opens
                            </label>
                        </div>
                    </div>
                    </div>{{-- /#voice-section --}}

                    {{-- ── Custom AI prompts (advanced) ─────────────────────────── --}}
                    @if(!empty($promptGroups))
                    <hr style="margin:18px 0;">
                    <details {{ !empty($promptOverrides) ? 'open' : '' }} style="margin-bottom:14px;">
                        <summary style="cursor:pointer;font-weight:600;font-size:15px;">
                            <i class="fa fa-sliders-h"></i> Custom AI prompts (advanced)
                            <small class="text-muted">— override the built-in instruction for each AI task. Leave blank to use the default.</small>
                        </summary>
                        <div style="margin-top:12px;padding:12px 14px;border-left:3px solid #6366f1;background:#eef2ff;border-radius:5px;">
                            <small class="text-muted" style="display:block;margin-bottom:10px;">
                                <i class="fa fa-info-circle"></i> Each box is the <strong>system prompt</strong> for one task.
                                The grey text is the built-in default — type here only to override it. Defaults are
                                <strong>tuned to your Business Type</strong> above (veterinary vs medical vs automotive …),
                                so changing it &amp; saving re-frames them. Keep any <code>{placeholder}</code> tokens
                                (e.g. <code>{specialty}</code>), and for tasks marked "must return JSON" keep the output
                                instructions so the app can still parse the result.
                            </small>
                            @foreach($promptGroups as $group => $items)
                                <h5 style="font-weight:700;margin:14px 0 6px;color:#3730a3;">{{ $group }}</h5>
                                @foreach($items as $key => $meta)
                                    <div class="form-group" style="margin-bottom:10px;">
                                        <label style="margin-bottom:2px;">{{ $meta['label'] }}
                                            <small class="text-muted">— {{ $meta['note'] }}</small>
                                            <a href="#" class="prompt-reset" data-key="{{ $key }}" style="font-size:11px;margin-left:6px;">↺ reset to default</a>
                                        </label>
                                        <textarea name="prompts[{{ $key }}]" class="form-control"
                                                  rows="3" style="font-family:monospace;font-size:11.5px;"
                                                  placeholder="{{ $promptDefaults[$key] ?? $meta['default'] }}">{{ $promptOverrides[$key] ?? '' }}</textarea>
                                    </div>
                                @endforeach
                            @endforeach
                        </div>
                    </details>
                    @endif

                    <div class="form-group">
                        <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> @lang('aiCore::lang.save')</button>
                        <button type="button" class="btn btn-default" id="btn_test"><i class="fa fa-plug"></i> @lang('aiCore::lang.test_connection')</button>
                        <span id="test_result" style="margin-left:10px;font-size:12px;"></span>
                    </div>

                    <div class="callout callout-info" style="font-size:12px;margin-bottom:0;">
                        <i class="fa fa-info-circle"></i> {{ __('aiCore::lang.disclaimer') }}
                    </div>
                </form>
            @endcomponent
        </div>

        <div class="col-md-4">
            @component('components.widget', ['class' => 'box-solid'])
                <h4 style="margin-top:0;"><i class="fa fa-chart-line"></i> @lang('aiCore::lang.usage_this_month')</h4>
                <p style="font-size:28px;font-weight:600;margin:0;">{{ number_format($mtdTokens) }}
                    <small style="font-size:13px;color:#888;">tokens</small></p>
                @if($settings->monthly_token_budget)
                    @php $pct = min(100, (int) round($mtdTokens / max(1, $settings->monthly_token_budget) * 100)); @endphp
                    <div class="progress" style="margin-top:8px;height:8px;">
                        <div class="progress-bar {{ $pct >= 100 ? 'progress-bar-danger' : ($pct >= 80 ? 'progress-bar-warning' : 'progress-bar-success') }}"
                             style="width: {{ $pct }}%;"></div>
                    </div>
                    <small class="text-muted">{{ number_format($settings->monthly_token_budget) }} budget ({{ $pct }}%)</small>
                @else
                    <small class="text-muted">No monthly budget set (unlimited).</small>
                @endif

                <hr>
                <h5 style="font-weight:600;">@lang('aiCore::lang.recent_calls')</h5>
                @if($recentLogs->isEmpty())
                    <p class="text-muted" style="font-size:12px;">No AI calls recorded yet.</p>
                @else
                    <table class="table table-condensed" style="font-size:11px;margin-bottom:0;">
                        <thead><tr><th>When</th><th>Module</th><th class="text-right">Tok</th><th></th></tr></thead>
                        <tbody>
                        @foreach($recentLogs as $log)
                            <tr>
                                <td>{{ optional($log->created_at)->format('m-d H:i') }}</td>
                                <td>{{ $log->module }}{{ $log->feature ? ' / '.$log->feature : '' }}</td>
                                <td class="text-right">{{ number_format($log->total_tokens) }}</td>
                                <td>@if($log->ok)<span style="color:#16a34a;">✓</span>@else<span style="color:#dc2626;" title="{{ $log->error }}">✗</span>@endif</td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>
                @endif
            @endcomponent
        </div>
    </div>

    {{-- ══ BOX A · AI services library ═══════════════════════════════════════
         Each service (Groq, Claude, …) is configured & connection-tested ONCE
         here. Every panel is its own <form> to service.save (nested forms are
         invalid HTML, so this sits outside the main form above). The failover
         chain below then just points slots at a configured service. --}}
    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-info'])
                <h4 style="margin-top:0;">
                    <i class="fa fa-plug"></i> @lang('aiCore::lang.ai_services')
                </h4>
                <p class="text-muted" style="font-size:12px;">{{ __('aiCore::lang.ai_services_help') }}</p>

                {{-- "Add provider" picker: lists only the not-yet-added services.
                     Adding just reveals the (server-rendered, hidden) panel — the
                     svc_ row is only created when the panel is saved. --}}
                @php
                    $addedCount = 0;
                    $notAdded   = [];
                    foreach ($presets as $pk => $pp) {
                        if (!empty($services[$pk])) { $addedCount++; } else { $notAdded[$pk] = $pp['label']; }
                    }
                @endphp
                <div id="service-add-row" class="form-inline" style="margin-bottom:14px;{{ empty($notAdded) ? 'display:none;' : '' }}">
                    <label style="font-size:12px;margin-right:6px;">@lang('aiCore::lang.add_provider')</label>
                    <select id="service-add-select" class="form-control input-sm">
                        @foreach($notAdded as $nk => $nlabel)
                            <option value="{{ $nk }}">{{ $nlabel }}</option>
                        @endforeach
                    </select>
                    <button type="button" class="btn btn-primary btn-sm" id="service-add-btn">
                        <i class="fa fa-plus"></i> @lang('aiCore::lang.add')
                    </button>
                </div>

                <p id="services-empty" class="text-muted" style="font-size:12px;{{ $addedCount === 0 ? '' : 'display:none;' }}">
                    <i class="fa fa-info-circle"></i> @lang('aiCore::lang.no_services_yet')
                </p>

                {{-- Flexbox wrap so cards of differing height never catch on each
                     other's float (the classic Bootstrap uneven-column gap). --}}
                <div class="row" style="display:flex; flex-wrap:wrap; align-items:flex-start;">
                    @foreach($presets as $skey => $preset)
                        @php
                            $svc        = $services[$skey] ?? null;
                            $isConf     = $svc && $svc->isConfigured();
                            $svcProvider = $svc->provider ?? $preset['provider'];
                            $svcBaseUrl  = $svc->base_url ?? $preset['base_url'];
                            $svcModel    = $svc->model ?? $preset['model'];
                        @endphp
                        <div class="col-md-6 service-panel-wrap" data-service="{{ $skey }}"
                             style="margin-bottom:14px;{{ $svc ? '' : 'display:none;' }}">
                            <form method="POST" action="{{ route('aicore.settings.service.save') }}"
                                  class="service-panel" data-service="{{ $skey }}"
                                  style="border:1px solid #d2d6de;border-radius:5px;padding:12px;height:100%;">
                                @csrf
                                <input type="hidden" name="service" value="{{ $skey }}">

                                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
                                    <h5 style="font-weight:700;margin:0;">{{ $preset['label'] }}</h5>
                                    @if($isConf)
                                        <span class="label label-success"><i class="fa fa-check"></i> @lang('aiCore::lang.configured')</span>
                                    @else
                                        <span class="label label-default">@lang('aiCore::lang.not_configured')</span>
                                    @endif
                                </div>

                                {{-- Default (primary) selector — exactly one service backs the
                                     primary at a time. The radios carry no name so they never
                                     submit with the panel's save form; clicking one posts the
                                     hidden make-default form instead. --}}
                                @if($svc)
                                    <div class="form-group" style="margin-bottom:8px;">
                                        @if($defaultServiceKey === $skey)
                                            <label style="font-weight:normal;font-size:12px;margin:0;cursor:default;">
                                                <input type="radio" checked disabled>
                                                <span class="label label-primary"><i class="fa fa-star"></i> @lang('aiCore::lang.default_service_badge')</span>
                                            </label>
                                        @elseif($isConf)
                                            <label class="service-make-default" data-service="{{ $skey }}"
                                                   style="font-weight:normal;font-size:12px;margin:0;cursor:pointer;">
                                                <input type="radio"> @lang('aiCore::lang.make_default')
                                            </label>
                                        @else
                                            <label style="font-weight:normal;font-size:12px;margin:0;color:#999;cursor:not-allowed;"
                                                   title="{{ __('aiCore::lang.make_default_hint') }}">
                                                <input type="radio" disabled> @lang('aiCore::lang.make_default')
                                            </label>
                                        @endif
                                    </div>
                                @endif

                                <div class="form-group" style="margin-bottom:8px;">
                                    <label style="font-size:12px;margin-bottom:2px;">@lang('aiCore::lang.provider')</label>
                                    <select name="provider" class="form-control input-sm service-provider">
                                        <option value="anthropic"         {{ $svcProvider == 'anthropic' ? 'selected' : '' }}>Anthropic (Claude)</option>
                                        <option value="openai"            {{ $svcProvider == 'openai' ? 'selected' : '' }}>OpenAI (GPT)</option>
                                        <option value="gemini"            {{ $svcProvider == 'gemini' ? 'selected' : '' }}>Google (Gemini)</option>
                                        <option value="openai_compatible" {{ $svcProvider == 'openai_compatible' ? 'selected' : '' }}>OpenAI-Compatible</option>
                                    </select>
                                </div>

                                <div class="form-group service-baseurl-group" style="margin-bottom:8px;display:{{ $svcProvider === 'openai_compatible' ? 'block' : 'none' }};">
                                    <label style="font-size:12px;margin-bottom:2px;">@lang('aiCore::lang.endpoint_base_url')</label>
                                    <input type="text" name="base_url" class="form-control input-sm"
                                           value="{{ $svcBaseUrl }}" placeholder="https://…">
                                </div>

                                <div class="form-group" style="margin-bottom:8px;">
                                    <label style="font-size:12px;margin-bottom:2px;">@lang('aiCore::lang.api_key')</label>
                                    <input type="password" name="api_key" class="form-control input-sm" autocomplete="new-password"
                                           placeholder="{{ ($svc && $svc->api_key) ? '••••••••  (saved)' : 'API key' }}">
                                </div>

                                <div class="form-group" style="margin-bottom:8px;">
                                    <label style="font-size:12px;margin-bottom:2px;">@lang('aiCore::lang.model')</label>
                                    <input type="text" name="model" class="form-control input-sm"
                                           value="{{ $svcModel }}" placeholder="model id">
                                </div>

                                <div class="row" style="margin:0 -5px 8px;">
                                    <div class="col-xs-6" style="padding:0 5px;">
                                        <label style="font-size:12px;margin-bottom:2px;">@lang('aiCore::lang.temperature')</label>
                                        <input type="number" name="temperature" class="form-control input-sm" step="0.1" min="0" max="1"
                                               value="{{ $svc->temperature ?? 0.4 }}">
                                    </div>
                                    <div class="col-xs-6" style="padding:0 5px;">
                                        <label style="font-size:12px;margin-bottom:2px;">@lang('aiCore::lang.max_tokens')</label>
                                        <input type="number" name="max_tokens" class="form-control input-sm" min="256" max="8192"
                                               value="{{ $svc->max_tokens ?? 1024 }}">
                                    </div>
                                </div>

                                <button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-save"></i> @lang('aiCore::lang.save_service')</button>
                                <button type="button" class="btn btn-default btn-sm service-test" data-service="{{ $skey }}"><i class="fa fa-plug"></i> @lang('aiCore::lang.test_connection')</button>
                                @if($svc)
                                    <button type="button" class="btn btn-danger btn-xs pull-right service-remove" data-service="{{ $skey }}"
                                            style="margin-top:4px;"><i class="fa fa-trash"></i> @lang('aiCore::lang.remove_service')</button>
                                @endif
                                <div class="service-test-result" style="margin-top:6px;font-size:11px;"></div>
                            </form>
                        </div>
                    @endforeach
                </div>

                {{-- Hidden forms the per-panel Remove / Make-default controls
                     submit (a panel is already a <form> to service.save, so these
                     post via separate ones — nested forms are invalid HTML). --}}
                <form id="service-remove-form" method="POST" action="{{ route('aicore.settings.service.remove') }}" style="display:none;">
                    @csrf
                    <input type="hidden" name="service" id="service-remove-key" value="">
                </form>
                <form id="service-default-form" method="POST" action="{{ route('aicore.settings.service.make_default') }}" style="display:none;">
                    @csrf
                    <input type="hidden" name="service" id="service-default-key" value="">
                </form>
            @endcomponent
        </div>
    </div>

    {{-- ══ BOX B · Failover chain ════════════════════════════════════════════
         A single <form> to chain.save: each slot is a dropdown picking one of
         the CONFIGURED services above (or "— none —"). --}}
    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-warning'])
                <h4 style="margin-top:0;">
                    <i class="fa fa-life-ring"></i> @lang('aiCore::lang.failover_chain')
                </h4>
                <p class="text-muted" style="font-size:12px;">{{ __('aiCore::lang.failover_intro') }}</p>

                <form method="POST" action="{{ route('aicore.settings.chain.save') }}">
                    @csrf
                    <div class="row">
                        @php
                            // Only configured services are selectable.
                            $configuredServices = [];
                            foreach ($presets as $ck => $cp) {
                                $cs = $services[$ck] ?? null;
                                if ($cs && $cs->isConfigured()) {
                                    $configuredServices[$ck] = $cp['label'] . ' — ' . $cs->model;
                                }
                            }
                        @endphp

                        {{-- Primary (Default) — read-only here; changed via the
                             "Make default" selector on the service cards above. --}}
                        <div class="col-md-3">
                            <div style="border:1px solid #d2d6de;border-radius:5px;padding:12px;height:100%;background:#f9fafb;">
                                <h5 style="font-weight:700;margin-top:0;">
                                    <span class="label label-success">1</span> @lang('aiCore::lang.primary_default')
                                </h5>
                                <p style="font-size:12px;margin-bottom:6px;">
                                    @if($defaultServiceKey && isset($presets[$defaultServiceKey]))
                                        <strong>{{ $presets[$defaultServiceKey]['label'] }}</strong>
                                        @if($settings->model)<br><small class="text-muted">{{ $settings->model }}</small>@endif
                                    @else
                                        <span class="{{ $defaultConfigured ? '' : 'text-muted' }}">@lang('aiCore::lang.chain_primary_manual')</span>
                                        @if($settings->model)<br><small class="text-muted">{{ $settings->provider }} — {{ $settings->model }}</small>@endif
                                    @endif
                                </p>
                                <small class="text-muted" style="font-size:11px;">@lang('aiCore::lang.chain_primary_note')</small>
                            </div>
                        </div>

                        {{-- fallback / fallback2 / fallback3 — service dropdowns --}}
                        @foreach((array) config('aicore.fallback_names', []) as $slotKey)
                            @php $current = $chainAssignments[$slotKey]['name'] ?? null; @endphp
                            <div class="col-md-3">
                                <div style="border:1px solid #d2d6de;border-radius:5px;padding:12px;height:100%;">
                                    <h5 style="font-weight:700;margin-top:0;">
                                        <span class="label label-default">{{ $loop->iteration + 1 }}</span> {{ $slotKey }}
                                    </h5>
                                    <div class="form-group" style="margin-bottom:6px;">
                                        <select name="chain[{{ $slotKey }}]" class="form-control input-sm">
                                            <option value="">@lang('aiCore::lang.chain_none')</option>
                                            @foreach($configuredServices as $csk => $cslabel)
                                                <option value="{{ $csk }}" {{ $current === $csk ? 'selected' : '' }}>{{ $cslabel }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>

                    <button type="submit" class="btn btn-warning btn-sm" style="margin-top:8px;">
                        <i class="fa fa-save"></i> @lang('aiCore::lang.chain_save')
                    </button>
                </form>
            @endcomponent
        </div>
    </div>
</section>
@endsection

@section('javascript')
<script>
// Reset a custom prompt to its (business-type-aware) default — clearing the box
// means "use the built-in default shown as the placeholder".
$(document).on('click', '.prompt-reset', function (e) {
    e.preventDefault();
    $('textarea[name="prompts[' + $(this).data('key') + ']"]').val('');
});

// Business Type → show the Voice transcription block only for clinical
// verticals (values still submit while hidden — that's intended).
var voiceVerticals = @json(config('aicore.voice_verticals', []));
$('#business_vertical').on('change', function () {
    $('#voice-section').toggle(voiceVerticals.indexOf($(this).val()) !== -1);
});

// Voice block: toggle visibility + base-URL/api-key rows per provider
$('#t_separate').on('change', function () {
    $('#t_block').toggle(this.checked);
});
$('#t_provider').on('change', function () {
    var p = $(this).val();
    $('#t_baseurl_row').toggle(p === 'whisper_openai_compat');
    $('#t_apikey_row').toggle(p !== 'webspeech');
});

$('#btn_test').on('click', function () {
    var $btn = $(this).prop('disabled', true);
    $('#test_result').html('<i class="fa fa-spinner fa-spin"></i> testing…');
    $.post('{{ route('aicore.settings.test') }}', { _token: '{{ csrf_token() }}' })
        .done(function (res) {
            $('#test_result').html('<span style="color:' + (res.success ? '#16a34a' : '#dc2626') + ';">'
                + (res.success ? '<i class="fa fa-check"></i> ' : '<i class="fa fa-times"></i> ')
                + $('<div>').text(res.msg).html() + '</span>');
        })
        .fail(function () { $('#test_result').html('<span style="color:#dc2626;">Test failed</span>'); })
        .always(function () { $btn.prop('disabled', false); });
});

// ── AI services library ───────────────────────────────────────────────
// "Add provider" → reveal that provider's (server-rendered, hidden) panel and
// drop it from the picker. No server roundtrip: the svc_ row is only created
// when the panel is saved, so an unsaved panel simply vanishes on reload.
$('#service-add-btn').on('click', function () {
    var $sel = $('#service-add-select');
    var key  = $sel.val();
    if (!key) { return; }
    $('.service-panel-wrap[data-service="' + key + '"]').show();
    $sel.find('option[value="' + key + '"]').remove();
    if (!$sel.find('option').length) { $('#service-add-row').hide(); }
    $('#services-empty').hide();
});

// Remove a saved service (confirm first) — posts the hidden remove form so the
// flash + refreshed Add picker come back server-rendered.
$(document).on('click', '.service-remove', function () {
    if (!confirm(@json(__('aiCore::lang.remove_service_confirm')))) { return; }
    $('#service-remove-key').val($(this).data('service'));
    $('#service-remove-form').trigger('submit');
});

// "Make default" radio → post the hidden make-default form; the page reloads
// with the badge on the newly-selected card (exactly one default at a time).
$(document).on('click', '.service-make-default', function () {
    $('#service-default-key').val($(this).data('service'));
    $('#service-default-form').trigger('submit');
});

// Show the base-URL field only for openai_compatible, per service panel.
$(document).on('change', '.service-panel .service-provider', function () {
    var $panel = $(this).closest('.service-panel');
    $panel.find('.service-baseurl-group').toggle($(this).val() === 'openai_compatible');
});

// Per-service connectivity test — same endpoint as the main Test button, with
// the service row name (svc_<key>) so it targets that service (no_fallback
// server-side). Services must be saved first — same as the main Test button.
$(document).on('click', '.service-test', function () {
    var $btn = $(this).prop('disabled', true);
    var $out = $btn.closest('.service-panel').find('.service-test-result');
    $out.html('<i class="fa fa-spinner fa-spin"></i> testing…');
    $.post('{{ route('aicore.settings.test') }}', { _token: '{{ csrf_token() }}', profile: 'svc_' + $btn.data('service') })
        .done(function (res) {
            $out.html('<span style="color:' + (res.success ? '#16a34a' : '#dc2626') + ';">'
                + (res.success ? '<i class="fa fa-check"></i> ' : '<i class="fa fa-times"></i> ')
                + $('<div>').text(res.msg).html() + '</span>');
        })
        .fail(function () { $out.html('<span style="color:#dc2626;">Test failed</span>'); })
        .always(function () { $btn.prop('disabled', false); });
});
</script>
@endsection
