<?php
/**
 * Audits CRUD admin page (WP Admin → Site Audit → Audits).
 *
 * Supports: list view, create new audit, edit existing audit (with
 * inline question/answer/category editor), delete, and duplicate.
 */

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

class Noon_Audit_Admin_Audits {

    public static function register_menu() {
        add_submenu_page(
            'noonelite-audit-engine',
            __( 'Audits', 'noonelite-audit-engine' ),
            __( 'Audits', 'noonelite-audit-engine' ),
            'manage_options',
            'noonelite-audit-engine-audits',
            [ __CLASS__, 'render_page' ]
        );

        add_action( 'admin_enqueue_scripts', [ __CLASS__, 'enqueue_assets' ] );
    }

    /**
     * Enqueue audit page JS with localized strings.
     */
    public static function enqueue_assets( $hook ) {
        if ( 'site-audit_page_noonelite-audit-engine-audits' !== $hook ) {
            return;
        }

        wp_enqueue_script(
            'noonelite-audit-admin-audits',
            NOON_AUDIT_PLUGIN_URL . 'includes/js/admin-audits.js',
            [],
            NOON_AUDIT_VERSION,
            true
        );

        // Determine question count for editor.
        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $question_count = 0;
        if ( isset( $_GET['action'] ) && $_GET['action'] === 'edit' && isset( $_GET['audit_id'] ) ) {
            $audit = Noon_Audit_Database::get_audit_by_id( (int) $_GET['audit_id'] );
            if ( $audit ) {
                $questions = json_decode( $audit->questions, true );
                $question_count = is_array( $questions ) ? count( $questions ) : 0;
            }
        }
        // phpcs:enable

        wp_localize_script( 'noonelite-audit-admin-audits', 'noonAuditAudits', [
            'questionCount' => $question_count,
            'i18n'          => [
                'shortcodeCopied' => __( 'Shortcode copied to clipboard', 'noonelite-audit-engine' ),
                'colour'          => __( 'Colour', 'noonelite-audit-engine' ),
                'categoryName'    => __( 'Category name', 'noonelite-audit-engine' ),
                'remove'          => __( 'Remove', 'noonelite-audit-engine' ),
                'question'        => __( 'Question', 'noonelite-audit-engine' ),
                'category'        => __( 'Category:', 'noonelite-audit-engine' ),
                'questionText'    => __( 'Question text', 'noonelite-audit-engine' ),
                'addAnswer'       => __( '+ Add Answer', 'noonelite-audit-engine' ),
                'answerText'      => __( 'Answer text', 'noonelite-audit-engine' ),
                'pts'             => __( 'Pts', 'noonelite-audit-engine' ),
            ],
        ] );
    }

    // ─── Router ──────────────────────────────────────────────────────────────

    public static function render_page() {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $action = isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : 'list';
        $id     = (int) ( isset( $_GET['audit_id'] ) ? sanitize_text_field( wp_unslash( $_GET['audit_id'] ) ) : 0 );
        // phpcs:enable

        switch ( $action ) {
            case 'new':
                self::render_editor( null );
                break;
            case 'edit':
                $audit = Noon_Audit_Database::get_audit_by_id( $id );
                if ( ! $audit ) {
                    echo '<div class="wrap"><div class="notice notice-error"><p>' . esc_html__( 'Audit not found.', 'noonelite-audit-engine' ) . '</p></div></div>';
                    return;
                }
                self::render_editor( $audit );
                break;
            default:
                self::render_list();
                break;
        }
    }

    // ─── Action Handler ──────────────────────────────────────────────────────

    public static function handle_actions() {
        if ( ! isset( $_GET['page'] ) || $_GET['page'] !== 'noonelite-audit-engine-audits' ) {
            return;
        }

        if ( ! isset( $_POST['noon_audit_save'] ) && ! isset( $_GET['action'] ) ) {
            return;
        }

        // Save (create or update).
        if ( isset( $_POST['noon_audit_save'] ) ) {
            check_admin_referer( 'noon_audit_editor' );

            $post_data = wp_unslash( $_POST );
            $id = (int) ( $post_data['audit_id'] ?? 0 );

            // Parse categories from form.
            $categories = [];
            $cat_ids    = $post_data['cat_id'] ?? [];
            $cat_names  = $post_data['cat_name'] ?? [];
            $cat_colors = $post_data['cat_color'] ?? [];
            for ( $i = 0; $i < count( $cat_ids ); $i++ ) {
                if ( ! empty( $cat_names[ $i ] ) ) {
                    $categories[] = [
                        'id'    => sanitize_title( $cat_ids[ $i ] ?: $cat_names[ $i ] ),
                        'name'  => sanitize_text_field( $cat_names[ $i ] ),
                        'color' => sanitize_hex_color( $cat_colors[ $i ] ?? '#6366f1' ),
                    ];
                }
            }

            // Parse questions from form.
            $questions    = [];
            $q_ids        = $post_data['q_id'] ?? [];
            $q_cats       = $post_data['q_cat'] ?? [];
            $q_texts      = $post_data['q_text'] ?? [];
            $q_answers    = $post_data['q_answers'] ?? [];
            for ( $i = 0; $i < count( $q_texts ); $i++ ) {
                if ( empty( $q_texts[ $i ] ) ) continue;

                $answers = [];
                if ( isset( $q_answers[ $i ] ) ) {
                    $a_texts  = $q_answers[ $i ]['text'] ?? [];
                    $a_points = $q_answers[ $i ]['points'] ?? [];
                    for ( $j = 0; $j < count( $a_texts ); $j++ ) {
                        if ( ! empty( $a_texts[ $j ] ) ) {
                            $answers[] = [
                                'text'   => sanitize_text_field( $a_texts[ $j ] ),
                                'points' => (int) ( $a_points[ $j ] ?? 0 ),
                            ];
                        }
                    }
                }

                $questions[] = [
                    'id'         => sanitize_title( $q_ids[ $i ] ?: 'q-' . ( $i + 1 ) ),
                    'categoryId' => sanitize_title( $q_cats[ $i ] ?? '' ),
                    'text'       => sanitize_text_field( $q_texts[ $i ] ),
                    'answers'    => $answers,
                ];
            }

            // Parse band headlines.
            $band_headlines = [];
            foreach ( [ 'critical', 'high', 'moderate', 'low' ] as $band ) {
                $band_headlines[ $band ] = [
                    'title' => sanitize_text_field( $post_data["band_{$band}_title"] ?? '' ),
                    'text'  => sanitize_text_field( $post_data["band_{$band}_text"] ?? '' ),
                ];
            }

            $data = [
                'title'          => $post_data['title'] ?? '',
                'slug'           => $post_data['slug'] ?? '',
                'hook_text'      => $post_data['hook_text'] ?? '',
                'categories'     => $categories,
                'questions'      => $questions,
                'band_headlines' => $band_headlines,
                'status'         => $post_data['status'] ?? 'published',
            ];

            if ( $id > 0 ) {
                Noon_Audit_Database::update_audit( $id, $data );
                $redirect = admin_url( 'admin.php?page=noonelite-audit-engine-audits&action=edit&audit_id=' . $id . '&saved=1' );
            } else {
                $new_id = Noon_Audit_Database::insert_audit( $data );
                $redirect = admin_url( 'admin.php?page=noonelite-audit-engine-audits&action=edit&audit_id=' . $new_id . '&saved=1' );
            }

            wp_safe_redirect( $redirect );
            exit;
        }

        // Archive.
        if ( ( isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '' ) === 'archive' && isset( $_GET['audit_id'] ) ) {
            check_admin_referer( 'noon_audit_archive_' . (int) $_GET['audit_id'] );
            Noon_Audit_Database::update_audit( (int) sanitize_text_field( wp_unslash( $_GET['audit_id'] ) ), [ 'status' => 'archived' ] );
            wp_safe_redirect( admin_url( 'admin.php?page=noonelite-audit-engine-audits&archived=1' ) );
            exit;
        }

        // Restore.
        if ( ( isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '' ) === 'restore' && isset( $_GET['audit_id'] ) ) {
            check_admin_referer( 'noon_audit_restore_' . (int) $_GET['audit_id'] );
            Noon_Audit_Database::update_audit( (int) sanitize_text_field( wp_unslash( $_GET['audit_id'] ) ), [ 'status' => 'draft' ] );
            wp_safe_redirect( admin_url( 'admin.php?page=noonelite-audit-engine-audits&restored=1' ) );
            exit;
        }

        // Delete permanently (only from archive, never for seed audits).
        if ( ( isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '' ) === 'delete' && isset( $_GET['audit_id'] ) ) {
            check_admin_referer( 'noon_audit_delete_' . (int) $_GET['audit_id'] );
            $audit = Noon_Audit_Database::get_audit_by_id( (int) sanitize_text_field( wp_unslash( $_GET['audit_id'] ) ) );
            if ( $audit && ! empty( $audit->is_seed ) ) {
                wp_safe_redirect( admin_url( 'admin.php?page=noonelite-audit-engine-audits&error=seed_protected' ) );
                exit;
            }
            Noon_Audit_Database::delete_audit( (int) sanitize_text_field( wp_unslash( $_GET['audit_id'] ) ) );
            wp_safe_redirect( admin_url( 'admin.php?page=noonelite-audit-engine-audits&deleted=1' ) );
            exit;
        }

        // Duplicate.
        if ( ( isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '' ) === 'duplicate' && isset( $_GET['audit_id'] ) ) {
            check_admin_referer( 'noon_audit_dup_' . (int) $_GET['audit_id'] );
            $src = Noon_Audit_Database::get_audit_by_id( (int) sanitize_text_field( wp_unslash( $_GET['audit_id'] ) ) );
            if ( $src ) {
                Noon_Audit_Database::insert_audit( [
                    'title'          => $src->title . ' ' . __( '(Copy)', 'noonelite-audit-engine' ),
                    'slug'           => $src->slug . '-copy',
                    'hook_text'      => $src->hook_text,
                    'categories'     => json_decode( $src->categories, true ),
                    'questions'      => json_decode( $src->questions, true ),
                    'band_headlines' => json_decode( $src->band_headlines, true ),
                    'status'         => 'draft',
                ] );
            }
            wp_safe_redirect( admin_url( 'admin.php?page=noonelite-audit-engine-audits&duplicated=1' ) );
            exit;
        }
    }

    // ─── List View ───────────────────────────────────────────────────────────

    private static function render_list() {
        $audits = Noon_Audit_Database::get_all_audits();
        ?>
        <div class="wrap">
            <h1 class="wp-heading-inline"><?php esc_html_e( 'Audits', 'noonelite-audit-engine' ); ?></h1>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=noonelite-audit-engine-audits&action=new' ) ); ?>" class="page-title-action"><?php esc_html_e( 'Add New Audit', 'noonelite-audit-engine' ); ?></a>
            <hr class="wp-header-end">

            <?php // phpcs:disable WordPress.Security.NonceVerification.Recommended ?>
            <?php if ( isset( $_GET['archived'] ) ) : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Audit archived.', 'noonelite-audit-engine' ); ?></p></div>
            <?php endif; ?>
            <?php if ( isset( $_GET['restored'] ) ) : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Audit restored as draft.', 'noonelite-audit-engine' ); ?></p></div>
            <?php endif; ?>
            <?php if ( isset( $_GET['deleted'] ) ) : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Audit permanently deleted.', 'noonelite-audit-engine' ); ?></p></div>
            <?php endif; ?>
            <?php if ( isset( $_GET['duplicated'] ) ) : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Audit duplicated as draft.', 'noonelite-audit-engine' ); ?></p></div>
            <?php endif; ?>
            <?php // phpcs:enable ?>

            <?php
                $active_audits   = array_filter( $audits, fn( $a ) => $a->status !== 'archived' );
                $archived_audits = array_filter( $audits, fn( $a ) => $a->status === 'archived' );
            ?>

            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th style="width:25%"><?php esc_html_e( 'Title', 'noonelite-audit-engine' ); ?></th>
                        <th><?php esc_html_e( 'Slug', 'noonelite-audit-engine' ); ?></th>
                        <th><?php esc_html_e( 'Questions', 'noonelite-audit-engine' ); ?></th>
                        <th><?php esc_html_e( 'Categories', 'noonelite-audit-engine' ); ?></th>
                        <th><?php esc_html_e( 'Status', 'noonelite-audit-engine' ); ?></th>
                        <th><?php esc_html_e( 'Shortcode', 'noonelite-audit-engine' ); ?></th>
                        <th><?php esc_html_e( 'Actions', 'noonelite-audit-engine' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ( empty( $active_audits ) ) : ?>
                        <tr><td colspan="7"><?php
                            /* translators: %s: HTML link */
                            printf( esc_html__( 'No active audits. %s.', 'noonelite-audit-engine' ), '<a href="' . esc_url( admin_url( 'admin.php?page=noonelite-audit-engine-audits&action=new' ) ) . '">' . esc_html__( 'Create your first audit', 'noonelite-audit-engine' ) . '</a>' );
                            ?></td></tr>
                    <?php else : ?>
                        <?php foreach ( $active_audits as $audit ) :
                            $questions  = json_decode( $audit->questions, true );
                            $categories = json_decode( $audit->categories, true );
                            $q_count    = is_array( $questions ) ? count( $questions ) : 0;
                            $c_count    = is_array( $categories ) ? count( $categories ) : 0;

                            $edit_url    = admin_url( 'admin.php?page=noonelite-audit-engine-audits&action=edit&audit_id=' . $audit->id );
                            $archive_url = wp_nonce_url( admin_url( 'admin.php?page=noonelite-audit-engine-audits&action=archive&audit_id=' . $audit->id ), 'noon_audit_archive_' . $audit->id );
                            $dup_url     = wp_nonce_url( admin_url( 'admin.php?page=noonelite-audit-engine-audits&action=duplicate&audit_id=' . $audit->id ), 'noon_audit_dup_' . $audit->id );
                        ?>
                            <tr>
                                <td><strong><a href="<?php echo esc_url( $edit_url ); ?>"><?php echo esc_html( $audit->title ); ?></a></strong></td>
                                <td><code><?php echo esc_html( $audit->slug ); ?></code></td>
                                <td><?php echo esc_html( $q_count ); ?></td>
                                <td><?php echo esc_html( $c_count ); ?></td>
                                <td>
                                    <span style="color: <?php echo $audit->status === 'published' ? '#10b981' : '#f59e0b'; ?>; font-weight: 600;">
                                        <?php echo esc_html( ucfirst( $audit->status ) ); ?>
                                    </span>
                                </td>
                                <td>
                                    <code class="noon-shortcode-copy" style="cursor:pointer;" title="<?php esc_attr_e( 'Click to copy', 'noonelite-audit-engine' ); ?>">[noon_audit type="<?php echo esc_attr( $audit->slug ); ?>"]</code>
                                    <button type="button" class="button button-small noon-copy-btn" data-shortcode='[noon_audit type="<?php echo esc_attr( $audit->slug ); ?>"]' style="margin-left:4px;padding:0 6px;" title="<?php esc_attr_e( 'Copy shortcode', 'noonelite-audit-engine' ); ?>"><span class="dashicons dashicons-clipboard" style="font-size:14px;width:14px;height:14px;vertical-align:middle;"></span></button>
                                </td>
                                <td>
                                    <a href="<?php echo esc_url( $edit_url ); ?>"><?php esc_html_e( 'Edit', 'noonelite-audit-engine' ); ?></a> |
                                    <a href="<?php echo esc_url( $dup_url ); ?>"><?php esc_html_e( 'Duplicate', 'noonelite-audit-engine' ); ?></a> |
                                    <a href="<?php echo esc_url( $archive_url ); ?>" onclick="return confirm(<?php echo wp_json_encode( __( 'Archive this audit? It can be restored later.', 'noonelite-audit-engine' ) ); ?>)" style="color: #f59e0b;"><?php esc_html_e( 'Archive', 'noonelite-audit-engine' ); ?></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>

            <?php if ( ! empty( $archived_audits ) ) : ?>
            <details style="margin-top: 20px;">
                <summary style="cursor: pointer; font-weight: 600; color: #6b7280; padding: 8px 0;"><?php
                    /* translators: %d: number of audits */
                    printf( esc_html__( 'Archived Audits (%d)', 'noonelite-audit-engine' ), (int) count( $archived_audits ) );
                    ?></summary>
                <table class="wp-list-table widefat fixed striped" style="margin-top: 10px;">
                    <thead>
                        <tr>
                            <th style="width:25%"><?php esc_html_e( 'Title', 'noonelite-audit-engine' ); ?></th>
                            <th><?php esc_html_e( 'Slug', 'noonelite-audit-engine' ); ?></th>
                            <th><?php esc_html_e( 'Questions', 'noonelite-audit-engine' ); ?></th>
                            <th><?php esc_html_e( 'Categories', 'noonelite-audit-engine' ); ?></th>
                            <th><?php esc_html_e( 'Actions', 'noonelite-audit-engine' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $archived_audits as $audit ) :
                            $questions  = json_decode( $audit->questions, true );
                            $categories = json_decode( $audit->categories, true );
                            $q_count    = is_array( $questions ) ? count( $questions ) : 0;
                            $c_count    = is_array( $categories ) ? count( $categories ) : 0;
                            $edit_url    = admin_url( 'admin.php?page=noonelite-audit-engine-audits&action=edit&audit_id=' . $audit->id );
                            $restore_url = wp_nonce_url( admin_url( 'admin.php?page=noonelite-audit-engine-audits&action=restore&audit_id=' . $audit->id ), 'noon_audit_restore_' . $audit->id );
                            $del_url     = wp_nonce_url( admin_url( 'admin.php?page=noonelite-audit-engine-audits&action=delete&audit_id=' . $audit->id ), 'noon_audit_delete_' . $audit->id );
                        ?>
                            <tr style="opacity: 0.7;">
                                <td><strong><?php echo esc_html( $audit->title ); ?></strong></td>
                                <td><code><?php echo esc_html( $audit->slug ); ?></code></td>
                                <td><?php echo esc_html( $q_count ); ?></td>
                                <td><?php echo esc_html( $c_count ); ?></td>
                                <td>
                                    <a href="<?php echo esc_url( $edit_url ); ?>"><?php esc_html_e( 'Edit', 'noonelite-audit-engine' ); ?></a> |
                                    <a href="<?php echo esc_url( $restore_url ); ?>" style="color: #10b981;"><?php esc_html_e( 'Restore', 'noonelite-audit-engine' ); ?></a>
                                    <?php if ( empty( $audit->is_seed ) ) : ?>
                                        | <a href="<?php echo esc_url( $del_url ); ?>" onclick="return confirm(<?php echo wp_json_encode( __( 'Permanently delete this audit? This cannot be undone.', 'noonelite-audit-engine' ) ); ?>)" style="color: #dc2626;"><?php esc_html_e( 'Delete Permanently', 'noonelite-audit-engine' ); ?></a>
                                    <?php else : ?>
                                        | <span style="color: #9ca3af; font-style: italic;" title="<?php esc_attr_e( 'Built-in audits cannot be deleted', 'noonelite-audit-engine' ); ?>"><?php esc_html_e( 'Built-in', 'noonelite-audit-engine' ); ?></span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </details>
            <?php endif; ?>
            <div class="noon-toast" id="noon-toast"></div>
        </div>
        <?php
    }

    // ─── Editor View ─────────────────────────────────────────────────────────

    private static function render_editor( $audit ) {
        $is_new     = ! $audit;
        $title      = $is_new ? '' : $audit->title;
        $slug       = $is_new ? '' : $audit->slug;
        $hook_text  = $is_new ? '' : $audit->hook_text;
        $status     = $is_new ? 'published' : $audit->status;
        $categories = $is_new ? [] : json_decode( $audit->categories, true );
        $questions  = $is_new ? [] : json_decode( $audit->questions, true );
        $bands      = $is_new ? Noon_Audit_Database::default_band_headlines() : json_decode( $audit->band_headlines, true );
        $audit_id   = $is_new ? 0 : $audit->id;

        if ( ! is_array( $categories ) ) $categories = [];
        if ( ! is_array( $questions ) )  $questions  = [];
        if ( ! is_array( $bands ) )      $bands      = Noon_Audit_Database::default_band_headlines();
        ?>
        <div class="wrap">
            <h1><?php
                /* translators: %s: audit title */
                echo $is_new ? esc_html__( 'Create New Audit', 'noonelite-audit-engine' ) : sprintf( esc_html__( 'Edit Audit: %s', 'noonelite-audit-engine' ), esc_html( $title ) );
                ?></h1>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=noonelite-audit-engine-audits' ) ); ?>"><?php esc_html_e( '← Back to Audits', 'noonelite-audit-engine' ); ?></a>

            <?php // phpcs:disable WordPress.Security.NonceVerification.Recommended ?>
            <?php if ( isset( $_GET['saved'] ) ) : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Audit saved successfully.', 'noonelite-audit-engine' ); ?></p></div>
            <?php endif; ?>
            <?php // phpcs:enable ?>

            <form method="post" id="noon-audit-editor-form">
                <?php wp_nonce_field( 'noon_audit_editor' ); ?>
                <input type="hidden" name="audit_id" value="<?php echo esc_attr( $audit_id ); ?>">

                <!-- ── Basic Info ──────────────────────────────────────────── -->
                <div class="noon-editor-section">
                    <h2><?php esc_html_e( 'Basic Info', 'noonelite-audit-engine' ); ?></h2>
                    <table class="form-table">
                        <tr>
                            <th><label for="title"><?php esc_html_e( 'Title', 'noonelite-audit-engine' ); ?></label></th>
                            <td><input type="text" id="title" name="title" value="<?php echo esc_attr( $title ); ?>" class="regular-text" required></td>
                        </tr>
                        <tr>
                            <th><label for="slug"><?php esc_html_e( 'Slug', 'noonelite-audit-engine' ); ?></label></th>
                            <td>
                                <input type="text" id="slug" name="slug" value="<?php echo esc_attr( $slug ); ?>" class="regular-text" required>
                                <p class="description"><?php
                                    /* translators: %s: HTML snippet */
                                    printf( esc_html__( 'Used in shortcode: %s', 'noonelite-audit-engine' ), '<code>[noon_audit type="<span id="slug-preview">' . esc_html( $slug ) . '</span>"]</code>' );
                                    ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="hook_text"><?php esc_html_e( 'Hook Text', 'noonelite-audit-engine' ); ?></label></th>
                            <td><textarea id="hook_text" name="hook_text" rows="3" class="large-text"><?php echo esc_textarea( $hook_text ); ?></textarea>
                            <p class="description"><?php esc_html_e( 'Shown on the landing screen before the user starts the quiz.', 'noonelite-audit-engine' ); ?></p></td>
                        </tr>
                        <tr>
                            <th><label for="status"><?php esc_html_e( 'Status', 'noonelite-audit-engine' ); ?></label></th>
                            <td>
                                <select id="status" name="status">
                                    <option value="published" <?php selected( $status, 'published' ); ?>><?php esc_html_e( 'Published', 'noonelite-audit-engine' ); ?></option>
                                    <option value="draft" <?php selected( $status, 'draft' ); ?>><?php esc_html_e( 'Draft', 'noonelite-audit-engine' ); ?></option>
                                    <option value="archived" <?php selected( $status, 'archived' ); ?>><?php esc_html_e( 'Archived', 'noonelite-audit-engine' ); ?></option>
                                </select>
                            </td>
                        </tr>
                    </table>
                </div>

                <!-- ── Categories ──────────────────────────────────────────── -->
                <div class="noon-editor-section">
                    <h2><?php esc_html_e( 'Categories', 'noonelite-audit-engine' ); ?></h2>
                    <p class="description"><?php esc_html_e( 'Define scoring categories. Questions are grouped by category on the results screen.', 'noonelite-audit-engine' ); ?></p>
                    <div id="noon-categories-list">
                        <?php foreach ( $categories as $i => $cat ) : ?>
                            <div class="noon-cat-row">
                                <input type="hidden" name="cat_id[]" value="<?php echo esc_attr( $cat['id'] ); ?>">
                                <input type="color" name="cat_color[]" value="<?php echo esc_attr( $cat['color'] ?? '#6366f1' ); ?>" title="Colour">
                                <input type="text" name="cat_name[]" value="<?php echo esc_attr( $cat['name'] ); ?>" placeholder="Category name">
                                <button type="button" class="noon-remove-btn" onclick="this.parentElement.remove()" title="Remove">×</button>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <button type="button" class="button noon-add-btn" onclick="noonAddCategory()"><?php esc_html_e( '+ Add Category', 'noonelite-audit-engine' ); ?></button>
                </div>

                <!-- ── Questions ───────────────────────────────────────────── -->
                <div class="noon-editor-section">
                    <h2><?php esc_html_e( 'Questions', 'noonelite-audit-engine' ); ?></h2>
                    <p class="description"><?php esc_html_e( 'Each question has 4 answer options with point values. Higher points = better score.', 'noonelite-audit-engine' ); ?></p>
                    <div id="noon-questions-list">
                        <?php foreach ( $questions as $qi => $q ) : ?>
                            <div class="noon-question-block">
                                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
                                    <strong><?php
                                        /* translators: %d: question number */
                                        printf( esc_html__( 'Question %d', 'noonelite-audit-engine' ), (int) $qi + 1 );
                                        ?></strong>
                                    <button type="button" class="noon-remove-btn" onclick="this.closest('.noon-question-block').remove(); noonReindex()" title="<?php esc_attr_e( 'Remove', 'noonelite-audit-engine' ); ?>">×</button>
                                </div>
                                <input type="hidden" name="q_id[]" value="<?php echo esc_attr( $q['id'] ); ?>">
                                <p>
                                    <label>Category:</label>
                                    <select name="q_cat[]" class="noon-q-cat-select">
                                        <?php foreach ( $categories as $cat ) : ?>
                                            <option value="<?php echo esc_attr( $cat['id'] ); ?>" <?php selected( $q['categoryId'] ?? '', $cat['id'] ); ?>><?php echo esc_html( $cat['name'] ); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </p>
                                <p><input type="text" name="q_text[]" value="<?php echo esc_attr( $q['text'] ); ?>" class="large-text" placeholder="Question text"></p>
                                <div class="noon-answers-list">
                                    <?php
                                    $letters = ['A', 'B', 'C', 'D', 'E', 'F'];
                                    foreach ( ( $q['answers'] ?? [] ) as $ai => $a ) : ?>
                                        <div class="noon-answer-row">
                                            <span style="font-weight:600; min-width:20px;"><?php echo esc_html( $letters[ $ai ] ?? '' ); ?></span>
                                            <input type="text" name="q_answers[<?php echo esc_attr( $qi ); ?>][text][]" value="<?php echo esc_attr( $a['text'] ); ?>" placeholder="Answer text">
                                            <input type="number" name="q_answers[<?php echo esc_attr( $qi ); ?>][points][]" value="<?php echo esc_attr( $a['points'] ); ?>" placeholder="Pts" min="0" max="10">
                                            <button type="button" class="noon-remove-btn" onclick="this.parentElement.remove()" title="Remove">×</button>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <button type="button" class="button button-small" onclick="noonAddAnswer(this)" style="margin-top:5px;"><?php esc_html_e( '+ Add Answer', 'noonelite-audit-engine' ); ?></button>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <button type="button" class="button noon-add-btn" onclick="noonAddQuestion()"><?php esc_html_e( '+ Add Question', 'noonelite-audit-engine' ); ?></button>
                </div>

                <!-- ── Band Headlines ──────────────────────────────────────── -->
                <div class="noon-editor-section">
                    <h2><?php esc_html_e( 'Score Band Headlines', 'noonelite-audit-engine' ); ?></h2>
                    <p class="description"><?php esc_html_e( 'Customise the headline shown for each risk band on the results screen.', 'noonelite-audit-engine' ); ?></p>
                    <?php foreach ( [ 'critical' => '0–30', 'high' => '31–55', 'moderate' => '56–75', 'low' => '76–100' ] as $band => $range ) : ?>
                        <div class="noon-band-row">
                            <label><?php echo esc_html( ucfirst( $band ) ); ?> <small>(<?php echo esc_html( $range ); ?>)</small></label>
                            <input type="text" name="band_<?php echo esc_attr( $band ); ?>_title" value="<?php echo esc_attr( $bands[ $band ]['title'] ?? '' ); ?>" placeholder="Title" style="max-width:200px;">
                            <input type="text" name="band_<?php echo esc_attr( $band ); ?>_text" value="<?php echo esc_attr( $bands[ $band ]['text'] ?? '' ); ?>" placeholder="Description text">
                        </div>
                    <?php endforeach; ?>
                </div>

                <?php submit_button( $is_new ? 'Create Audit' : 'Save Changes', 'primary', 'noon_audit_save' ); ?>
            </form>
        </div>
        <?php
    }
}
