@extends('admin.layouts.app')
@section('title', isset($noticia) ? 'Editar Publicación' : 'Nueva Publicación')

@section('styles')
<style>
:root { --n-blue:#1a237e; --n-gold:#ffe082; --n-purple:#4527a0; }

/* ── Hero ── */
.not-hero {
    background: linear-gradient(135deg,#0d1b6e 0%,#1a237e 45%,#4527a0 100%);
    border-radius: 20px; padding: 22px 28px;
    display: flex; align-items: center; justify-content: space-between;
    flex-wrap: wrap; gap: 16px; margin-bottom: 28px;
    box-shadow: 0 8px 32px rgba(13,27,110,.25);
}
.not-hero h1 {
    font-size: 1.35rem; font-weight: 800; color: #fff; margin: 0 0 2px;
    display: flex; align-items: center; gap: 10px;
}
.not-hero p { color: rgba(255,255,255,.55); margin: 0; font-size: .83rem; }

/* ── Form card ── */
.form-card {
    background: #fff; border-radius: 18px;
    box-shadow: 0 4px 24px rgba(0,0,0,.07);
    overflow: hidden; margin-bottom: 20px;
}
.form-card-header {
    background: linear-gradient(135deg,var(--n-blue),var(--n-purple));
    padding: 14px 22px; display: flex; align-items: center; gap: 10px;
}
.form-card-header .fch-icon {
    width: 34px; height: 34px; border-radius: 10px;
    background: rgba(255,224,130,.15); border: 1.5px solid rgba(255,224,130,.25);
    display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.form-card-header .fch-icon i { color: var(--n-gold); font-size: 16px; }
.form-card-header span { color: #fff; font-weight: 800; font-size: .95rem; }
.form-card-header small { color: rgba(255,255,255,.5); font-size:.78rem; font-weight:600; margin-left:auto; }
.form-card-body { padding: 24px 28px; }

/* ── Labels & inputs ── */
.fl { font-size: .82rem; font-weight: 700; color: #475569; margin-bottom: 6px; display: block; }
.fl .req { color: #ef4444; }
.fi {
    width: 100%; border: 1.5px solid #e2e8f0; border-radius: 10px;
    padding: 10px 14px; font-size: .88rem; color: #1e293b;
    transition: border-color .2s, box-shadow .2s; outline: none;
    background: #fff;
}
.fi:focus { border-color: var(--n-blue); box-shadow: 0 0 0 3px rgba(26,35,126,.1); }
.fi-row { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16px; margin-bottom: 18px; }
.fi-row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 18px; }
.fg { margin-bottom: 18px; }

/* ── Editor tabs ── */
.editor-tabs { display: flex; gap: 4px; margin-bottom: 6px; }
.editor-tab {
    padding: 5px 14px; font-size: 12px; font-weight: 700;
    border-radius: 8px; border: 1.5px solid #e2e8f0;
    background: #f8fafc; color: #64748b; cursor: pointer; transition: all .15s;
}
.editor-tab.active { background: var(--n-blue); color: #fff; border-color: var(--n-blue); }
.editor-wrapper { border: 1.5px solid #e2e8f0; border-radius: 10px; overflow: hidden; transition: box-shadow .2s; }
.editor-wrapper:focus-within { box-shadow: 0 0 0 3px rgba(26,35,126,.1); border-color: var(--n-blue); }

/* ── HTML raw ── */
#htmlRawArea {
    font-family: 'Cascadia Code', 'Consolas', monospace;
    font-size: 13px; background: #0f172a; color: #e2e8f0;
    border-radius: 0 0 10px 10px; border: none;
    min-height: 340px; padding: 16px; resize: vertical;
    width: 100%; display: none;
}

/* ── Imagen preview ── */
#imgPreviewWrap { position: relative; display: inline-block; margin-bottom: 10px; }
#imgPreview {
    max-height: 130px; border-radius: 10px; display: block;
    border: 2px solid #e2e8f0; box-shadow: 0 4px 12px rgba(0,0,0,.08);
}
#btnRemoveImg {
    position: absolute; top: -8px; right: -8px;
    background: #ef4444; color: #fff; border: none; border-radius: 50%;
    width: 24px; height: 24px; font-size: 12px; cursor: pointer;
    line-height: 24px; text-align: center;
}

/* ── Botones de enlace ── */
.boton-row {
    display: flex; align-items: center; gap: 10px; margin-bottom: 8px;
    padding: 12px 14px; border-radius: 12px;
    border: 1.5px solid #eee; transition: all .2s;
}
.boton-row.has-url { background: rgba(26,35,126,.04); border-color: #c5cae9; }

/* ── Popup section ── */
.popup-section {
    background: linear-gradient(135deg,#1a237e08,#7b1fa208);
    border: 2px solid #c5cae9; border-radius: 16px; padding: 20px 22px;
}

/* ── Submit bar ── */
.submit-bar {
    background: #f8faff; border-top: 1.5px solid #f1f5f9;
    padding: 18px 28px; display: flex; gap: 12px; justify-content: flex-end;
    align-items: center;
}

/* ── Char count ── */
.char-count { font-size: 11px; color: #94a3b8; text-align: right; margin-top: 3px; }

/* ── Toggle switch ── */
.toggle-label {
    display: flex; align-items: center; gap: 10px; cursor: pointer;
    background: #fff; padding: 10px 16px; border-radius: 10px;
    border: 1.5px solid #e2e8f0; transition: border-color .2s;
}
.toggle-label:hover { border-color: var(--n-blue); }
.toggle-label input[type=checkbox] { width: 18px; height: 18px; cursor: pointer; accent-color: var(--n-blue); }
.toggle-label span { font-weight: 700; color: #334155; font-size: .88rem; }
</style>
@endsection

@section('content')

{{-- ═══════ HERO ═══════ --}}
<div class="not-hero">
    <div>
        <h1>
            <div style="width:38px;height:38px;border-radius:12px;background:rgba(255,224,130,.15);border:1.5px solid rgba(255,224,130,.25);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="bi bi-newspaper" style="color:var(--n-gold);font-size:18px;"></i>
            </div>
            {{ isset($noticia) ? 'Editar Publicación' : 'Nueva Publicación' }}
        </h1>
        <p>{{ isset($noticia) ? 'Modifica los datos de la publicación existente' : 'Completa el formulario para crear una nueva publicación' }}</p>
    </div>
    <div style="display:flex;gap:10px;align-items:center;">
        <a href="{{ route('admin.noticias.index') }}"
           style="display:inline-flex;align-items:center;gap:7px;padding:10px 18px;background:rgba(255,255,255,.12);border:1.5px solid rgba(255,255,255,.3);color:#fff;border-radius:12px;font-weight:700;font-size:.85rem;text-decoration:none;transition:all .2s;"
           onmouseover="this.style.background='rgba(255,255,255,.2)'" onmouseout="this.style.background='rgba(255,255,255,.12)'">
            <i class="bi bi-arrow-left"></i> Volver
        </a>
    </div>
</div>

<form action="{{ isset($noticia) ? route('admin.noticias.update', $noticia) : route('admin.noticias.store') }}"
      method="POST" enctype="multipart/form-data" id="formNoticia">
    @csrf
    @if(isset($noticia)) @method('PUT') @endif

    {{-- Errores manejados por SweetAlert2 en el layout --}}
    {{-- Resaltado de campos inválidos --}}
    @if($errors->any())
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        @foreach($errors->keys() as $field)
        var el = document.querySelector('[name="{{ $field }}"]');
        if (el) { el.style.borderColor = '#ef4444'; el.style.boxShadow = '0 0 0 3px rgba(239,68,68,.12)'; }
        @endforeach
    });
    </script>
    @endif

    {{-- ════════════════════════════════════════════════
         SECCIÓN 1 — DATOS PRINCIPALES
    ════════════════════════════════════════════════ --}}
    <div class="form-card">
        <div class="form-card-header">
            <div class="fch-icon"><i class="bi bi-file-earmark-text-fill"></i></div>
            <span>Datos Principales</span>
            <small>Título, tipo, categoría y fecha</small>
        </div>
        <div class="form-card-body">

            {{-- Título --}}
            <div class="fg">
                <label class="fl">Título <span class="req">*</span></label>
                <input type="text" name="titulo" id="inputTitulo" class="fi"
                       value="{{ old('titulo', $noticia->titulo ?? '') }}"
                       placeholder="Título de la publicación..." required>
            </div>

            {{-- Tipo + Categoría + Fecha --}}
            <div class="fi-row">
                <div>
                    <label class="fl">Tipo <span class="req">*</span></label>
                    <select name="tipo" class="fi" required>
                        @foreach(['noticia'=>'📰 Noticia','comunicado'=>'📢 Comunicado','convocatoria'=>'📋 Convocatoria','logro'=>'🏆 Logro'] as $val => $label)
                        <option value="{{ $val }}" {{ old('tipo', $noticia->tipo ?? '') === $val ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div>
                    <label class="fl">Categoría</label>
                    <input type="text" name="categoria" class="fi"
                           value="{{ old('categoria', $noticia->categoria ?? '') }}"
                           placeholder="Ej: Olimpiadas, Eventos...">
                </div>
                <div>
                    <label class="fl">Fecha de Publicación <span class="req">*</span></label>
                    <input type="date" name="fecha_publicacion" class="fi"
                           value="{{ old('fecha_publicacion', isset($noticia) ? $noticia->fecha_publicacion->format('Y-m-d') : date('Y-m-d')) }}"
                           required>
                </div>
            </div>

            {{-- Resumen --}}
            <div class="fg">
                <label class="fl">
                    Resumen
                    <span style="font-weight:400;color:#94a3b8;font-size:.78rem;"> — aparece en tarjetas y vista previa</span>
                </label>
                <textarea name="resumen" id="resumen" class="fi"
                          rows="2" placeholder="Breve descripción para la tarjeta..."
                          oninput="document.getElementById('charCount').textContent=this.value.length"
                          style="resize:vertical;">{{ old('resumen', $noticia->resumen ?? '') }}</textarea>
                <div class="char-count"><span id="charCount">{{ strlen(old('resumen', $noticia->resumen ?? '')) }}</span> caracteres</div>
            </div>

            {{-- Opciones: Destacado + Activo --}}
            <div style="display:flex;gap:14px;flex-wrap:wrap;">
                <label class="toggle-label">
                    <input type="checkbox" name="destacado" value="1"
                           {{ old('destacado', $noticia->destacado ?? false) ? 'checked' : '' }}>
                    <i class="bi bi-star-fill" style="color:#f59e0b;"></i>
                    <span>Destacado</span>
                </label>
                <label class="toggle-label">
                    <input type="checkbox" name="activo" value="1"
                           {{ old('activo', $noticia->activo ?? true) ? 'checked' : '' }}>
                    <i class="bi bi-toggle-on" style="color:#10b981;"></i>
                    <span>Activo / Publicado</span>
                </label>
            </div>
        </div>
    </div>

    {{-- ════════════════════════════════════════════════
         SECCIÓN 2 — CONTENIDO
    ════════════════════════════════════════════════ --}}
    <div class="form-card">
        <div class="form-card-header">
            <div class="fch-icon"><i class="bi bi-pencil-square"></i></div>
            <span>Contenido</span>
            <small>Editor visual HTML (TinyMCE)</small>
        </div>
        <div class="form-card-body">
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;">
                <label class="fl mb-0">Cuerpo del artículo</label>
                <div class="editor-tabs">
                    <button type="button" class="editor-tab active" id="tabVisual" onclick="switchTab('visual')">
                        <i class="bi bi-eye me-1"></i>Visual
                    </button>
                    <button type="button" class="editor-tab" id="tabHtml" onclick="switchTab('html')">
                        <i class="bi bi-code-slash me-1"></i>HTML
                    </button>
                </div>
            </div>
            <div class="editor-wrapper">
                <textarea name="contenido" id="contenido">{{ old('contenido', $noticia->contenido ?? '') }}</textarea>
                <textarea id="htmlRawArea" spellcheck="false"
                          placeholder="<!-- Escribe HTML aquí... -->"></textarea>
            </div>
        </div>
    </div>

    {{-- ════════════════════════════════════════════════
         SECCIÓN 3 — IMAGEN
    ════════════════════════════════════════════════ --}}
    <div class="form-card">
        <div class="form-card-header">
            <div class="fch-icon"><i class="bi bi-image-fill"></i></div>
            <span>Imagen</span>
            <small>JPG · PNG · WebP — recomendado 800×500 px</small>
        </div>
        <div class="form-card-body">
            @if(isset($noticia) && $noticia->imagen)
            <div id="imgPreviewWrap">
                <img id="imgPreview" src="{{ asset('storage/'.$noticia->imagen) }}" alt="Imagen actual">
                <button type="button" id="btnRemoveImg" title="Quitar imagen" onclick="quitarImagen()">✕</button>
            </div>
            <input type="hidden" name="imagen_actual" value="{{ $noticia->imagen }}">
            @else
            <div id="imgPreviewWrap" style="display:none;">
                <img id="imgPreview" src="" alt="Vista previa">
                <button type="button" id="btnRemoveImg" title="Quitar imagen" onclick="quitarImagen()">✕</button>
            </div>
            @endif
            <input type="file" name="imagen" id="inputImagen" class="fi" accept="image/*"
                   onchange="previewImagen(this)" style="max-width:420px;">
            <div style="font-size:.78rem;color:#94a3b8;margin-top:6px;"><i class="bi bi-info-circle me-1"></i>Formatos: JPG, PNG, WebP. Tamaño recomendado: 800×500 px.</div>
        </div>
    </div>

    {{-- ════════════════════════════════════════════════
         SECCIÓN 4 — BOTONES DE ENLACE
    ════════════════════════════════════════════════ --}}
    <div class="form-card">
        <div class="form-card-header">
            <div class="fch-icon"><i class="bi bi-link-45deg"></i></div>
            <span>Botones de Enlace</span>
            <small>Hasta 5 botones — solo aparecen si tienen URL</small>
        </div>
        <div class="form-card-body">
            @php
                $paletaColores   = ['#1565c0','#2e7d32','#ad1457','#e65100','#6a1b9a'];
                $botonesGuardados = old('boton_url') ? null : ($noticia->botones ?? null);
            @endphp

            <div id="botonesContainer">
                @for($i = 0; $i < 5; $i++)
                @php
                    $btn      = $botonesGuardados[$i] ?? null;
                    $textoVal = old("boton_texto.$i", $btn['texto'] ?? '');
                    $urlVal   = old("boton_url.$i",   $btn['url']   ?? '');
                    $colorVal = old("boton_color.$i", $btn['color'] ?? $paletaColores[$i]);
                @endphp
                <div class="boton-row {{ $urlVal ? 'has-url' : '' }}" id="boton-row-{{ $i }}">

                    {{-- Número --}}
                    <div style="flex-shrink:0;">
                        <span class="btn-num-badge"
                              style="display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:50%;background:{{ $colorVal }};color:#fff;font-size:12px;font-weight:800;">
                            {{ $i + 1 }}
                        </span>
                    </div>

                    {{-- Color picker --}}
                    <div style="flex-shrink:0;" title="Color del botón">
                        <input type="color" name="boton_color[{{ $i }}]"
                               value="{{ $colorVal }}"
                               class="boton-color-input" data-idx="{{ $i }}"
                               style="width:36px;height:36px;border:none;border-radius:8px;cursor:pointer;padding:2px;background:transparent;"
                               onchange="actualizarColorBoton({{ $i }}, this.value)">
                    </div>

                    {{-- Texto --}}
                    <div style="flex:1;min-width:0;">
                        <input type="text" name="boton_texto[{{ $i }}]"
                               value="{{ $textoVal }}"
                               class="fi" style="padding:7px 12px;font-size:.84rem;"
                               placeholder="Texto del botón (ej: Ver resultados →)">
                    </div>

                    {{-- URL --}}
                    <div style="flex:2;min-width:0;">
                        <div style="position:relative;">
                            <span style="position:absolute;left:10px;top:50%;transform:translateY(-50%);color:#94a3b8;font-size:13px;">
                                <i class="bi bi-link"></i>
                            </span>
                            <input type="url" name="boton_url[{{ $i }}]"
                                   value="{{ $urlVal }}"
                                   class="fi boton-url-input" data-idx="{{ $i }}"
                                   placeholder="https://... (vacío = no mostrar)"
                                   style="padding:7px 12px 7px 30px;font-size:.84rem;"
                                   oninput="toggleBotonRow({{ $i }}, this.value)">
                        </div>
                    </div>

                    {{-- Preview --}}
                    <div style="flex-shrink:0;" id="preview-btn-{{ $i }}">
                        @if($urlVal)
                        <span style="display:inline-block;padding:5px 14px;border-radius:50px;background:{{ $colorVal }};color:#fff;font-size:12px;font-weight:700;white-space:nowrap;max-width:140px;overflow:hidden;text-overflow:ellipsis;">
                            {{ $textoVal ?: 'Ver más' }}
                        </span>
                        @else
                        <span style="color:#cbd5e1;font-size:12px;"><i class="bi bi-dash-circle"></i> vacío</span>
                        @endif
                    </div>

                </div>
                @endfor
            </div>

            <div style="font-size:11.5px;color:#94a3b8;margin-top:8px;">
                <i class="bi bi-palette me-1"></i>Haz clic en el círculo de color para cambiarlo. Los botones sin URL no aparecen en la noticia pública.
            </div>
        </div>
    </div>

    {{-- ════════════════════════════════════════════════
         SECCIÓN 5 — POPUP CAROUSEL
    ════════════════════════════════════════════════ --}}
    <div class="form-card">
        <div class="form-card-header">
            <div class="fch-icon"><i class="bi bi-megaphone-fill"></i></div>
            <span>Popup Carousel</span>
            <small>Ventana emergente en la página pública</small>
            @if(isset($noticia) && $noticia->mostrar_popup)
            <span style="background:#4caf50;color:#fff;padding:3px 12px;border-radius:50px;font-size:11px;font-weight:800;margin-left:auto;">
                <i class="bi bi-broadcast-pin me-1"></i>ACTIVO EN POPUP
            </span>
            @endif
        </div>
        <div class="form-card-body">
            <div class="popup-section">
                <div style="font-size:.85rem;color:#7b1fa2;margin-bottom:16px;">
                    <i class="bi bi-info-circle me-1"></i>
                    Solo <strong>Noticias</strong> y <strong>Comunicados</strong> aparecen en el popup. Se muestra al entrar al sitio web.
                </div>
                <div style="display:flex;align-items:center;gap:20px;flex-wrap:wrap;">
                    <label class="toggle-label">
                        <input type="checkbox" name="mostrar_popup" value="1" id="chkPopup"
                               {{ old('mostrar_popup', $noticia->mostrar_popup ?? false) ? 'checked' : '' }}
                               onchange="togglePopupConfig(this.checked)">
                        <i class="bi bi-megaphone" style="color:#7b1fa2;"></i>
                        <span style="color:#1a237e;">Mostrar en Popup Carousel</span>
                    </label>

                    <div id="popupOrdenWrap"
                         style="{{ old('mostrar_popup', $noticia->mostrar_popup ?? false) ? '' : 'opacity:.4;pointer-events:none;' }}display:flex;align-items:center;gap:8px;">
                        <label style="font-size:.83rem;font-weight:700;color:#555;margin:0;">
                            <i class="bi bi-sort-numeric-up me-1"></i>Orden en carrusel:
                        </label>
                        <input type="number" name="popup_orden" min="0" max="99"
                               value="{{ old('popup_orden', $noticia->popup_orden ?? 0) }}"
                               class="fi" style="width:70px;padding:7px 10px;text-align:center;font-weight:700;">
                        <small style="color:#94a3b8;font-size:11px;">(0 = primero)</small>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- ═══════ SUBMIT BAR ═══════ --}}
    <div class="submit-bar">
        <a href="{{ route('admin.noticias.index') }}"
           style="display:inline-flex;align-items:center;gap:7px;padding:11px 20px;background:#f1f5f9;color:#64748b;border-radius:12px;font-weight:700;text-decoration:none;font-size:.88rem;transition:all .2s;"
           onmouseover="this.style.background='#e2e8f0'" onmouseout="this.style.background='#f1f5f9'">
            <i class="bi bi-x-lg"></i> Cancelar
        </a>
        <button type="submit" id="btnSubmit"
                style="display:inline-flex;align-items:center;gap:8px;padding:12px 28px;background:linear-gradient(135deg,#1a237e,#4527a0);color:#fff;border:none;border-radius:14px;font-weight:800;font-size:.9rem;cursor:pointer;box-shadow:0 4px 16px rgba(26,35,126,.3);transition:all .2s;"
                onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform=''">
            <i class="bi bi-save-fill"></i>
            {{ isset($noticia) ? 'Actualizar Publicación' : 'Guardar Publicación' }}
        </button>
    </div>

</form>
@endsection

@section('scripts')
{{-- TinyMCE --}}
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
// ── TinyMCE ────────────────────────────────────────────
tinymce.init({
    selector: '#contenido',
    language: 'es_ES',
    language_url: '{{ asset("js/tinymce/langs/es_ES.js") }}',
    convert_urls: false,
    relative_urls: false,
    remove_script_host: false,
    height: 440,
    menubar: 'file edit view insert format tools table',
    plugins: [
        'advlist','autolink','lists','link','image','charmap',
        'anchor','searchreplace','visualblocks','code','fullscreen',
        'insertdatetime','media','table','help','wordcount',
        'emoticons','preview'
    ],
    toolbar:
        'undo redo | styles | bold italic underline strikethrough | ' +
        'forecolor backcolor | alignleft aligncenter alignright alignjustify | ' +
        'bullist numlist outdent indent | link image media | ' +
        'blockquote code | removeformat | fullscreen preview | help',
    toolbar_mode: 'sliding',
    content_style: `
        body {
            font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            font-size: 15px; line-height: 1.7; color: #1a202c;
            padding: 16px 24px; max-width: 860px; margin: 0 auto;
        }
        h1,h2,h3,h4 { font-weight: 700; color: #1a237e; margin-top: 1.4em; }
        a { color: #1565c0; }
        img { max-width: 100%; border-radius: 8px; }
        blockquote { border-left: 4px solid #1a237e; padding: 8px 16px; background: #f0f4ff; margin: 16px 0; color: #333; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #e2e8f0; padding: 8px 12px; }
        th { background: #1a237e; color: #ffe082; }
        code { background: #f1f5f9; padding: 2px 6px; border-radius: 4px; font-family: monospace; }
        pre  { background: #0f172a; color: #e2e8f0; padding: 16px; border-radius: 8px; overflow: auto; }
    `,
    images_upload_handler: function (blobInfo) {
        return new Promise(resolve => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result);
            reader.readAsDataURL(blobInfo.blob());
        });
    },
    style_formats: [
        { title: 'Párrafo',    block: 'p' },
        { title: 'Título 1',   block: 'h1' },
        { title: 'Título 2',   block: 'h2' },
        { title: 'Título 3',   block: 'h3' },
        { title: 'Cita',       block: 'blockquote' },
        { title: 'Código',     block: 'pre' },
        { title: 'Resaltado',  inline: 'span', styles: { 'background-color': '#fffde7', 'border-radius': '3px', 'padding': '1px 4px' } },
    ],
    setup: function (editor) {
        editor.on('change input', function () { editor.save(); });
    },
    promotion: false,
    branding: false,
});

// ── Tabs Visual / HTML ─────────────────────────────────
let modoActual = 'visual';

function switchTab(modo) {
    const raw  = document.getElementById('htmlRawArea');
    const tabV = document.getElementById('tabVisual');
    const tabH = document.getElementById('tabHtml');
    const editorContainer = document.querySelector('.tox-tinymce');

    if (modo === 'html') {
        const ed = tinymce.get('contenido');
        if (ed) raw.value = ed.getContent();
        raw.style.display = 'block';
        if (editorContainer) editorContainer.style.display = 'none';
        tabH.classList.add('active'); tabV.classList.remove('active');
        modoActual = 'html';
    } else {
        const ed = tinymce.get('contenido');
        if (ed && raw.value.trim() !== '') ed.setContent(raw.value);
        raw.style.display = 'none';
        if (editorContainer) editorContainer.style.display = '';
        tabV.classList.add('active'); tabH.classList.remove('active');
        modoActual = 'visual';
    }
}

document.getElementById('formNoticia').addEventListener('submit', function () {
    const ed = tinymce.get('contenido');
    if (modoActual === 'html') {
        const raw = document.getElementById('htmlRawArea').value;
        if (ed) { ed.setContent(raw); ed.save(); }
    } else {
        if (ed) ed.save();
    }
    // Feedback visual en botón
    const btn = document.getElementById('btnSubmit');
    btn.textContent = 'Guardando...';
    btn.disabled = true;
});

// ── Imagen preview ─────────────────────────────────────
function previewImagen(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = e => {
            document.getElementById('imgPreview').src = e.target.result;
            document.getElementById('imgPreviewWrap').style.display = 'inline-block';
        };
        reader.readAsDataURL(input.files[0]);
    }
}
function quitarImagen() {
    document.getElementById('inputImagen').value = '';
    document.getElementById('imgPreviewWrap').style.display = 'none';
    const h = document.querySelector('[name=imagen_actual]');
    if (h) h.value = '';
}

// ── Char count ─────────────────────────────────────────
document.getElementById('charCount').textContent =
    document.getElementById('resumen').value.length;

// ── Botones de enlace ──────────────────────────────────
function actualizarColorBoton(idx, color) {
    const badge = document.querySelector(`#boton-row-${idx} .btn-num-badge`);
    if (badge) badge.style.background = color;
    actualizarPreviewBoton(idx);
}

function actualizarPreviewBoton(idx) {
    const row     = document.getElementById(`boton-row-${idx}`);
    const urlEl   = row.querySelector('.boton-url-input');
    const textoEl = row.querySelectorAll('input[type=text]')[0];
    const colorEl = row.querySelector('input[type=color]');
    const preview = document.getElementById(`preview-btn-${idx}`);
    const url     = urlEl   ? urlEl.value.trim()             : '';
    const texto   = textoEl ? (textoEl.value.trim() || 'Ver más') : 'Ver más';
    const color   = colorEl ? colorEl.value                  : '#1565c0';

    if (url) {
        preview.innerHTML = `<span style="display:inline-block;padding:5px 14px;border-radius:50px;background:${color};color:#fff;font-size:12px;font-weight:700;white-space:nowrap;max-width:140px;overflow:hidden;text-overflow:ellipsis;">${texto}</span>`;
    } else {
        preview.innerHTML = `<span style="color:#cbd5e1;font-size:12px;"><i class="bi bi-dash-circle"></i> vacío</span>`;
    }
}

function toggleBotonRow(idx, valor) {
    const row = document.getElementById(`boton-row-${idx}`);
    if (valor.trim() !== '') {
        row.classList.add('has-url');
    } else {
        row.classList.remove('has-url');
        row.style.background = '';
        row.style.borderColor = '';
    }
    actualizarPreviewBoton(idx);
}

document.querySelectorAll('.boton-row input[type=text]').forEach(input => {
    input.addEventListener('input', function () {
        const idx = parseInt(this.closest('.boton-row').id.replace('boton-row-', ''));
        actualizarPreviewBoton(idx);
    });
});

// ── Popup carousel ─────────────────────────────────────
function togglePopupConfig(checked) {
    const wrap = document.getElementById('popupOrdenWrap');
    wrap.style.opacity      = checked ? '1'    : '.4';
    wrap.style.pointerEvents= checked ? 'auto' : 'none';
}
</script>
@endsection
