<div class="flex items-center gap-3 mb-6">
    <a href="{{ route('kb.admin.index') }}" class="text-gray-400 hover:text-gray-600">
        <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
        </svg>
    </a>
    <h1 class="text-2xl font-bold text-gray-900">
        {{ $article ? 'Editar artículo' : 'Nuevo artículo' }}
    </h1>
    @if($article && $article->status === 'published')
    <a href="{{ route('kb.show', $article->slug) }}" target="_blank"
       class="ml-auto text-sm text-blue-600 hover:underline">Ver publicado →</a>
    @endif
</div>

<form method="POST"
      action="{{ $article ? route('kb.admin.update', $article) : route('kb.admin.store') }}">
    @csrf
    @if($article) @method('PATCH') @endif

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

        {{-- Editor principal --}}
        <div class="lg:col-span-2 space-y-5">

            {{-- Título --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    Título <span class="text-red-500">*</span>
                </label>
                <input type="text" name="title" id="title"
                       value="{{ old('title', $article?->title) }}"
                       placeholder="Título claro y descriptivo del artículo"
                       class="w-full rounded-lg border-gray-300 text-base font-medium focus:ring-blue-500 focus:border-blue-500 @error('title') border-red-500 @enderror">
                @error('title') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
            </div>

            {{-- Editor enriquecido (EasyMDE -> Markdown -> HTML) --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    Contenido <span class="text-red-500">*</span>
                </label>

                {{-- Toolbar --}}
                <div id="editor-toolbar" class="flex flex-wrap gap-1 p-2 bg-gray-50 rounded-t-lg border border-b-0 border-gray-300">
                    @foreach([
                        ['cmd'=>'bold',      'icon'=>'B',  'title'=>'Negrita'],
                        ['cmd'=>'italic',    'icon'=>'I',  'title'=>'Cursiva'],
                        ['cmd'=>'h2',        'icon'=>'H2', 'title'=>'Título 2'],
                        ['cmd'=>'h3',        'icon'=>'H3', 'title'=>'Título 3'],
                        ['cmd'=>'ul',        'icon'=>'≡',  'title'=>'Lista'],
                        ['cmd'=>'ol',        'icon'=>'1.', 'title'=>'Lista numerada'],
                        ['cmd'=>'code',      'icon'=>'<>', 'title'=>'Código'],
                        ['cmd'=>'blockquote','icon'=>'❝',  'title'=>'Cita'],
                        ['cmd'=>'hr',        'icon'=>'—',  'title'=>'Separador'],
                    ] as $btn)
                    <button type="button"
                            onclick="execCmd('{{ $btn['cmd'] }}')"
                            title="{{ $btn['title'] }}"
                            class="px-2.5 py-1 text-xs font-medium text-gray-600 bg-white border border-gray-300 rounded hover:bg-gray-100 transition">
                        {{ $btn['icon'] }}
                    </button>
                    @endforeach
                </div>

                <textarea id="content-editor" name="content"
                          class="w-full min-h-96 rounded-b-lg border border-gray-300 p-4 text-sm font-mono focus:ring-blue-500 focus:border-blue-500"
                          placeholder="Escribe el contenido del artículo en HTML o texto plano...">{{ old('content', $article?->content) }}</textarea>

                <p class="text-xs text-gray-400 mt-1">
                    Puedes usar HTML: &lt;h2&gt;, &lt;p&gt;, &lt;ul&gt;&lt;li&gt;, &lt;code&gt;, &lt;strong&gt;, &lt;em&gt;, etc.
                </p>
                @error('content') <p class="text-red-500 text-xs mt-1">{{ $message }}</p> @enderror
            </div>

        </div>

        {{-- Panel lateral --}}
        <div class="space-y-5">

            {{-- Publicación --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <h3 class="text-sm font-semibold text-gray-900 mb-4">Publicación</h3>
                <div class="space-y-4">
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">Estado</label>
                        <select name="status" class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                            <option value="draft"     {{ old('status',$article?->status ?? 'draft') === 'draft'     ? 'selected' : '' }}>📝 Borrador</option>
                            <option value="published" {{ old('status',$article?->status) === 'published' ? 'selected' : '' }}>✅ Publicado</option>
                            <option value="archived"  {{ old('status',$article?->status) === 'archived'  ? 'selected' : '' }}>📦 Archivado</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">Categoría</label>
                        <select name="category_id" class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                            <option value="">— Sin categoría —</option>
                            @foreach($categories as $cat)
                            <option value="{{ $cat->id }}" {{ old('category_id',$article?->category_id) == $cat->id ? 'selected' : '' }}>
                                {{ $cat->name }}
                            </option>
                            @foreach($cat->children as $child)
                            <option value="{{ $child->id }}" {{ old('category_id',$article?->category_id) == $child->id ? 'selected' : '' }}>
                                &nbsp;&nbsp;└ {{ $child->name }}
                            </option>
                            @endforeach
                            @endforeach
                        </select>
                    </div>
                    <div>
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input type="checkbox" name="featured" value="1"
                                   {{ old('featured', $article?->featured) ? 'checked' : '' }}
                                   class="rounded border-gray-300 text-blue-600">
                            <span class="text-sm text-gray-700">⭐ Artículo destacado</span>
                        </label>
                    </div>
                </div>
                <div class="mt-4 pt-4 border-t border-gray-100 flex flex-col gap-2">
                    <button type="submit"
                            class="w-full py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition">
                        {{ $article ? 'Guardar cambios' : 'Crear artículo' }}
                    </button>
                    <a href="{{ route('kb.admin.index') }}"
                       class="w-full py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-200 transition text-center">
                        Cancelar
                    </a>
                    @if($article && auth()->user()->hasAnyRole(['admin','superadmin']))
                    <form method="POST" action="{{ route('kb.admin.destroy', $article) }}"
                          onsubmit="return confirm('¿Eliminar este artículo?')">
                        @csrf @method('DELETE')
                        <button type="submit"
                                class="w-full py-2 bg-red-50 text-red-600 text-sm font-medium rounded-lg hover:bg-red-100 transition">
                            Eliminar
                        </button>
                    </form>
                    @endif
                </div>
            </div>

            {{-- Tags --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <label class="block text-sm font-semibold text-gray-900 mb-2">Etiquetas</label>
                <input type="text" name="tags" value="{{ old('tags', $article?->tags) }}"
                       placeholder="correo, contraseña, red (separadas por coma)"
                       class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                <p class="text-xs text-gray-400 mt-1">Separadas por coma. Mejoran la búsqueda.</p>
            </div>

            {{-- Stats (solo al editar) --}}
            @if($article)
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <h3 class="text-sm font-semibold text-gray-900 mb-3">Estadísticas</h3>
                <dl class="space-y-2">
                    <div class="flex justify-between text-xs">
                        <dt class="text-gray-500">Vistas</dt>
                        <dd class="font-semibold text-gray-900">{{ $article->views }}</dd>
                    </div>
                    <div class="flex justify-between text-xs">
                        <dt class="text-gray-500">👍 Útil</dt>
                        <dd class="font-semibold text-green-600">{{ $article->helpful_yes }}</dd>
                    </div>
                    <div class="flex justify-between text-xs">
                        <dt class="text-gray-500">👎 No útil</dt>
                        <dd class="font-semibold text-red-500">{{ $article->helpful_no }}</dd>
                    </div>
                    @if($article->helpful_rate !== null)
                    <div class="flex justify-between text-xs">
                        <dt class="text-gray-500">Tasa de utilidad</dt>
                        <dd class="font-semibold {{ $article->helpful_rate >= 70 ? 'text-green-600' : 'text-red-500' }}">
                            {{ $article->helpful_rate }}%
                        </dd>
                    </div>
                    @endif
                    <div class="flex justify-between text-xs">
                        <dt class="text-gray-500">Publicado</dt>
                        <dd class="text-gray-700">{{ $article->published_at?->format('d/m/Y') ?? '—' }}</dd>
                    </div>
                </dl>
            </div>
            @endif
        </div>
    </div>
</form>

<script>
function execCmd(cmd) {
    const ta = document.getElementById('content-editor');
    const start = ta.selectionStart;
    const end   = ta.selectionEnd;
    const sel   = ta.value.substring(start, end);

    const wrap = {
        bold:        ['<strong>', '</strong>'],
        italic:      ['<em>', '</em>'],
        code:        ['<code>', '</code>'],
        blockquote:  ['<blockquote>', '</blockquote>'],
        h2:          ['<h2>', '</h2>'],
        h3:          ['<h3>', '</h3>'],
    };
    const block = {
        ul: `<ul>\n  <li>${sel || 'Elemento'}</li>\n</ul>`,
        ol: `<ol>\n  <li>${sel || 'Elemento'}</li>\n</ol>`,
        hr: '<hr>',
    };

    let replacement;
    if (wrap[cmd])  replacement = wrap[cmd][0] + (sel || 'texto') + wrap[cmd][1];
    else if (block[cmd]) replacement = block[cmd];
    else return;

    ta.setRangeText(replacement, start, end, 'end');
    ta.focus();
}
</script>
