@php
    $selectedCategorias = old('categoria_ids');
    if ($selectedCategorias === null && isset($servico?->cds_tipo)) {
        $selectedCategorias = collect(explode(';', (string) $servico->cds_tipo))
            ->filter()
            ->map(fn ($id) => (int) $id)
            ->values()
            ->all();
    }
    $selectedCategorias = collect($selectedCategorias ?? [])->map(fn ($id) => (int) $id)->all();
@endphp

{{-- Google Fonts --}}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Serif+Display:ital@0;1&family=DM+Sans:opsz,wght@9..40,300;9..40,400;9..40,500;9..40,600&display=swap" rel="stylesheet">

<style>
    :root {
        --c-bg:        #F7F5F2;
        --c-surface:   #FFFFFF;
        --c-border:    #E2DDD8;
        --c-border-focus: #2C2C2C;
        --c-text:      #1A1A1A;
        --c-muted:     #6B6560;
        --c-accent:    #C9622F;
        --c-accent-lt: #F5EAE3;
        --c-dark:      #1E1C1A;
        --c-chip-bg:   #F0EDE9;
        --radius-sm:   6px;
        --radius-md:   10px;
        --radius-lg:   14px;
        --shadow-sm:   0 1px 3px rgba(0,0,0,.06), 0 1px 2px rgba(0,0,0,.04);
        --shadow-md:   0 4px 12px rgba(0,0,0,.08);
        --font-display: 'DM Serif Display', Georgia, serif;
        --font-body:    'DM Sans', system-ui, sans-serif;
        --transition:   0.18s ease;
    }

    .cs-form-wrap {
        font-family: var(--font-body);
        color: var(--c-text);
        border-radius: var(--radius-lg);
        margin: 0 auto;
    }

    /* ── Section headings ───────────────────────────────── */
    .cs-section {
        margin-bottom: 2rem;
    }
    .cs-section-label {
        font-family: var(--font-body);
        font-size: 0.6875rem;
        font-weight: 600;
        letter-spacing: .12em;
        text-transform: uppercase;
        color: var(--c-accent);
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    .cs-section-label::after {
        content: '';
        flex: 1;
        height: 1px;
        background: var(--c-border);
    }

    /* ── Field groups ───────────────────────────────────── */
    .cs-grid {
        display: grid;
        gap: 1.125rem;
    }
    .cs-grid-2 { grid-template-columns: 1fr 1fr; }
    .cs-grid-3 { grid-template-columns: 1fr 1fr 1fr; }

    @media (max-width: 640px) {
        .cs-grid-2,
        .cs-grid-3 { grid-template-columns: 1fr; }
        .cs-form-wrap { padding: 1.25rem; }
    }

    /* ── Label ──────────────────────────────────────────── */
    .cs-label {
        display: block;
        font-size: 0.8125rem;
        font-weight: 500;
        color: var(--c-muted);
        margin-bottom: 0.4rem;
        letter-spacing: 0.01em;
    }

    /* ── Inputs & Textareas ─────────────────────────────── */
    .cs-input,
    .cs-select,
    .cs-textarea {
        width: 100%;
        background: var(--c-surface);
        border: 1.5px solid var(--c-border);
        border-radius: var(--radius-sm);
        padding: 0.6rem 0.875rem;
        font-family: var(--font-body);
        font-size: 0.9375rem;
        color: var(--c-text);
        transition: border-color var(--transition), box-shadow var(--transition);
        box-shadow: var(--shadow-sm);
        outline: none;
        appearance: none;
        -webkit-appearance: none;
        box-sizing: border-box;
    }
    .cs-input:focus,
    .cs-select:focus,
    .cs-textarea:focus {
        border-color: var(--c-border-focus);
        box-shadow: 0 0 0 3px rgba(44,44,44,.08);
    }
    .cs-input::placeholder,
    .cs-textarea::placeholder { color: #C4BFB9; }

    .cs-textarea { resize: vertical; line-height: 1.55; }

    /* ── Select custom arrow ────────────────────────────── */
    .cs-select-wrap { position: relative; }
    .cs-select-wrap::after {
        content: '';
        pointer-events: none;
        position: absolute;
        right: 0.875rem;
        top: 50%;
        transform: translateY(-50%);
        width: 0; height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-top: 6px solid var(--c-muted);
    }
    .cs-select { padding-right: 2.25rem; cursor: pointer; }

    /* ── Title input (big) ──────────────────────────────── */
    .cs-input-title {
        font-family: var(--font-display);
        font-size: 1.35rem;
        padding: 0.7rem 0.875rem;
        letter-spacing: -0.01em;
    }

    /* ── Status pill select ─────────────────────────────── */
    .cs-status-wrap { position: relative; }
    .cs-status-wrap::after {
        content: '';
        pointer-events: none;
        position: absolute;
        right: 0.875rem;
        top: 50%;
        transform: translateY(-50%);
        width: 0; height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-top: 6px solid var(--c-muted);
    }
    .cs-status {
        padding-left: 2.25rem !important;
        background-color: var(--c-surface);
    }
    .cs-status-dot {
        position: absolute;
        left: 0.875rem;
        top: 50%;
        transform: translateY(-50%);
        width: 9px; height: 9px;
        border-radius: 50%;
        background: #52C97A;
        pointer-events: none;
        transition: background var(--transition);
    }
    .cs-status[data-status="1"] ~ .cs-status-dot { background: #F0B429; }
    .cs-status[data-status="2"] ~ .cs-status-dot { background: #CBD5E0; }
    .cs-status[data-status="3"] ~ .cs-status-dot { background: #52C97A; }

    /* ── Checkboxes / category chips ───────────────────── */
    .cs-chip-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
    }
    .cs-chip {
        display: inline-flex;
        align-items: center;
        gap: 0.45rem;
        padding: 0.35rem 0.75rem;
        border-radius: 100px;
        border: 1.5px solid var(--c-border);
        background: var(--c-chip-bg);
        cursor: pointer;
        font-size: 0.8125rem;
        font-weight: 500;
        color: var(--c-muted);
        transition: all var(--transition);
        user-select: none;
    }
    .cs-chip:hover {
        border-color: var(--c-accent);
        color: var(--c-accent);
        background: var(--c-accent-lt);
    }
    .cs-chip input[type="checkbox"] { display: none; }
    .cs-chip-dot {
        width: 7px; height: 7px;
        border-radius: 50%;
        border: 1.5px solid currentColor;
        flex-shrink: 0;
        transition: background var(--transition);
    }
    .cs-chip input[type="checkbox"]:checked ~ .cs-chip-dot {
        background: currentColor;
    }
    .cs-chip:has(input:checked) {
        border-color: var(--c-accent);
        color: var(--c-accent);
        background: var(--c-accent-lt);
    }

    /* ── Divider ────────────────────────────────────────── */
    .cs-divider {
        border: none;
        border-top: 1px solid var(--c-border);
        margin: 2rem 0;
    }

    /* ── Field card (for icon+input pairs) ─────────────── */
    .cs-field { display: flex; flex-direction: column; }

    /* ── Footer actions ─────────────────────────────────── */
    .cs-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 2.5rem;
        padding-top: 1.5rem;
        border-top: 1px solid var(--c-border);
        gap: 1rem;
    }
    .cs-btn {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.65rem 1.35rem;
        border-radius: var(--radius-sm);
        font-family: var(--font-body);
        font-size: 0.9rem;
        font-weight: 500;
        cursor: pointer;
        border: none;
        text-decoration: none;
        transition: all var(--transition);
        white-space: nowrap;
    }
    .cs-btn-ghost {
        background: transparent;
        color: var(--c-muted);
        border: 1.5px solid var(--c-border);
    }
    .cs-btn-ghost:hover {
        border-color: var(--c-text);
        color: var(--c-text);
        background: var(--c-surface);
    }
    .cs-btn-primary {
        background: var(--c-dark);
        color: #fff;
        box-shadow: var(--shadow-sm);
    }
    .cs-btn-primary:hover {
        background: var(--c-accent);
        transform: translateY(-1px);
        box-shadow: 0 6px 16px rgba(201,98,47,.25);
    }

    /* ── Info badge ─────────────────────────────────────── */
    .cs-badge {
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        font-size: 0.75rem;
        color: var(--c-muted);
        background: var(--c-chip-bg);
        border: 1px solid var(--c-border);
        border-radius: 100px;
        padding: 0.2rem 0.65rem;
    }

    /* ── Span helper ────────────────────────────────────── */
    .cs-span-full { grid-column: 1 / -1; }
</style>

<div class="cs-form-wrap">

    {{-- ── 1. Identificação ────────────────────────────────── --}}
    <div class="cs-section">
        <div class="cs-section-label">Identificação</div>
        <div class="cs-grid cs-grid-2" style="grid-template-columns: 2fr 1fr;">

            <div class="cs-field">
                <label class="cs-label">{{ __('Título do serviço') }}</label>
                <input
                    type="text"
                    name="cds_titulo"
                    class="cs-input cs-input-title"
                    required
                    placeholder="Ex.: Alvará de funcionamento…"
                    value="{{ old('cds_titulo', $servico->cds_titulo ?? '') }}"
                >
            </div>

            <div class="cs-field">
                <label class="cs-label">{{ __('Status de publicação') }}</label>
                <div class="cs-select-wrap cs-status-wrap">
                    <select
                        class="cs-select cs-status"
                        name="cds_status"
                        required
                        id="statusSelect"
                        onchange="updateStatusDot(this)"
                    >
                        <option value="3" @selected(old('cds_status', $servico->cds_status ?? '3') === '3')>{{ __('Publicado') }}</option>
                        <option value="1" @selected(old('cds_status', $servico->cds_status ?? '3') === '1')>{{ __('Rascunho') }}</option>
                        <option value="2" @selected(old('cds_status', $servico->cds_status ?? '3') === '2')>{{ __('Inativo') }}</option>
                    </select>
                    <span class="cs-status-dot" id="statusDot"></span>
                </div>
            </div>

        </div>
    </div>

    {{-- ── 2. Organização ───────────────────────────────────── --}}
    <div class="cs-section">
        <div class="cs-section-label">Organização</div>

        <div class="cs-grid cs-grid-2" style="margin-bottom: 1.25rem;">
            <div class="cs-field">
                <label class="cs-label">{{ __('Secretaria responsável') }}</label>
                <div class="cs-select-wrap">
                    <select class="cs-select" name="cds_secretaria">
                        <option value="">{{ __('Selecione…') }}</option>
                        @foreach($secretarias as $secretaria)
                            <option value="{{ $secretaria->id }}" @selected(old('cds_secretaria', $servico->cds_secretaria ?? '') === $secretaria->id)>
                                {{ $secretaria->name }} ({{ $secretaria->abbreviation }})
                            </option>
                        @endforeach
                    </select>
                </div>
            </div>

            <div class="cs-field">
                <label class="cs-label">{{ __('Categoria principal') }}</label>
                <div class="cs-select-wrap">
                    <select class="cs-select" name="categoria_principal_id">
                        <option value="">{{ __('Selecione…') }}</option>
                        @foreach($tipos as $tipo)
                            <option value="{{ $tipo->id_tipo }}" @selected((int) old('categoria_principal_id', $servico->categoria_principal_id ?? 0) === (int) $tipo->id_tipo)>
                                {{ $tipo->tip_descricao }}
                            </option>
                        @endforeach
                    </select>
                </div>
            </div>
        </div>

        <div class="cs-field">
            <label class="cs-label" style="margin-bottom:.65rem;">
                {{ __('Categorias adicionais') }}
                <span class="cs-badge" style="margin-left:.5rem;">marque uma ou mais</span>
            </label>
            <div class="cs-chip-grid">
                @foreach($tipos as $tipo)
                    <label class="cs-chip">
                        <input
                            type="checkbox"
                            name="categoria_ids[]"
                            value="{{ $tipo->id_tipo }}"
                            @checked(in_array((int) $tipo->id_tipo, $selectedCategorias, true))
                        >
                        <span class="cs-chip-dot"></span>
                        {{ $tipo->tip_descricao }}
                    </label>
                @endforeach
            </div>
        </div>
    </div>

    {{-- ── 3. Descrição ─────────────────────────────────────── --}}
    <div class="cs-section">
        <div class="cs-section-label">Descrição</div>
        <div class="cs-field">
            <label class="cs-label">{{ __('Descrição geral do serviço') }}</label>
            <textarea name="cds_descricao" rows="5" class="cs-textarea" placeholder="Descreva o serviço de forma clara e objetiva…">{{ old('cds_descricao', $servico->cds_descricao ?? '') }}</textarea>
        </div>
    </div>

    {{-- ── 4. Localização & Contato ─────────────────────────── --}}
    <div class="cs-section">
        <div class="cs-section-label">Localização &amp; Contato</div>
        <div class="cs-grid cs-grid-2">

            <div class="cs-field">
                <label class="cs-label">{{ __('Setor') }}</label>
                <textarea name="cds_setor" rows="2" class="cs-textarea" placeholder="Setor responsável…">{{ old('cds_setor', $servico->cds_setor ?? '') }}</textarea>
            </div>
            <div class="cs-field">
                <label class="cs-label">{{ __('Local(is) de entrada') }}</label>
                <textarea name="cds_entrada" rows="2" class="cs-textarea" placeholder="Onde o cidadão deve comparecer…">{{ old('cds_entrada', $servico->cds_entrada ?? '') }}</textarea>
            </div>

            <div class="cs-field">
                <label class="cs-label">{{ __('Telefone') }}</label>
                <input type="text" name="cds_telefone" class="cs-input" placeholder="(00) 0000-0000" value="{{ old('cds_telefone', $servico->cds_telefone ?? '') }}">
            </div>
            <div class="cs-field">
                <label class="cs-label">{{ __('E-mail') }}</label>
                <input type="email" name="cds_email" class="cs-input" placeholder="contato@prefeitura.gov.br" value="{{ old('cds_email', $servico->cds_email ?? '') }}">
            </div>

            <div class="cs-field">
                <label class="cs-label">{{ __('URL de solicitação online') }}</label>
                <input type="url" name="cds_solicitacao" class="cs-input" placeholder="https://…" value="{{ old('cds_solicitacao', $servico->cds_solicitacao ?? '') }}">
            </div>
            <div class="cs-field">
                <label class="cs-label">{{ __('URL do mapa') }}</label>
                <input type="url" name="cds_mapa" class="cs-input" placeholder="https://maps.google.com/…" value="{{ old('cds_mapa', $servico->cds_mapa ?? '') }}">
            </div>

            <div class="cs-field cs-span-full">
                <label class="cs-label">{{ __('Contato complementar') }}</label>
                <textarea name="cds_contato" rows="2" class="cs-textarea" placeholder="Informações adicionais de contato…">{{ old('cds_contato', $servico->cds_contato ?? '') }}</textarea>
            </div>

        </div>
    </div>

    {{-- ── 5. Regras de Acesso ──────────────────────────────── --}}
    <div class="cs-section">
        <div class="cs-section-label">Regras de Acesso</div>
        <div class="cs-grid cs-grid-2">

            <div class="cs-field">
                <label class="cs-label">{{ __('Quem pode solicitar') }}</label>
                <textarea name="cds_quem" rows="3" class="cs-textarea" placeholder="Cidadãos, empresas, servidores…">{{ old('cds_quem', $servico->cds_quem ?? '') }}</textarea>
            </div>
            <div class="cs-field">
                <label class="cs-label">{{ __('Quando pode solicitar') }}</label>
                <textarea name="cds_quando" rows="3" class="cs-textarea" placeholder="Horários, períodos, sazonalidades…">{{ old('cds_quando', $servico->cds_quando ?? '') }}</textarea>
            </div>
            <div class="cs-field">
                <label class="cs-label">{{ __('Atendimento') }}</label>
                <textarea name="cds_atendimento" rows="3" class="cs-textarea" placeholder="Presencial, online, híbrido…">{{ old('cds_atendimento', $servico->cds_atendimento ?? '') }}</textarea>
            </div>
            <div class="cs-field">
                <label class="cs-label">{{ __('Requisitos e documentos') }}</label>
                <textarea name="cds_requisitos" rows="3" class="cs-textarea" placeholder="Liste os documentos necessários…">{{ old('cds_requisitos', $servico->cds_requisitos ?? '') }}</textarea>
            </div>

        </div>
    </div>

    {{-- ── 6. Prazos, Taxas & Legislação ───────────────────── --}}
    <div class="cs-section">
        <div class="cs-section-label">Prazos, Taxas &amp; Legislação</div>
        <div class="cs-grid cs-grid-2">

            <div class="cs-field">
                <label class="cs-label">{{ __('Prazos') }}</label>
                <textarea name="cds_prazo" rows="3" class="cs-textarea" placeholder="Tempo médio de resposta, SLA…">{{ old('cds_prazo', $servico->cds_prazo ?? '') }}</textarea>
            </div>
            <div class="cs-field">
                <label class="cs-label">{{ __('Taxas') }}</label>
                <textarea name="cds_taxas" rows="3" class="cs-textarea" placeholder="Valores, isenções, formas de pagamento…">{{ old('cds_taxas', $servico->cds_taxas ?? '') }}</textarea>
            </div>
            <div class="cs-field cs-span-full">
                <label class="cs-label">{{ __('Legislação') }}</label>
                <textarea name="cds_legislacao" rows="3" class="cs-textarea" placeholder="Leis, decretos, portarias aplicáveis…">{{ old('cds_legislacao', $servico->cds_legislacao ?? '') }}</textarea>
            </div>

        </div>
    </div>

    {{-- ── 7. Etapas & Observações ──────────────────────────── --}}
    <div class="cs-section">
        <div class="cs-section-label">Etapas &amp; Observações</div>
        <div class="cs-grid cs-grid-2">

            <div class="cs-field">
                <label class="cs-label">{{ __('Etapas do serviço') }}</label>
                <textarea name="cds_etapas" rows="4" class="cs-textarea" placeholder="Descreva o passo a passo…">{{ old('cds_etapas', $servico->cds_etapas ?? '') }}</textarea>
            </div>
            <div class="cs-field">
                <label class="cs-label">{{ __('Observações') }}</label>
                <textarea name="cds_obs" rows="4" class="cs-textarea" placeholder="Notas e informações adicionais…">{{ old('cds_obs', $servico->cds_obs ?? '') }}</textarea>
            </div>

        </div>
    </div>

    {{-- ── Footer ────────────────────────────────────────────── --}}
    <div class="cs-footer">
        <a href="{{ route('admin.cartaServicos.index', request()->only(['q', 'tipo_id', 'page'])) }}" class="cs-btn cs-btn-ghost">
            ← {{ __('Voltar') }}
        </a>
        <button type="submit" class="cs-btn cs-btn-primary">
            {{ __('Salvar serviço') }} →
        </button>
    </div>

</div>

<script>
    function updateStatusDot(sel) {
        sel.setAttribute('data-status', sel.value);
        const dot = document.getElementById('statusDot');
        const colors = { '3': '#52C97A', '1': '#F0B429', '2': '#CBD5E0' };
        dot.style.background = colors[sel.value] || '#CBD5E0';
    }
    // Init on page load
    document.addEventListener('DOMContentLoaded', () => {
        const sel = document.getElementById('statusSelect');
        if (sel) updateStatusDot(sel);
    });
</script>