<?php

if (!defined('ABSPATH')) {
  exit;
}

/**
 * Render the authentication page
 */
function content_craft_ai_render_auth_page()
{
  // Get auth status - we'll rely on the global auth check for redirects
  $user = content_craft_ai_check_auth();

  // If user is authenticated, don't redirect here
  if ($user) {
    // This is a fallback - the auth-check.php should handle this redirect already
    // Just return without rendering anything
    return;
  }

  // Get view parameter - properly sanitize and unslash
  // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading view parameter from URL for navigation, not processing form data
  $auth_view = isset($_GET['view']) ? sanitize_text_field(wp_unslash($_GET['view'])) : 'login';

  // Ensure the script is enqueued
  wp_enqueue_script('content-craft-ai-admin');

  // Add data as JSON in window object
  wp_localize_script(
    'content-craft-ai-admin',
    'contentCraftAIData',
    array_merge(
      (array) wp_scripts()->get_data('content-craft-ai-admin', 'data'),
      array(
        'page' => 'auth',
        'user' => null,
        'authView' => $auth_view,
        'wpApiUrl' => rest_url('content-craft-ai/v1'),
        'nonce' => wp_create_nonce('wp_rest'),
        'siteUrl' => get_site_url(),
        'adminUrl' => admin_url()
      )
    )
  );

  // Render the app container
  echo '<div id="content-craft-ai-app"></div>';
}
