@extends('layouts.admin')

@section('title', 'AI Assistant Settings')

@section('content')
<div class="max-w-[1200px] mx-auto admin-simple px-4 lg:px-0 py-10">
    <style>
        .admin-simple{
            font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, "Noto Sans", Arial, "Apple Color Emoji","Segoe UI Emoji";
            min-height:calc(100vh - 120px);
        }
        .admin-simple .uppercase{ text-transform:none !important }
        .admin-simple [class*="tracking-"]{ letter-spacing:normal !important }
        .admin-simple .font-black{ font-weight:600 !important }
        .admin-simple label{ font-size:0.875rem; font-weight:600; color:#374151 }
        .admin-simple input[type="text"],
        .admin-simple input[type="email"],
        .admin-simple input[type="number"],
        .admin-simple input[type="file"],
        .admin-simple textarea,
        .admin-simple select{
            background:#ffffff; border:1px solid #e5e7eb; border-radius:0.75rem;
            padding:0.625rem 0.75rem; font-size:0.875rem; font-weight:500; letter-spacing:normal;
        }
        .admin-simple input:focus,
        .admin-simple textarea:focus,
        .admin-simple select:focus{
            outline:none; border-color:#22c55e; box-shadow:0 0 0 3px rgba(34,197,94,0.2)
        }
        @keyframes fadeUpSoft{
            0%{ opacity:0; transform:translateY(10px) scale(0.98) }
            100%{ opacity:1; transform:translateY(0) scale(1) }
        }
        .admin-simple .fade-card{
            opacity:0;
            animation:fadeUpSoft .45s ease-out forwards;
            transform-origin:top;
        }
        .admin-simple .fade-card-delay-1{ animation-delay:.05s }
        .admin-simple .fade-card-delay-2{ animation-delay:.1s }
        .admin-simple .fade-card-delay-3{ animation-delay:.15s }
        .admin-simple .section-header{
            padding:1rem 1.25rem;
            background:linear-gradient(to right, rgba(16,185,129,0.04), rgba(59,130,246,0.02));
            border-bottom:1px solid #f3f4f6;
        }
        .admin-simple .section-title{ font-size:0.9rem; font-weight:700; color:#111827 }
        .admin-simple .section-sub{ font-size:0.75rem; color:#6b7280; font-weight:600 }
        .admin-simple .card{
            background:#ffffff;
            border:1px solid #e5e7eb;
            border-radius:1rem;
            box-shadow:0 8px 18px rgba(15,23,42,0.04);
        }
        .admin-simple .btn-primary{
            display:inline-flex; align-items:center; gap:0.5rem;
            background:linear-gradient(135deg,#16a34a,#22c55e);
            color:#fff; padding:0.8rem 1.4rem; border-radius:9999px;
            font-size:0.9rem; font-weight:700;
            box-shadow:0 10px 22px rgba(22,163,74,0.18);
            transition:transform .18s ease, box-shadow .18s ease, background .18s ease, filter .18s ease;
        }
        .admin-simple .btn-primary:hover{
            background:linear-gradient(135deg,#15803d,#16a34a);
            box-shadow:0 12px 26px rgba(22,163,74,0.24);
        }
        .admin-simple .secret-input-wrapper{
            background:#f9fafb;
            border-radius:0.9rem;
            border:1px solid #e5e7eb;
            padding:0.1rem 0.8rem;
        }
        .admin-simple .secret-input-wrapper:focus-within{
            border-color:#22c55e;
            background:#fefeff;
        }
        .admin-simple .secret-input{
            border:none;
            background:transparent;
            padding-left:0;
            padding-right:2.25rem;
        }
        .admin-simple .secret-input:focus{
            outline:none;
            box-shadow:none;
        }
        .admin-simple #ai-test-button{
            box-shadow:0 8px 18px rgba(15,23,42,0.06);
        }
    </style>

    <div class="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8 px-5 py-4 rounded-2xl bg-white border border-gray-200 shadow-sm fade-card">
        <div>
            <div class="flex items-center gap-2 mb-2">
                <span class="px-3 py-1 bg-emerald-50 text-emerald-700 text-[11px] font-semibold rounded-full ring-1 ring-emerald-100">AI configuration</span>
                <span class="text-[11px] font-semibold text-gray-400">Admin settings</span>
            </div>
            <h1 class="text-[1.6rem] font-semibold tracking-tight text-gray-900">AI settings</h1>
            <p class="text-sm text-gray-500 mt-1.5 max-w-xl">
                Manage AI provider, models and product copy settings from a single place.
            </p>
        </div>
        <div class="flex items-center gap-3 mt-4 md:mt-0">
            <button
                type="submit"
                form="ai-settings-form"
                class="btn-primary">
                <i class="fas fa-save text-xs mr-2"></i>
                Save AI Settings
            </button>
        </div>
    </div>

    @if(session('success'))
        <div class="bg-emerald-50/80 border border-emerald-100/80 p-4 rounded-xl mb-6 flex items-center shadow-sm fade-card fade-card-delay-1">
            <div class="bg-green-100 p-2 rounded-lg mr-3">
                <i class="fas fa-check text-green-600"></i>
            </div>
            <div>
                <p class="text-green-800 font-bold text-sm">{{ session('success') }}</p>
            </div>
        </div>
    @endif

    @if($errors->any())
        <div class="bg-red-50/90 border border-red-100 p-4 rounded-xl mb-6 flex items-start shadow-sm fade-card fade-card-delay-1">
            <div class="bg-red-100 p-2 rounded-lg mr-3">
                <i class="fas fa-exclamation-triangle text-red-600"></i>
            </div>
            <div>
                <p class="text-red-800 font-bold text-sm mb-1">Please fix the following issues:</p>
                <ul class="text-xs text-red-700 space-y-1">
                    @foreach ($errors->all() as $error)
                        <li>• {{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        </div>
    @endif

    <form id="ai-settings-form" action="{{ route('admin.ai.settings.update') }}" method="POST" class="space-y-10">
        @csrf

        <div class="grid grid-cols-1 xl:grid-cols-3 gap-8 items-start">
            <div class="xl:col-span-2 space-y-8">
                <div class="card overflow-hidden fade-card fade-card-delay-1">
                    <div class="section-header">
                        <div>
                            <p class="section-title">Provider Configuration</p>
                            <p class="section-sub">Connect your AI provider securely.</p>
                        </div>
                    </div>
                    <div class="p-6 md:p-8 space-y-6">
                    @php
                        $hasAiKey = !empty($settings['ai_api_key'] ?? null);
                    @endphp

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div class="space-y-2">
                            <label class="text-xs font-semibold text-gray-700">API Base URL</label>
                            <input
                                type="text"
                                name="ai_api_base_url"
                                value="{{ old('ai_api_base_url', $settings['ai_api_base_url'] ?? 'https://openrouter.ai/api/v1') }}"
                                class="w-full rounded-xl border border-gray-200 text-sm focus:ring-2 focus:ring-brand/20 focus:border-brand/40"
                                placeholder="https://openrouter.ai/api/v1">
                            <p class="text-[11px] text-gray-400 mt-1">Recommended: OpenRouter unified endpoint for 300+ models.</p>
                        </div>

                        <div class="space-y-2">
                            <label class="text-xs font-semibold text-gray-700">Model</label>
                            <input
                                type="text"
                                name="ai_model"
                                value="{{ old('ai_model', $settings['ai_model'] ?? 'openai/gpt-4.1-mini') }}"
                                class="w-full rounded-xl border border-gray-200 text-sm focus:ring-2 focus:ring-brand/20 focus:border-brand/40"
                                placeholder="openai/gpt-4.1-mini">
                            <p class="text-[11px] text-gray-400 mt-1">Example OpenRouter model: openai/gpt-4.1-mini or any listed model ID.</p>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <label class="text-xs font-semibold text-gray-700">Secret API Key</label>
                        <div class="relative secret-input-wrapper">
                            <input
                                type="password"
                                name="ai_api_key"
                                value="{{ old('ai_api_key') }}"
                                class="secret-input w-full text-sm"
                                autocomplete="off"
                                placeholder="sk-or-v1-xxxxxxxx">
                            @if($hasAiKey && !old('ai_api_key'))
                                <div class="absolute inset-y-0 left-3 flex items-center text-[12px] text-gray-400 select-none pointer-events-none">
                                    ••••••••••••••••••••
                                </div>
                            @endif
                            <div class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400">
                                <i class="fas fa-lock text-xs"></i>
                            </div>
                        </div>
                        <p class="text-[11px] text-gray-400 mt-1">Your AI provider's secret key.</p>
                    </div>
                    </div>
                </div>

                <div class="card overflow-hidden fade-card fade-card-delay-2">
                    <div class="section-header">
                        <div>
                            <p class="section-title">Generation Defaults</p>
                        </div>
                    </div>
                    <div class="p-6 md:p-8 space-y-6">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
                        <div class="space-y-2">
                            <label class="text-xs font-semibold text-gray-700">Language</label>
                            <select name="ai_language" class="w-full rounded-xl border border-gray-200 text-sm focus:ring-2 focus:ring-brand/20 focus:border-brand/40">
                                @php
                                    $lang = $settings['ai_language'] ?? 'en';
                                @endphp
                                <option value="en" {{ $lang === 'en' ? 'selected' : '' }}>English</option>
                                <option value="bn" {{ $lang === 'bn' ? 'selected' : '' }}>Bangla</option>
                            </select>
                            <p class="text-[11px] text-gray-400 mt-1">Preferred language for generated text.</p>
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-semibold text-gray-700">Tone</label>
                            @php
                                $tone = $settings['ai_tone'] ?? 'neutral';
                            @endphp
                            <select name="ai_tone" class="w-full rounded-xl border border-gray-200 text-sm focus:ring-2 focus:ring-brand/20 focus:border-brand/40">
                                <option value="neutral" {{ $tone === 'neutral' ? 'selected' : '' }}>Neutral</option>
                                <option value="friendly" {{ $tone === 'friendly' ? 'selected' : '' }}>Friendly</option>
                                <option value="formal" {{ $tone === 'formal' ? 'selected' : '' }}>Formal</option>
                            </select>
                            <p class="text-[11px] text-gray-400 mt-1">Overall voice of the copy.</p>
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-semibold text-gray-700">Creativity (Temperature)</label>
                            <input
                                type="number"
                                step="0.1"
                                min="0"
                                max="1"
                                name="ai_temperature"
                                value="{{ old('ai_temperature', $settings['ai_temperature'] ?? '0.7') }}"
                                class="w-full rounded-xl border border-gray-200 text-sm focus:ring-2 focus:ring-brand/20 focus:border-brand/40">
                            <p class="text-[11px] text-gray-400 mt-1">Lower = more precise, higher = more creative.</p>
                        </div>
                    </div>
                    </div>
                </div>

                <div class="card overflow-hidden fade-card fade-card-delay-3">
                    <div class="section-header">
                        <div>
                            <p class="section-title">Background Removal (Product Images)</p>
                            <p class="section-sub">Configure API used by “Remove background” in the product image editor.</p>
                        </div>
                        <button
                            type="button"
                            id="removebg-help-toggle"
                            class="inline-flex items-center px-3 py-1.5 rounded-full border border-gray-200 text-[11px] font-semibold text-gray-700 bg-white hover:bg-gray-50 hover:border-brand/30 transition-all">
                            <i class="fas fa-info-circle text-xs mr-1.5 text-emerald-500"></i>
                            How to get API
                        </button>
                    </div>
                    <div class="p-6 md:p-8 space-y-6">
                        @php
                            $hasRemoveBgKey = !empty($settings['removebg_api_key'] ?? null);
                        @endphp
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                            <div class="space-y-2">
                                <label class="text-xs font-semibold text-gray-700">Background removal API URL</label>
                                <input
                                    type="text"
                                    name="removebg_api_url"
                                    value="{{ old('removebg_api_url', $settings['removebg_api_url'] ?? 'https://api.remove.bg/v1.0/removebg') }}"
                                    class="w-full rounded-xl border border-gray-200 text-sm focus:ring-2 focus:ring-brand/20 focus:border-brand/40"
                                    placeholder="https://api.remove.bg/v1.0/removebg">
                                <p class="text-[11px] text-gray-400 mt-1">Use remove.bg or any compatible background removal endpoint.</p>
                            </div>
                            <div class="space-y-2">
                                <label class="text-xs font-semibold text-gray-700">Background removal API key</label>
                                <div class="relative secret-input-wrapper">
                                    <input
                                        type="password"
                                        name="removebg_api_key"
                                        value="{{ old('removebg_api_key') }}"
                                        class="secret-input w-full text-sm"
                                        autocomplete="off"
                                        placeholder="rb-xxxxxxxx">
                                    @if($hasRemoveBgKey && !old('removebg_api_key'))
                                        <div class="absolute inset-y-0 left-3 flex items-center text-[12px] text-gray-400 select-none pointer-events-none">
                                            ••••••••••••••••••••
                                        </div>
                                    @endif
                                    <div class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400">
                                        <i class="fas fa-image text-xs"></i>
                                    </div>
                                </div>
                                <p class="text-[11px] text-gray-400 mt-1">Stored securely in the database. Used only for product image background removal.</p>
                            </div>
                        </div>
                        <div class="flex flex-col gap-3 mt-2">
                            <p class="text-[11px] text-gray-500 max-w-md">
                                When configured, admins can use the “Remove background” button in the product image editor to send images to this API and receive clean, ecommerce-ready cutouts.
                            </p>
                            <div
                                id="removebg-help-panel"
                                class="hidden rounded-xl border border-dashed border-emerald-200 bg-emerald-50/40 px-4 py-3 text-[11px] text-gray-700 space-y-1.5"
                            >
                                <p class="font-semibold text-gray-900 flex items-center gap-1.5">
                                    <span class="inline-flex h-5 w-5 items-center justify-center rounded-full bg-emerald-500 text-white text-[9px]">
                                        <i class="fas fa-image"></i>
                                    </span>
                                    Where to get the API
                                </p>
                                <p>1. Go to <span class="font-mono text-[10px]">remove.bg</span> and create an account.</p>
                                <p>2. Open the dashboard → API section and copy your secret API key.</p>
                                <p>3. Paste the key in “Background removal API key” and set the API URL above.</p>
                                <p>4. Click “Save AI Settings”, then use “Remove background” in the product image editor.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="space-y-6">
                <div class="card overflow-hidden fade-card fade-card-delay-3">
                    <div class="section-header">
                        <div>
                            <p class="section-title">Connection Status</p>
                            <p class="section-sub">Status of the AI configuration.</p>
                        </div>
                    </div>
                    <div class="p-6 space-y-5">
                        @php
                            $isConfigured = ($settings['ai_api_key'] ?? null) && ($settings['ai_model'] ?? null) && ($settings['ai_api_base_url'] ?? null);
                        @endphp
                        @if($isConfigured)
                            <div class="flex items-start justify-between gap-4">
                                <div class="flex items-center gap-3">
                                    <div class="w-9 h-9 rounded-xl bg-emerald-50 flex items-center justify-center text-emerald-600">
                                        <i class="fas fa-circle-check text-sm"></i>
                                    </div>
                                    <div>
                                        <p class="text-sm font-semibold text-gray-900">Connected</p>
                                        <p class="text-[11px] text-gray-500 mt-0.5">You can start using the AI description assistant.</p>
                                    </div>
                                </div>
                                <span class="inline-flex items-center px-3 py-1 rounded-full bg-emerald-50 text-emerald-700 text-[11px] font-semibold">System online</span>
                            </div>
                        @else
                            <div class="flex items-start justify-between gap-4">
                                <div class="flex items-center gap-3">
                                    <div class="w-9 h-9 rounded-xl bg-amber-50 flex items-center justify-center text-amber-600">
                                        <i class="fas fa-triangle-exclamation text-sm"></i>
                                    </div>
                                    <div>
                                        <p class="text-sm font-semibold text-gray-900">Configuration required</p>
                                        <p class="text-[11px] text-gray-500 mt-0.5">Add API base URL, model and secret key to enable AI.</p>
                                    </div>
                                </div>
                                <span class="inline-flex items-center px-3 py-1 rounded-full bg-amber-50 text-amber-700 text-[11px] font-semibold">Not connected</span>
                            </div>
                        @endif
                        <div class="border-t border-gray-100 pt-4 space-y-2">
                            <div class="flex items-center justify-between text-[11px] text-gray-500">
                                <span>Endpoint</span>
                                <span class="font-medium text-gray-800 truncate max-w-[200px] text-right">{{ $settings['ai_api_base_url'] ?? 'Not set' }}</span>
                            </div>
                            <div class="flex items-center justify-between text-[11px] text-gray-500">
                                <span>Model</span>
                                <span class="font-medium text-gray-800 truncate max-w-[200px] text-right">{{ $settings['ai_model'] ?? 'Not set' }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mt-6">
            <div class="card overflow-hidden fade-card fade-card-delay-2">
                <div class="section-header">
                    <div>
                        <p class="section-title">Test Mode</p>
                        <p class="section-sub">Send a sample prompt and verify the AI response.</p>
                    </div>
                </div>
                <div class="p-6 md:p-8 space-y-4">
                    <div class="space-y-3">
                        <label class="text-xs font-semibold text-gray-700">Test prompt</label>
                        <textarea id="ai-test-prompt" rows="5" class="w-full rounded-xl border border-gray-200 text-sm focus:ring-2 focus:ring-brand/20 focus:border-brand/40" placeholder="Example: Write a short, attractive description for fresh organic apples, 1kg pack."></textarea>
                        <p class="text-[11px] text-gray-400">This uses the same configuration that product descriptions will use.</p>
                    </div>
                    <div class="flex items-center justify-between mt-4">
                        <p id="ai-test-status" class="text-[11px] text-gray-400"></p>
                        <button id="ai-test-button" type="button" class="inline-flex items-center px-4 py-2 rounded-xl bg-gray-900 text-white text-[11px] font-semibold tracking-[0.16em] uppercase hover:bg-black transition-all disabled:opacity-60">
                            <span class="label">Run test</span>
                        </button>
                    </div>
                </div>
            </div>
            <div class="card overflow-hidden fade-card fade-card-delay-3">
                <div class="section-header">
                    <div>
                        <p class="section-title">Test Response</p>
                        <p class="section-sub">Preview the generated copy before using it.</p>
                    </div>
                </div>
                <div class="p-6 md:p-8 space-y-4">
                    <textarea id="ai-test-output" rows="9" class="w-full rounded-xl border border-gray-200 text-sm bg-gray-50 focus:outline-none" readonly></textarea>
                </div>
            </div>
        </div>

        <div class="mt-8 flex justify-end fade-card fade-card-delay-3">
            <button type="submit" class="btn-primary">
                <i class="fas fa-save mr-2 text-[11px]"></i>
                Save AI Settings
            </button>
        </div>
    </form>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var btn = document.getElementById('ai-test-button');
            var promptInput = document.getElementById('ai-test-prompt');
            var output = document.getElementById('ai-test-output');
            var status = document.getElementById('ai-test-status');

            if (btn && promptInput && output && status) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();

                    var prompt = promptInput.value.trim();
                    if (!prompt) {
                        status.textContent = 'Please write a test prompt first.';
                        status.className = 'text-[11px] text-rose-600 font-medium';
                        return;
                    }

                    btn.disabled = true;
                    status.textContent = '';
                    status.className = 'text-[11px] text-gray-400';
                    output.value = '';

                    var label = btn.querySelector('.label');
                    if (label) {
                        label.textContent = 'Generating...';
                    }

                    fetch('{{ url('/api/ai/generate-description') }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({
                            prompt: prompt,
                            max_tokens: 220
                        })
                    })
                        .then(function (res) {
                            return res.json().then(function (data) {
                                return { status: res.status, data: data };
                            });
                        })
                        .then(function (result) {
                            if (result.data && result.data.status === 'success' && result.data.data && result.data.data.text) {
                                output.value = result.data.data.text;
                                status.textContent = 'AI responded successfully.';
                                status.className = 'text-[11px] text-emerald-600 font-medium';
                            } else {
                                var message = (result.data && result.data.message) ? result.data.message : 'Failed to generate text. Please check API key and model.';
                                status.textContent = message;
                                status.className = 'text-[11px] text-rose-600 font-medium';
                            }
                        })
                        .catch(function () {
                            status.textContent = 'Network error. Please try again.';
                            status.className = 'text-[11px] text-rose-600 font-medium';
                        })
                        .finally(function () {
                            btn.disabled = false;
                            if (label) {
                                label.textContent = 'Run test';
                            }
                        });
                });
            }

            var helpToggle = document.getElementById('removebg-help-toggle');
            var helpPanel = document.getElementById('removebg-help-panel');

            if (helpToggle && helpPanel) {
                helpToggle.addEventListener('click', function () {
                    if (helpPanel.classList.contains('hidden')) {
                        helpPanel.classList.remove('hidden');
                        helpToggle.classList.add('border-emerald-300', 'bg-emerald-50/60', 'text-emerald-800');
                    } else {
                        helpPanel.classList.add('hidden');
                        helpToggle.classList.remove('border-emerald-300', 'bg-emerald-50/60', 'text-emerald-800');
                    }
                });
            }
        });
    </script>
</div>
@endsection
