<?php
if (!defined('ABSPATH')) exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound
class SS_AI_Admin {
    public static function render(){
        if (!current_user_can('manage_options')) return;

        $nonce = wp_create_nonce('ss_ai_admin_actions');

        // Previews (server-side; no ajax needed)
        $llms   = class_exists('SS_AI_Protocol') ? SS_AI_Protocol::preview_llms()   : '';
        $policy = class_exists('SS_AI_Protocol') ? SS_AI_Protocol::preview_policy() : '';

        $policy_id   = (int) get_option('ss_ai_policy_page_id');
        $policy_url  = $policy_id ? get_permalink($policy_id) : '';
        $llms_url    = home_url('/llms.txt');
        $robots_url  = home_url('/robots.txt');

        echo '<div class="wrap" id="ss-ai-admin">';
        echo '<h1>AI Protocol Files</h1>';

        // ---------- Status ----------
        echo '<div class="ss-card"><h2 style="margin-top:0">Status</h2>';
        echo '<ul id="ss-ai-status" class="ss-recs" style="margin-left:18px">';
        echo '<li>Policy page: <span data-k="policy">checking…</span> ';
        if ($policy_url) echo '(<a href="'.esc_url($policy_url).'" target="_blank" rel="noopener">view</a>)';
        echo '</li>';
        echo '<li>llms.txt: <span data-k="llms">checking…</span> (<a href="'.esc_url($llms_url).'" target="_blank" rel="noopener">open</a>)</li>';
        echo '<li>robots.txt (AI block): <span data-k="robots">checking…</span> (<a href="'.esc_url($robots_url).'" target="_blank" rel="noopener">open</a>)</li>';
        echo '</ul>';
        echo '</div>';

        // ---------- Previews ----------
        echo '<div class="ss-card"><h2 style="margin-top:0">Preview — llms.txt</h2>';
        echo '<textarea readonly rows="12" style="width:100%;font-family:monospace">'.esc_textarea($llms).'</textarea>';
        echo '<p>';
        echo '<button class="button button-primary" id="ss-ai-publish" data-nonce="'.esc_attr($nonce).'">Publish to root</button> ';
        echo '<a class="button" href="'.esc_url( admin_url('admin-post.php?action=ss_ai_download&file=llms&_wpnonce='.$nonce) ).'">Download llms.txt</a>';
        echo '</p>';
        echo '</div>';

        echo '<div class="ss-card"><h2 style="margin-top:0">Preview — AI Visibility Policy (HTML)</h2>';
        echo '<textarea readonly rows="14" style="width:100%;font-family:monospace">'.esc_textarea($policy).'</textarea>';
        echo '<p><a class="button" href="'.esc_url( admin_url('admin-post.php?action=ss_ai_download&file=policy&_wpnonce='.$nonce) ).'">Download policy.html</a></p>';
        echo '</div>';

        // ---------- Inline JS for actions ----------
        ?>
        <script>
        (function(){
          function setRow(k, text, ok){
            var el = document.querySelector('#ss-ai-status [data-k="'+k+'"]');
            if(!el) return;
            el.textContent = text || '';
            el.style.fontWeight = ok ? '600' : '400';
            el.style.color = ok ? '#11623a' : '#8a1f11';
          }
          function checkStatus(){
            var form = new FormData();
            form.append('action','ss_ai_status');
            form.append('_ajax_nonce','<?php echo esc_js($nonce); ?>');
            var ajaxUrl = '<?php echo esc_js( admin_url('admin-ajax.php') ); ?>';

            fetch(ajaxurl, {method:'POST', body:form})
              .then(r => r.json()).then(function(j){
                if(!j || !j.success) throw new Error('Bad response');
                var d = j.data || {};
                setRow('policy', d.policy_ok ? 'OK' : (d.policy_msg||'Missing'), !!d.policy_ok);
                setRow('llms', d.llms_ok ? '200 text/plain' : (d.llms_msg||'Missing'), !!d.llms_ok);
                setRow('robots', d.robots_ok ? 'AI block present' : (d.robots_msg||'Missing'), !!d.robots_ok);
              }).catch(function(){
                setRow('policy','Error'); setRow('llms','Error'); setRow('robots','Error');
              });
          }
          function publishNow(btn){
            btn.disabled = true; btn.textContent = 'Publishing…';
            var form = new FormData();
            form.append('action','ss_ai_publish_llms');
            form.append('_ajax_nonce','<?php echo esc_js($nonce); ?>');
            fetch(ajaxurl, {method:'POST', body:form})
              .then(r => r.json()).then(function(j){
                btn.textContent = j && j.success ? 'Published ✓' : 'Failed';
                setTimeout(function(){ btn.disabled=false; btn.textContent='Publish to root'; }, 900);
                checkStatus();
              }).catch(function(){
                btn.textContent = 'Failed';
                setTimeout(function(){ btn.disabled=false; btn.textContent='Publish to root'; }, 900);
              });
          }
          document.getElementById('ss-ai-publish')?.addEventListener('click', function(){ publishNow(this); });
          checkStatus();
        })();
        </script>
        <?php
        echo '</div>';
    }
}
// phpcs:enable