<?php
/**
 * ACRIB Core MU-Plugin
 * Always-on: custom footer, security hardening, performance tweaks.
 * @version 1.5
 */

// --- Remove Kadence default copyright footer ---
// template-hooks.php is included at the root of functions.php, so the action
// is added before after_setup_theme fires. Priority 999 removes it after.
add_action('after_setup_theme', function () {
    remove_action('kadence_footer', 'Kadence\footer_markup');
    remove_action('kadence_footer_html', 'Kadence\footer_html');
}, 999);

// --- Sticky navy header: remove any transparent-header classes ---
// The header is now always navy (non-transparent), sticky on scroll.
add_filter('body_class', function ($classes) {
    $classes = array_diff($classes, ['transparent-header', 'mobile-transparent-header']);
    if (!in_array('non-transparent-header', $classes)) {
        $classes[] = 'non-transparent-header';
        $classes[] = 'mobile-non-transparent-header';
    }
    return $classes;
}, 999);

// --- Footer: bottom bar with legal links + org identity + Cloud Host credit ---
add_action('wp_footer', function () {
    $year       = date('Y');
    $legal_url  = home_url('/aviso-legal/');
    $pp_url     = home_url('/politica-privacidad/');
    $cookie_url = home_url('/politica-cookies/');

    // Language-aware labels + new legal page URLs
    $lang = function_exists('pll_current_language') ? pll_current_language() : 'es';
    $ids  = get_option('acrib_legal_page_ids', []);
    $estatutos_url = !empty($ids['estatutos'][$lang]) ? get_permalink($ids['estatutos'][$lang]) : home_url('/estatutos/');
    $etica_url     = !empty($ids['etica'][$lang])     ? get_permalink($ids['etica'][$lang])     : home_url('/codigo-etico/');
    $deon_url      = !empty($ids['deon'][$lang])      ? get_permalink($ids['deon'][$lang])      : home_url('/codigo-deontologico/');
    $ll = [
        'es' => ['al' => 'Aviso Legal', 'pp' => 'Privacidad', 'ck' => 'Cookies', 'est' => 'Estatutos', 'eta' => 'Código Ético', 'deo' => 'Código Deontológico'],
        'ro' => ['al' => 'Mențiuni Legale', 'pp' => 'Confidențialitate', 'ck' => 'Cookie-uri', 'est' => 'Statut', 'eta' => 'Cod Etic', 'deo' => 'Cod Deontologic'],
        'en' => ['al' => 'Legal Notice', 'pp' => 'Privacy Policy', 'ck' => 'Cookies', 'est' => 'Statutes', 'eta' => 'Code of Ethics', 'deo' => 'Deontological Code'],
    ];
    $l = $ll[$lang] ?? $ll['es'];
    ?>
    <div class="acrib-footer-bottom">
      <div class="acrib-footer-bottom-inner">
        <p class="acrib-footer-copyright">
          &copy; <?php echo $year; ?> <strong>ACRIB</strong> &mdash; Asociaci&oacute;n Casa Rom&acirc;neasc&#259; de las Islas Baleares
        </p>
        <a class="acrib-footer-fb" href="https://www.facebook.com/profile.php?id=61583585888787" target="_blank" rel="noopener noreferrer" aria-label="ACRIB en Facebook"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg></a>
        <ul class="acrib-footer-legal-links">
          <li><a href="<?php echo esc_url($legal_url); ?>"><?php echo esc_html($l['al']); ?></a></li>
          <li><a href="<?php echo esc_url($pp_url); ?>"><?php echo esc_html($l['pp']); ?></a></li>
          <li><a href="<?php echo esc_url($cookie_url); ?>"><?php echo esc_html($l['ck']); ?></a></li>
          <li><a href="<?php echo esc_url($estatutos_url); ?>"><?php echo esc_html($l['est']); ?></a></li>
          <li><a href="<?php echo esc_url($etica_url); ?>"><?php echo esc_html($l['eta']); ?></a></li>
          <li><a href="<?php echo esc_url($deon_url); ?>"><?php echo esc_html($l['deo']); ?></a></li>
        </ul>
        <p class="acrib-footer-ids">
          CIF:&nbsp;<strong>G22992846</strong> &nbsp;&bull;&nbsp; Reg. Asoc. Illes Balears, Secc.&nbsp;1.ª, n.º&nbsp;311000012342
        </p>
        <p class="acrib-footer-hosted">
          Hosted &amp; Maintained by <a href="https://cloudhost.es" target="_blank" rel="noopener noreferrer">Cloud Host</a>
        </p>
      </div>
    </div>
    <?php
}, 100);

// ── Contact section: inject address sidebar next to CF7 form ──
add_action('wpcf7_enqueue_scripts', function () {
    add_action('wp_footer', function () {
        $lang = function_exists('pll_current_language') ? pll_current_language() : 'es';
        $ll = [
            'es' => ['title' => 'Información de contacto', 'addr' => 'Dirección', 'email' => 'Correo general', 'pres' => 'Presidencia'],
            'ro' => ['title' => 'Informații de contact', 'addr' => 'Adresă', 'email' => 'E-mail general', 'pres' => 'Președinție'],
            'en' => ['title' => 'Contact information', 'addr' => 'Address', 'email' => 'General email', 'pres' => 'Presidency'],
        ];
        $l = $ll[$lang] ?? $ll['es'];
        ?>
<style id="acrib-contact-layout-css">
.acrib-contact-layout{display:grid;grid-template-columns:280px 1fr;gap:2.5rem;align-items:start;}
.acrib-contact-info{background:#f4f7fb;border-radius:6px;padding:1.75rem 1.5rem;border-top:3px solid #c69c48;}
.acrib-contact-info h4{font-family:"Lato",sans-serif;font-size:.75rem;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:#13294b;margin:0 0 1.25rem;}
.acrib-ci-row{display:flex;flex-direction:column;margin-bottom:1rem;}
.acrib-ci-label{font-size:.7rem;font-weight:700;letter-spacing:.07em;text-transform:uppercase;color:#8a9ab5;font-family:"Lato",sans-serif;margin-bottom:.25rem;}
.acrib-ci-value,.acrib-contact-info address{font-size:.9rem;color:#13294b;line-height:1.6;font-style:normal;}
.acrib-contact-info a{color:#c69c48;text-decoration:none;}
.acrib-contact-info a:hover{text-decoration:underline;}
.acrib-ci-cif{font-size:.72rem;color:#8a9ab5;margin:.75rem 0 0;padding-top:.75rem;border-top:1px solid #dce6f0;}
@media(max-width:820px){.acrib-contact-layout{grid-template-columns:1fr;}}
</style>
<script id="acrib-contact-layout-js">
(function(){
    var form=document.querySelector('.wpcf7');
    if(!form) return;
    var layout=document.createElement('div');
    layout.className='acrib-contact-layout';
    form.parentNode.insertBefore(layout,form);
    var info=document.createElement('div');
    info.className='acrib-contact-info';
    info.innerHTML='<h4><?php echo esc_js($l['title']); ?></h4>'
        +'<div class="acrib-ci-row"><span class="acrib-ci-label"><?php echo esc_js($l['addr']); ?></span>'
        +'<address>Avda. Asima, n.\u00ba\u00a017<br>Planta\u00a01, Puerta\u00a0A<br>07009 Palma de Mallorca<br>Illes Balears, Espa\u00f1a</address></div>'
        +'<div class="acrib-ci-row"><span class="acrib-ci-label"><?php echo esc_js($l['email']); ?></span>'
        +'<span class="acrib-ci-value"><a href="mailto:info@acrib.es">info@acrib.es</a></span></div>'
        +'<div class="acrib-ci-row"><span class="acrib-ci-label"><?php echo esc_js($l['pres']); ?></span>'
        +'<span class="acrib-ci-value"><a href="mailto:presidencia@acrib.es">presidencia@acrib.es</a></span></div>'
        +'<p class="acrib-ci-cif">CIF: G22992846</p>';
    layout.appendChild(info);
    layout.appendChild(form);
}());
</script>
        <?php
    }, 55);
});

// --- Security headers ---
add_action('send_headers', function () {
    if (!is_admin()) {
        header('X-Frame-Options: SAMEORIGIN');
        header('X-Content-Type-Options: nosniff');
        header('Referrer-Policy: strict-origin-when-cross-origin');
        header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
    }
});

// --- Disable XML-RPC ---
add_filter('xmlrpc_enabled', '__return_false');
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'wp_shortlink_wp_head');

// --- Disable REST API user enumeration ---
add_filter('rest_endpoints', function ($endpoints) {
    unset($endpoints['/wp/v2/users'], $endpoints['/wp/v2/users/(?P<id>[\d]+)']);
    return $endpoints;
});

// --- Disable emoji (reduces ~20KB page weight) ---
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_filter('the_content_feed', 'wp_staticize_emoji');
remove_filter('comment_text_rss', 'wp_staticize_emoji');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');

// --- Limit post revisions ---
if (!defined('WP_POST_REVISIONS')) {
    define('WP_POST_REVISIONS', 3);
}

// --- Global: hide Kadence title section on pages with custom heroes ---
// Kadence free ignores _kadence_post_layout title:hide meta.
// We read it ourselves and output the fix for any page that set it.
add_action('wp_head', function () {
    if (is_singular()) {
        $layout = get_post_meta(get_the_ID(), '_kadence_post_layout', true);
        $meta   = $layout ? json_decode($layout, true) : [];
        $hide_title = isset($meta['title'])  && $meta['title']  === 'hide';
        $full_width = isset($meta['layout']) && $meta['layout'] === 'fullwidth';
        if ($hide_title || $full_width) {
            $id    = get_the_ID();
            $rules = [];
            if ($hide_title) {
                $rules[] = '.page-id-' . $id . ' .entry-hero.page-hero-section{display:none!important}';
            }
            if ($full_width) {
                $rules[] = '.page-id-' . $id . ' .entry-content-wrap{padding:0!important;box-shadow:none!important;margin:0!important;background:none!important}';
                $rules[] = '.page-id-' . $id . ' .content-area{max-width:100%!important;padding:0!important}';
            }
            if ($rules) {
                echo '<style id="acrib-page-fixes-' . $id . '">' . implode("\n", $rules) . '</style>' . "\n";
            }
        }
    }
}, 5);

// --- Homepage + translations: layout fixes ---
// With the sticky navy header the hero now sits directly below the header.
// These rules clean up Kadence's boxed-content wrappers and size the hero.
add_action('wp_head', function () {
    if (!is_front_page() && !is_singular()) return;
    $inject = is_front_page();
    if (!$inject && function_exists('pll_get_post_translations')) {
        $front_id = (int) get_option('page_on_front');
        if ($front_id) {
            $inject = in_array(get_the_ID(), pll_get_post_translations($front_id), true);
        }
    }
    if (!$inject) return;
    echo '<style id="acrib-homepage-fixes">
/* Hide Kadence blank page-title section above hero */
.home .entry-hero.page-hero-section{display:none!important}
/* Remove boxed content styling on homepage */
.home .entry-content-wrap{
    padding:0!important;box-shadow:none!important;
    margin:0!important;background:none!important;
}
.home .content-area,.home #content{margin-bottom:0!important}
/* Hero: fill the full viewport height */
.acrib-hero.wp-block-cover{
    height:100svh!important;
    height:100vh!important;
    min-height:0!important;
}
/* Centre hero content */
.acrib-hero .wp-block-cover__inner-container{
    height:100%!important;
    min-height:0!important;
    display:flex!important;
    flex-direction:column!important;
    align-items:center!important;
    justify-content:center!important;
    padding:2rem!important;
    box-sizing:border-box!important;
}
</style>' . "\n";
}, 5);

// --- Single post: spacing fix between featured image and title/meta ---
add_action('wp_head', function () {
    if (!is_singular('post')) return;
    echo '<style id="acrib-single-post-spacing">
/* Gap between featured image (above-position) and post title/meta */
.single-post .post-thumbnail.article-post-thumbnail{
    margin-bottom:0!important;
}
.single-post .single-entry .entry-content-wrap{
    padding-top:2rem!important;
}
/* If title is shown in the hero section: add breathing room below hero */
.single-post .entry-hero.page-hero-section{
    margin-bottom:1rem!important;
}
</style>' . "\n";
}, 8);

// ═══════════════════════════════════════════════════════════════════
// STICKY HEADER + SEARCH
// ═══════════════════════════════════════════════════════════════════

// ── Sticky header CSS + search overlay CSS ──
add_action('wp_head', function () {
    echo '<style id="acrib-sticky-search-styles">
/* ── Sticky navy header ─────────────────────────────────────────── */
#masthead.site-header{
    position:sticky!important;
    top:0;
    z-index:9999;
    background:#13294b!important;
    box-shadow:0 2px 12px rgba(19,41,75,.22);
}
/* ── Search icon button in nav ──────────────────────────────────── */
li.acrib-search-item{
    list-style:none;
    display:flex!important;
    align-items:center;
    padding:0;
}
.acrib-search-btn{
    background:none;
    border:none;
    cursor:pointer;
    padding:.3rem .5rem;
    color:#fff;
    opacity:.8;
    transition:opacity .2s;
    display:flex;
    align-items:center;
    line-height:1;
}
.acrib-search-btn:hover,
.acrib-search-btn:focus{opacity:1;outline:none;}
/* ── Search overlay ─────────────────────────────────────────────── */
#acrib-search-overlay{
    display:none;
    position:fixed;
    inset:0;
    background:rgba(10,20,40,.88);
    z-index:99999;
    align-items:flex-start;
    justify-content:center;
    padding-top:12vh;
}
#acrib-search-overlay.is-open{display:flex;}
#acrib-search-wrap{
    width:100%;
    max-width:620px;
    padding:0 1.5rem;
}
#acrib-search-input{
    width:100%;
    background:#fff;
    border:none;
    border-radius:6px;
    padding:1rem 1.25rem;
    font-size:1.15rem;
    color:#13294b;
    box-shadow:0 8px 40px rgba(0,0,0,.45);
    outline:none;
    font-family:"Source Sans 3","Source Sans Pro",sans-serif;
    box-sizing:border-box;
    -webkit-appearance:none;
    appearance:none;
}
#acrib-search-close{
    display:block;
    width:100%;
    text-align:right;
    background:none;
    border:none;
    color:rgba(255,255,255,.55);
    font-size:.78rem;
    font-family:"Lato",sans-serif;
    cursor:pointer;
    padding:.5rem 0 0;
    letter-spacing:.05em;
}
#acrib-search-close:hover{color:#fff;}
#acrib-search-results{
    margin-top:.4rem;
    background:#fff;
    border-radius:6px;
    overflow:hidden;
    box-shadow:0 8px 40px rgba(0,0,0,.3);
    max-height:55vh;
    overflow-y:auto;
}
#acrib-search-results a{
    display:block;
    padding:.75rem 1.25rem;
    color:#13294b;
    text-decoration:none;
    border-bottom:1px solid #eef2f9;
    font-family:"Lato",sans-serif;
    font-size:.95rem;
    line-height:1.4;
}
#acrib-search-results a:last-child{border-bottom:none;}
#acrib-search-results a:hover{background:#f4f7fb;color:#c69c48;}
#acrib-search-results .acrib-no-results{
    padding:.9rem 1.25rem;
    color:#8a9ab5;
    font-family:"Lato",sans-serif;
    font-size:.9rem;
}
@media(max-width:600px){
    #acrib-search-overlay{padding-top:8vh;}
    #acrib-search-wrap{padding:0 1rem;}
    #acrib-search-input{font-size:1rem;padding:.85rem 1rem;}
}
</style>' . "\n";
}, 1);

// ── Search icon: append magnifying glass to primary nav menus ──
add_filter('wp_nav_menu_items', function ($items, $args) {
    if (empty($args->menu) || !in_array((int) $args->menu->term_id, [2, 16, 17])) {
        return $items;
    }
    $items .= '<li class="menu-item acrib-search-item">'
        . '<button class="acrib-search-btn" id="acrib-search-open" aria-label="Search" type="button">'
        . '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'
        . '<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>'
        . '</svg>'
        . '</button></li>';
    return $items;
}, 10, 2);

// ── Search overlay HTML + AJAX JS ──
add_action('wp_footer', function () {
    $lang        = function_exists('pll_current_language') ? pll_current_language() : 'es';
    $placeholder = $lang === 'ro' ? 'Caută...' : ($lang === 'en' ? 'Search...' : 'Buscar...');
    $close_hint  = $lang === 'ro' ? 'Apasă ESC pentru a închide' : ($lang === 'en' ? 'Press ESC to close' : 'Pulsa ESC para cerrar');
    $no_results  = $lang === 'ro' ? 'Niciun rezultat.' : ($lang === 'en' ? 'No results found.' : 'Sin resultados.');
    ?>
<div id="acrib-search-overlay" role="dialog" aria-modal="true" aria-label="<?php echo esc_attr($placeholder); ?>">
  <div id="acrib-search-wrap">
    <input type="search" id="acrib-search-input" placeholder="<?php echo esc_attr($placeholder); ?>" autocomplete="off" spellcheck="false" />
    <div id="acrib-search-results" hidden></div>
    <button id="acrib-search-close" type="button"><?php echo esc_html($close_hint); ?></button>
  </div>
</div>
<script id="acrib-search-js">
(function(){
    var overlay  = document.getElementById('acrib-search-overlay'),
        input    = document.getElementById('acrib-search-input'),
        results  = document.getElementById('acrib-search-results'),
        openBtn  = document.getElementById('acrib-search-open'),
        closeBtn = document.getElementById('acrib-search-close');
    if (!overlay || !openBtn) return;

    var lang  = <?php echo json_encode($lang); ?>;
    var noRes = <?php echo json_encode($no_results); ?>;
    var timer = null;

    function openSearch() {
        overlay.classList.add('is-open');
        setTimeout(function(){ input.focus(); }, 50);
        document.body.style.overflow = 'hidden';
    }
    function closeSearch() {
        overlay.classList.remove('is-open');
        input.value = '';
        results.innerHTML = '';
        results.hidden = true;
        document.body.style.overflow = '';
    }

    openBtn.addEventListener('click', openSearch);
    closeBtn.addEventListener('click', closeSearch);
    overlay.addEventListener('click', function(e) {
        if (e.target === overlay) closeSearch();
    });
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && overlay.classList.contains('is-open')) closeSearch();
        if ((e.ctrlKey || e.metaKey) && e.key === 'k') { e.preventDefault(); openSearch(); }
    });

    input.addEventListener('input', function() {
        clearTimeout(timer);
        var q = input.value.trim();
        if (q.length < 2) { results.innerHTML = ''; results.hidden = true; return; }
        timer = setTimeout(function(){ doSearch(q); }, 300);
    });

    function doSearch(q) {
        var url = '/wp-json/wp/v2/search?search=' + encodeURIComponent(q) + '&per_page=6&lang=' + lang;
        fetch(url)
            .then(function(r) { return r.json(); })
            .then(function(data) {
                results.hidden = false;
                if (!data || !data.length) {
                    results.innerHTML = '<p class="acrib-no-results">' + noRes + '</p>';
                    return;
                }
                results.innerHTML = data.map(function(item) {
                    return '<a href="' + item.url + '">' + item.title + '</a>';
                }).join('');
            })
            .catch(function() {});
    }
}());
</script>
    <?php
}, 99);


// ═══════════════════════════════════════════════════════════════════
// CONTACT FORM 7 — REDESIGN CSS, REFERENCE NUMBERS & ENHANCEMENTS
// @version 2.0
// ═══════════════════════════════════════════════════════════════════

// ── Form reference: generate sequential ref at send time ──
add_action('wpcf7_before_send_mail', function ($cf7) {
    $submission = WPCF7_Submission::get_instance();
    if (!$submission) return;
    $posted = $submission->get_posted_data();
    $ref    = !empty($posted['form-ref']) ? $posted['form-ref'] : '';

    // Generate sequential ref if JS didn't supply one
    if (!$ref) {
        $counter = (int) get_option('acrib_form_counter', 1000) + 1;
        update_option('acrib_form_counter', $counter, false);
        $ref = 'ACRIB-' . date('Y') . '-' . str_pad($counter, 4, '0', STR_PAD_LEFT);
    }

    // Ensure ref appears in subject + body even if tag not resolved
    $mail = $cf7->prop('mail');
    $mail['body']    = str_replace('[form-ref]', $ref, $mail['body']);
    $mail['subject'] = str_replace('[form-ref]', $ref, $mail['subject']);
    $cf7->set_properties(['mail' => $mail]);
});

// ── CF7 redesign CSS ──
add_action('wp_head', function () {
    if (!is_page() && !is_singular()) return;
    echo '<style id="acrib-cf7-styles">
/* ══ ACRIB Contact Form Redesign ══════════════════════════════════ */
.acrib-cf7{
    background:#fff;
    color:#13294b!important;
    border-top:4px solid #c69c48;
    border-radius:3px;
    padding:1.5rem 1.75rem 1.4rem;
    box-shadow:0 4px 28px rgba(19,41,75,.1);
}
.acrib-cf7 .cf7-row{
    display:flex;
    gap:1rem;
    margin-bottom:.8rem;
    align-items:flex-start;
}
.acrib-cf7 .cf7-field{
    flex:1;
    display:flex;
    flex-direction:column;
    min-width:0;
}
.acrib-cf7 p{margin:0!important;padding:0!important;}
.acrib-cf7 .cf7-field label{
    font-family:"Lato",sans-serif;
    font-size:.7rem;
    font-weight:700;
    letter-spacing:.09em;
    text-transform:uppercase;
    color:#13294b!important;
    margin-bottom:.35rem;
    display:block;
}
.acrib-cf7 input[type="text"],
.acrib-cf7 input[type="email"],
.acrib-cf7 input[type="tel"],
.acrib-cf7 select,
.acrib-cf7 textarea{
    width:100%;
    background:#f4f7fb;
    border:1.5px solid #8fa3bc;
    border-radius:4px;
    padding:.72rem .95rem;
    font-size:.95rem;
    color:#13294b;
    font-family:"Source Sans 3","Source Sans Pro",sans-serif;
    transition:border-color .18s,background .18s,box-shadow .18s;
    outline:none;
    box-sizing:border-box;
    -webkit-appearance:none;
    appearance:none;
}
.acrib-cf7 input[type="text"]:focus,
.acrib-cf7 input[type="email"]:focus,
.acrib-cf7 input[type="tel"]:focus,
.acrib-cf7 select:focus,
.acrib-cf7 textarea:focus{
    border-color:#c69c48;
    background:#fff;
    box-shadow:0 0 0 3px rgba(198,156,72,.14);
}
.acrib-cf7 select{
    background-image:url("data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%2710%27 height=%276%27 viewBox=%270 0 10 6%27%3E%3Cpath d=%27M0 0l5 6 5-6z%27 fill=%27%2313294b%27/%3E%3C/svg%3E");
    background-repeat:no-repeat;
    background-position:right .9rem center;
    padding-right:2.2rem;
    cursor:pointer;
}
.acrib-cf7 textarea{min-height:90px;resize:vertical;line-height:1.5;}
.acrib-cf7 .wpcf7-not-valid{border-color:#a12932!important;background:#fff7f7!important;}
.acrib-cf7 .wpcf7-not-valid-tip{
    font-size:.73rem;color:#a12932;margin-top:.3rem;
    font-family:"Lato",sans-serif;display:block;
}
.acrib-cf7 .wpcf7-response-output{
    border-radius:4px!important;padding:.85rem 1.1rem!important;
    font-size:.88rem!important;font-family:"Lato",sans-serif!important;
    margin-top:1rem!important;border:none!important;
}
.acrib-cf7 .wpcf7-mail-sent-ok{
    background:#f0faf4!important;color:#1a6b3a!important;
    border-left:4px solid #28a745!important;
}
.acrib-cf7 .wpcf7-validation-errors,
.acrib-cf7 .wpcf7-mail-sent-ng,
.acrib-cf7 .wpcf7-spam-blocked{
    background:#fff5f5!important;color:#a12932!important;
    border-left:4px solid #a12932!important;
}
.acrib-cf7 .cf7-ref-label{
    font-size:.72rem;font-family:"Lato",sans-serif;
    color:#8a9ab5!important;letter-spacing:.04em;
    margin:0 0 .7rem;text-align:right;min-height:1.2em;
}
.acrib-cf7 .cf7-ref-label span{
    background:#eef2f9;padding:2px 9px;border-radius:3px;
    font-weight:700;color:#13294b;font-size:.75rem;
    letter-spacing:.06em;
}
.acrib-cf7 .cf7-legal{
    margin:.9rem 0 1rem;display:flex;
    flex-direction:column;gap:.55rem;
}
.acrib-cf7 .wpcf7-acceptance{display:block;}
.acrib-cf7 .wpcf7-acceptance .wpcf7-list-item{
    margin:0!important;display:flex!important;
    align-items:flex-start!important;gap:.55rem!important;
}
.acrib-cf7 .wpcf7-acceptance input[type="checkbox"]{
    flex-shrink:0;width:17px;height:17px;margin-top:2px;
    border:2px solid #8fa3bc;border-radius:3px;background:#f4f7fb;
    cursor:pointer;transition:border-color .18s,background .18s;
    -webkit-appearance:none;appearance:none;position:relative;
}
.acrib-cf7 .wpcf7-acceptance input[type="checkbox"]:checked{
    background:#13294b;border-color:#13294b;
}
.acrib-cf7 .wpcf7-acceptance input[type="checkbox"]:checked::after{
    content:"";position:absolute;top:1px;left:4px;
    width:5px;height:8px;border:2px solid #fff;
    border-top:none;border-left:none;transform:rotate(45deg);display:block;
}
.acrib-cf7 .wpcf7-acceptance input[type="checkbox"]:focus{
    outline:none;box-shadow:0 0 0 3px rgba(198,156,72,.18);border-color:#c69c48;
}
.acrib-cf7 .wpcf7-acceptance .wpcf7-list-item-label{
    font-size:.82rem;color:#4a5568!important;line-height:1.55;font-family:"Lato",sans-serif;
}
.acrib-cf7 .wpcf7-acceptance .wpcf7-list-item-label a{
    color:#c69c48;text-decoration:underline;text-underline-offset:2px;
}
.acrib-cf7 .wpcf7-submit{
    display:block;width:100%;background:#13294b;color:#fff;
    border:none;border-radius:4px;padding:.75rem 2rem;
    font-size:.85rem;font-weight:700;letter-spacing:.12em;
    text-transform:uppercase;font-family:"Lato",sans-serif;
    cursor:pointer;transition:background .2s,box-shadow .2s,transform .12s;
    position:relative;
}
.acrib-cf7 .wpcf7-submit:hover{
    background:#c69c48;box-shadow:0 4px 14px rgba(198,156,72,.28);
}
.acrib-cf7 .wpcf7-submit:active{transform:translateY(1px);}
.acrib-cf7 .wpcf7-spinner{
    position:absolute;right:1.2rem;top:50%;transform:translateY(-50%);margin:0;
}
@media(max-width:580px){
    .acrib-cf7 .cf7-row{flex-direction:column;gap:.9rem;}
    .acrib-cf7{padding:1.6rem 1.1rem 1.4rem;}
}
</style>
';
}, 20);

// ── CF7 JS: populate reference number on page load ──
add_action('wp_footer', function () {
    if (!is_page() && !is_singular()) return;
    ?>
<script id="acrib-cf7-js">
(function(){
    function acribRef(){
        var n=new Date(),
            p=function(v){return String(v).padStart(2,'0');};
        return'ACRIB-'+n.getFullYear()+p(n.getMonth()+1)+p(n.getDate())+'-'+p(n.getHours())+p(n.getMinutes());
    }
    function initForms(){
        document.querySelectorAll('.acrib-cf7').forEach(function(w){
            var ref=acribRef();
            var hf=w.querySelector('input[name="form-ref"]');
            if(hf&&!hf.value) hf.value=ref;
            var badge=w.querySelector('.cf7-ref-label span');
            if(badge) badge.textContent=(hf&&hf.value)?hf.value:ref;
        });
    }
    if(document.readyState==='loading'){
        document.addEventListener('DOMContentLoaded',initForms);
    }else{initForms();}
    document.addEventListener('wpcf7mailsent',function(){
        setTimeout(initForms,200);
    });
}());
</script>
    <?php
}, 30);
