<?php
/**
 * Plugin Name: Mark Bogner's Story Prompts
 * Description: Generate AI-powered writing prompts based on selected story genres using the Anthropic Claude API.
 * Version: 1.5.2
 * Author: Mark Bogner
 * License: GPL-2.0+
 */

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

define( 'ASPG_VERSION', '1.2.0' );
define( 'ASPG_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'ASPG_PLUGIN_URL', plugin_dir_url( __FILE__ ) );

// ── Color scheme defaults & helpers ────────────────────────────────────────

function aspg_default_colors() {
    return [
        'accent'       => [ 'label' => 'Accent / Primary',       'default' => '#b8842a' ],
        'accent_dark'  => [ 'label' => 'Accent Dark',            'default' => '#8a5f18' ],
        'background'   => [ 'label' => 'Widget Background',      'default' => '#fdf6e8' ],
        'surface'      => [ 'label' => 'Input / Surface',        'default' => '#f5ead0' ],
        'border'       => [ 'label' => 'Border',                 'default' => '#c9a05a' ],
        'text_main'    => [ 'label' => 'Main Text',              'default' => '#1a1209' ],
        'text_muted'   => [ 'label' => 'Muted / Label Text',     'default' => '#7a6545' ],
        'button_text'  => [ 'label' => 'Button Text',            'default' => '#ffffff' ],
        'success'      => [ 'label' => 'Success / Confirm',      'default' => '#3a7a4a' ],
        'error'        => [ 'label' => 'Error',                  'default' => '#c0392b' ],
        'prompt_text'  => [ 'label' => 'Prompt Quote Text',      'default' => '#1a1209' ],
        'attribution'  => [ 'label' => 'Attribution Text',       'default' => '#7a6545' ],
    ];
}

function aspg_get_colors() {
    $saved    = get_option( 'aspg_colors', [] );
    $defaults = aspg_default_colors();
    $colors   = [];
    foreach ( $defaults as $key => $meta ) {
        $colors[ $key ] = ( isset( $saved[ $key ] ) && preg_match( '/^#[0-9a-fA-F]{6}$/', $saved[ $key ] ) )
            ? $saved[ $key ]
            : $meta['default'];
    }
    return $colors;
}

// Inject dynamic CSS variables into the frontend <head>
add_action( 'wp_head', 'aspg_inject_color_css' );
function aspg_inject_color_css() {
    $c = aspg_get_colors();

    // Convert border hex to rgba for transparency
    $border_hex = ltrim( $c['border'], '#' );
    $br = hexdec( substr( $border_hex, 0, 2 ) );
    $bg = hexdec( substr( $border_hex, 2, 2 ) );
    $bb = hexdec( substr( $border_hex, 4, 2 ) );

    echo '<style id="aspg-custom-colors">
.aspg-widget, .aspg-signup-widget {
    --aspg-ink:        ' . esc_attr( $c['text_main'] )   . ';
    --aspg-parchment:  ' . esc_attr( $c['background'] )  . ';
    --aspg-cream:      ' . esc_attr( $c['surface'] )     . ';
    --aspg-amber:      ' . esc_attr( $c['accent'] )      . ';
    --aspg-amber-dark: ' . esc_attr( $c['accent_dark'] ) . ';
    --aspg-amber-glow: rgba(' . (int)$br . ',' . (int)$bg . ',' . (int)$bb . ',0.15);
    --aspg-border:     rgba(' . (int)$br . ',' . (int)$bg . ',' . (int)$bb . ',0.5);
    --aspg-text-muted: ' . esc_attr( $c['text_muted'] )  . ';
    --aspg-success:    ' . esc_attr( $c['success'] )     . ';
    --aspg-error-col:  ' . esc_attr( $c['error'] )       . ';
}
.aspg-btn { color: ' . esc_attr( $c['button_text'] ) . ' !important; }
.aspg-prompt-text { color: ' . esc_attr( $c['prompt_text'] ) . ' !important; }
.aspg-attribution { color: ' . esc_attr( $c['attribution'] ) . ' !important; }
</style>' . "\n";
}

register_activation_hook( __FILE__, 'aspg_create_subscribers_table' );

function aspg_create_subscribers_table() {
    global $wpdb;
    $table_name      = $wpdb->prefix . 'aspg_subscribers';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS {$table_name} (
        id            BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        name          VARCHAR(150)        NOT NULL,
        email         VARCHAR(200)        NOT NULL,
        subscribed_at DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY  (id),
        UNIQUE KEY   email (email)
    ) {$charset_collate};";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );
}

// ── Admin settings page ────────────────────────────────────────────────────

add_action( 'admin_menu', 'aspg_add_settings_page' );
function aspg_add_settings_page() {
    add_options_page(
        'Mark Bogner\'s Story Prompts Settings',
        'Story Prompt AI',
        'manage_options',
        'aspg-settings',
        'aspg_render_settings_page'
    );

    add_menu_page(
        'Mailing List Subscribers',
        'Story Prompt Subscribers',
        'manage_options',
        'aspg-subscribers',
        'aspg_render_subscribers_page',
        'dashicons-email-alt',
        30
    );

    add_menu_page(
        'Story Prompt Color Customizer',
        'Story Prompt Colors',
        'manage_options',
        'aspg-colors',
        'aspg_render_colors_page',
        'dashicons-art',
        31
    );
}

add_action( 'admin_init', 'aspg_register_settings' );
function aspg_register_settings() {
    register_setting( 'aspg_settings_group', 'aspg_anthropic_api_key', [
        'sanitize_callback' => 'sanitize_text_field',
    ]);

    add_settings_section( 'aspg_main_section', 'API Configuration', null, 'aspg-settings' );

    add_settings_field(
        'aspg_anthropic_api_key',
        'Anthropic API Key',
        'aspg_api_key_field_cb',
        'aspg-settings',
        'aspg_main_section'
    );
}

function aspg_api_key_field_cb() {
    $key = get_option( 'aspg_anthropic_api_key', '' );
    echo '<input type="password" name="aspg_anthropic_api_key" value="' . esc_attr( $key ) . '" class="regular-text" placeholder="sk-ant-..." />';
    echo '<p class="description">Enter your <a href="https://console.anthropic.com/" target="_blank">Anthropic API key</a>. It is stored securely in the database.</p>';
}

function aspg_render_settings_page() {
    ?>
    <div class="wrap">
        <h1>Mark Bogner's Story Prompts — Settings</h1>
        <form method="post" action="options.php">
            <?php
            settings_fields( 'aspg_settings_group' );
            do_settings_sections( 'aspg-settings' );
            submit_button( 'Save Settings' );
            ?>
        </form>
        <hr>
        <h2>Shortcode Usage</h2>
        <p>Paste the shortcode below anywhere on a page or post:</p>
        <code>[story_prompt_generator]</code>
        <p>You can also pass optional attributes:</p>
        <ul style="list-style:disc;margin-left:1.5em;">
            <li><code>title="Your Title"</code> — Override the widget heading.</li>
            <li><code>button_text="Generate"</code> — Override the button label.</li>
        </ul>
        <p>Example: <code>[story_prompt_generator title="Spark Your Story" button_text="Inspire Me"]</code></p>
        <hr>
        <h2>Mailing List Sign-Up Shortcode</h2>
        <p>Add the sign-up form to any page with:</p>
        <code>[mailer_signup]</code>
        <p>Collected subscribers are viewable under <strong>Story Prompt Subscribers</strong> in the admin menu.</p>
    </div>
    <?php
}

// ── Shortcode ──────────────────────────────────────────────────────────────

add_shortcode( 'story_prompt_generator', 'aspg_render_shortcode' );
function aspg_render_shortcode( $atts ) {
    $atts = shortcode_atts([
        'title'       => 'Story Prompt Generator',
        'button_text' => 'Generate Prompt',
    ], $atts, 'story_prompt_generator' );

    wp_enqueue_style(  'aspg-style',  ASPG_PLUGIN_URL . 'assets/style.css',  [], ASPG_VERSION );
    wp_enqueue_script( 'aspg-script', ASPG_PLUGIN_URL . 'assets/script.js', [], ASPG_VERSION, true );

    wp_localize_script( 'aspg-script', 'ASPG', [
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'nonce'    => wp_create_nonce( 'aspg_generate_nonce' ),
    ]);

    $genres = aspg_get_genres();

    ob_start();
    ?>
    <div class="aspg-widget" role="region" aria-label="Story Prompt Generator">
        <div class="aspg-inner">
            <div class="aspg-header">
                <div class="aspg-quill-icon" aria-hidden="true">
                    <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M38 6C28 10 18 22 14 38" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/>
                        <path d="M38 6C34 16 26 24 14 38" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-dasharray="2 3"/>
                        <path d="M14 38 L11 43 L17 40 Z" fill="currentColor"/>
                        <path d="M38 6 C42 2 46 4 44 8 C40 8 38 10 38 6Z" fill="currentColor" opacity="0.5"/>
                    </svg>
                </div>
                <h2 class="aspg-title"><?php echo esc_html( $atts['title'] ); ?></h2>
                <p class="aspg-subtitle">Pick a genre and let my brain craft your next story spark.</p>
            </div>

            <div class="aspg-form">
                <div class="aspg-select-wrapper">
                    <label for="aspg-genre" class="aspg-label">Story Genre</label>
                    <div class="aspg-select-box">
                        <select id="aspg-genre" name="genre" aria-label="Select a story genre">
                            <option value="">— Choose a genre —</option>
                            <?php foreach ( $genres as $value => $label ) : ?>
                                <option value="<?php echo esc_attr( $value ); ?>"><?php echo esc_html( $label ); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <span class="aspg-chevron" aria-hidden="true">
                            <svg viewBox="0 0 20 20" fill="none"><path d="M5 7.5L10 12.5L15 7.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
                        </span>
                    </div>
                </div>

                <button id="aspg-generate-btn" class="aspg-btn" type="button" disabled>
                    <span class="aspg-btn-text"><?php echo esc_html( $atts['button_text'] ); ?></span>
                    <span class="aspg-btn-icon" aria-hidden="true">
                        <svg viewBox="0 0 20 20" fill="none"><path d="M4 10h12M11 5l5 5-5 5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
                    </span>
                </button>
            </div>

            <div class="aspg-result-area" aria-live="polite" aria-atomic="true">
                <div class="aspg-result-idle">
                    <span class="aspg-dot"></span><span class="aspg-dot"></span><span class="aspg-dot"></span>
                    <p>Your prompt will appear here.</p>
                </div>
                <div class="aspg-result-loading" hidden>
                    <div class="aspg-spinner" role="status" aria-label="Generating prompt…">
                        <svg viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" fill="none" stroke="currentColor" stroke-width="4" stroke-dasharray="90 60"/></svg>
                    </div>
                    <p>Crafting your prompt…</p>
                </div>
                <div class="aspg-result-output" hidden>
                    <div class="aspg-genre-badge" id="aspg-genre-badge"></div>
                    <blockquote class="aspg-prompt-text" id="aspg-prompt-text"></blockquote>
                    <button class="aspg-copy-btn" id="aspg-copy-btn" type="button" aria-label="Copy prompt to clipboard">
                        <svg viewBox="0 0 20 20" fill="none"><rect x="7" y="7" width="10" height="12" rx="2" stroke="currentColor" stroke-width="1.8"/><path d="M13 7V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2h2" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
                        Copy
                    </button>
                </div>
                <div class="aspg-result-error" hidden>
                    <span class="aspg-error-icon" aria-hidden="true">⚠</span>
                    <p id="aspg-error-msg"></p>
                </div>
            </div>
        </div>

        <p class="aspg-attribution">Writing prompts generated by the mind of Mark Bogner.</p>
    </div>
    <?php
    return ob_get_clean();
}

// ── Genre list ─────────────────────────────────────────────────────────────

function aspg_get_genres() {
    return [
        'literary-fiction'  => 'Literary Fiction',
        'fantasy'           => 'Fantasy',
        'science-fiction'   => 'Science Fiction',
        'horror'            => 'Horror',
        'mystery'           => 'Mystery & Thriller',
        'romance'           => 'Romance',
        'historical-fiction'=> 'Historical Fiction',
        'adventure'         => 'Adventure',
        'crime'             => 'Crime & Noir',
        'magical-realism'   => 'Magical Realism',
        'dystopian'         => 'Dystopian',
        'comedy'            => 'Comedy & Satire',
        'western'           => 'Western',
        'young-adult'       => 'Young Adult',
        'childrens'         => 'Children\'s Story',
    ];
}

// ── AJAX handler ───────────────────────────────────────────────────────────

add_action( 'wp_ajax_aspg_generate',        'aspg_ajax_generate' );
add_action( 'wp_ajax_nopriv_aspg_generate', 'aspg_ajax_generate' );

function aspg_ajax_generate() {
    check_ajax_referer( 'aspg_generate_nonce', 'nonce' );

    $genre = isset( $_POST['genre'] ) ? sanitize_text_field( wp_unslash( $_POST['genre'] ) ) : '';

    if ( empty( $genre ) ) {
        wp_send_json_error( [ 'message' => 'Please select a genre.' ] );
    }

    $genres      = aspg_get_genres();
    $genre_label = isset( $genres[ $genre ] ) ? $genres[ $genre ] : $genre;

    $api_key = get_option( 'aspg_anthropic_api_key', '' );
    if ( empty( $api_key ) ) {
        wp_send_json_error( [ 'message' => 'API key not configured. Please contact the site administrator.' ] );
    }

    $prompt = sprintf(
        'You are a creative writing coach. Generate a single compelling writing prompt (1–2 sentences) for the "%s" genre. ' .
        'The prompt should be vivid, specific, and immediately inspire a writer. ' .
        'Return ONLY the prompt text — no labels, no quotes, no preamble.',
        $genre_label
    );

    $response = wp_remote_post( 'https://api.anthropic.com/v1/messages', [
        'timeout' => 30,
        'headers' => [
            'Content-Type'      => 'application/json',
            'x-api-key'         => $api_key,
            'anthropic-version' => '2023-06-01',
        ],
        'body' => wp_json_encode([
            'model'      => 'claude-sonnet-4-20250514',
            'max_tokens' => 200,
            'messages'   => [
                [ 'role' => 'user', 'content' => $prompt ],
            ],
        ]),
    ]);

    if ( is_wp_error( $response ) ) {
        wp_send_json_error( [ 'message' => 'Network error: ' . $response->get_error_message() ] );
    }

    $code = wp_remote_retrieve_response_code( $response );
    $body = json_decode( wp_remote_retrieve_body( $response ), true );

    if ( 200 !== (int) $code ) {
        $err = isset( $body['error']['message'] ) ? $body['error']['message'] : 'Unknown API error.';
        wp_send_json_error( [ 'message' => $err ] );
    }

    $text = isset( $body['content'][0]['text'] ) ? trim( $body['content'][0]['text'] ) : '';

    if ( empty( $text ) ) {
        wp_send_json_error( [ 'message' => 'The AI returned an empty response. Please try again.' ] );
    }

    wp_send_json_success([
        'prompt' => $text,
        'genre'  => $genre_label,
    ]);
}

// ═══════════════════════════════════════════════════════════════════════════
// MAILING LIST — Sign-up shortcode, AJAX handler, Admin list view
// ═══════════════════════════════════════════════════════════════════════════

// ── [mailer_signup] shortcode ──────────────────────────────────────────────

add_shortcode( 'mailer_signup', 'aspg_render_mailer_signup' );
function aspg_render_mailer_signup() {
    wp_enqueue_style(  'aspg-style',        ASPG_PLUGIN_URL . 'assets/style.css',  [], ASPG_VERSION );
    wp_enqueue_script( 'aspg-signup-script', ASPG_PLUGIN_URL . 'assets/signup.js', [], ASPG_VERSION, true );

    wp_localize_script( 'aspg-signup-script', 'ASPG_SIGNUP', [
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'nonce'    => wp_create_nonce( 'aspg_signup_nonce' ),
    ]);

    ob_start();
    ?>
    <div class="aspg-signup-widget" role="region" aria-label="Mailing List Sign Up">
        <div class="aspg-signup-inner">
            <div class="aspg-signup-header">
                <div class="aspg-envelope-icon" aria-hidden="true">
                    <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <rect x="4" y="10" width="40" height="28" rx="3" stroke="currentColor" stroke-width="2.5"/>
                        <path d="M4 13l20 14 20-14" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </div>
                <h2 class="aspg-signup-title">Mailer Sign Up</h2>
                <p class="aspg-signup-tagline">Sign up here, to be added to the mailing list — and receive writing prompts directly in your inbox, weekly.</p>
            </div>

            <div class="aspg-signup-form" id="aspg-signup-form">
                <div class="aspg-field-group">
                    <label for="aspg-signup-name" class="aspg-label">Your Name</label>
                    <input type="text" id="aspg-signup-name" class="aspg-input" placeholder="Jane Austen" autocomplete="name" />
                </div>
                <div class="aspg-field-group">
                    <label for="aspg-signup-email" class="aspg-label">Email Address</label>
                    <input type="email" id="aspg-signup-email" class="aspg-input" placeholder="jane@example.com" autocomplete="email" />
                </div>
                <button id="aspg-signup-btn" class="aspg-btn aspg-signup-btn" type="button">
                    <span class="aspg-btn-text">Join the Mailing List</span>
                    <span class="aspg-btn-icon" aria-hidden="true">
                        <svg viewBox="0 0 20 20" fill="none"><path d="M4 10h12M11 5l5 5-5 5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
                    </span>
                </button>
                <p class="aspg-signup-notice" id="aspg-signup-notice" aria-live="polite" hidden></p>
            </div>

            <div class="aspg-signup-success" id="aspg-signup-success" hidden>
                <div class="aspg-success-icon" aria-hidden="true">
                    <svg viewBox="0 0 48 48" fill="none"><circle cx="24" cy="24" r="20" stroke="currentColor" stroke-width="2.5"/><path d="M14 24l7 7 13-13" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
                </div>
                <h3 class="aspg-success-title">You're on the list!</h3>
                <p class="aspg-success-msg">Thanks for signing up. Watch your inbox for weekly writing prompts.</p>
            </div>
        </div>
        <p class="aspg-attribution">Writing prompts generated by the mind of Mark Bogner.</p>
    </div>
    <?php
    return ob_get_clean();
}

// ── AJAX: save subscriber ──────────────────────────────────────────────────

add_action( 'wp_ajax_aspg_signup',        'aspg_ajax_signup' );
add_action( 'wp_ajax_nopriv_aspg_signup', 'aspg_ajax_signup' );

function aspg_ajax_signup() {
    check_ajax_referer( 'aspg_signup_nonce', 'nonce' );

    $name  = isset( $_POST['name'] )  ? sanitize_text_field( wp_unslash( $_POST['name'] ) )  : '';
    $email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) )       : '';

    if ( empty( $name ) ) {
        wp_send_json_error( [ 'message' => 'Please enter your name.' ] );
    }

    if ( empty( $email ) || ! is_email( $email ) ) {
        wp_send_json_error( [ 'message' => 'Please enter a valid email address.' ] );
    }

    global $wpdb;
    $table = $wpdb->prefix . 'aspg_subscribers';

    // Check for duplicate
    $existing = $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$table} WHERE email = %s LIMIT 1",
        $email
    ) );

    if ( $existing ) {
        wp_send_json_error( [ 'message' => 'This email address is already subscribed!' ] );
    }

    $inserted = $wpdb->insert(
        $table,
        [
            'name'          => $name,
            'email'         => $email,
            'subscribed_at' => current_time( 'mysql' ),
        ],
        [ '%s', '%s', '%s' ]
    );

    if ( false === $inserted ) {
        wp_send_json_error( [ 'message' => 'Something went wrong. Please try again.' ] );
    }

    wp_send_json_success( [ 'message' => 'Subscribed successfully!' ] );
}

// ── Admin: subscribers list page ───────────────────────────────────────────

function aspg_render_subscribers_page() {
    global $wpdb;
    $table = $wpdb->prefix . 'aspg_subscribers';

    // Handle CSV export
    if ( isset( $_GET['aspg_export'] ) && 'csv' === $_GET['aspg_export'] ) {
        check_admin_referer( 'aspg_export_csv' );
        $rows = $wpdb->get_results( "SELECT name, email, subscribed_at FROM {$table} ORDER BY subscribed_at DESC", ARRAY_A );
        header( 'Content-Type: text/csv; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename="story-prompt-subscribers.csv"' );
        $out = fopen( 'php://output', 'w' );
        fputcsv( $out, [ 'Name', 'Email', 'Subscribed At' ] );
        foreach ( $rows as $row ) {
            fputcsv( $out, $row );
        }
        fclose( $out );
        exit;
    }

    // Handle single delete
    if ( isset( $_GET['aspg_delete'] ) && isset( $_GET['_wpnonce'] ) ) {
        if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'aspg_delete_subscriber' ) ) {
            $wpdb->delete( $table, [ 'id' => absint( $_GET['aspg_delete'] ) ], [ '%d' ] );
            echo '<div class="notice notice-success is-dismissible"><p>Subscriber deleted.</p></div>';
        }
    }

    $subscribers = $wpdb->get_results( "SELECT * FROM {$table} ORDER BY subscribed_at DESC" );
    $count       = count( $subscribers );
    $export_url  = wp_nonce_url( admin_url( 'admin.php?page=aspg-subscribers&aspg_export=csv' ), 'aspg_export_csv' );
    ?>
    <div class="wrap">
        <h1 style="display:flex;align-items:center;gap:10px;">
            <span class="dashicons dashicons-email-alt" style="font-size:1.6rem;height:auto;width:auto;color:#b8842a;"></span>
            Story Prompt Subscribers
        </h1>
        <p style="color:#666;">
            <strong><?php echo esc_html( $count ); ?></strong> subscriber<?php echo 1 !== $count ? 's' : ''; ?> collected.
            <?php if ( $count > 0 ) : ?>
                &nbsp;|&nbsp; <a href="<?php echo esc_url( $export_url ); ?>">⬇ Export as CSV</a>
            <?php endif; ?>
        </p>

        <?php if ( empty( $subscribers ) ) : ?>
            <p style="font-style:italic;color:#999;">No subscribers yet. Add the <code>[mailer_signup]</code> shortcode to a page to start collecting sign-ups.</p>
        <?php else : ?>
            <table class="widefat fixed striped" style="max-width:860px;">
                <thead>
                    <tr>
                        <th style="width:40px;">#</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Signed Up</th>
                        <th style="width:80px;">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $subscribers as $i => $sub ) :
                        $delete_url = wp_nonce_url(
                            admin_url( 'admin.php?page=aspg-subscribers&aspg_delete=' . absint( $sub->id ) ),
                            'aspg_delete_subscriber'
                        );
                    ?>
                    <tr>
                        <td><?php echo esc_html( $i + 1 ); ?></td>
                        <td><?php echo esc_html( $sub->name ); ?></td>
                        <td><a href="mailto:<?php echo esc_attr( $sub->email ); ?>"><?php echo esc_html( $sub->email ); ?></a></td>
                        <td><?php echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $sub->subscribed_at ) ) ); ?></td>
                        <td><a href="<?php echo esc_url( $delete_url ); ?>" onclick="return confirm('Delete this subscriber?');" style="color:#c0392b;">Delete</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    <?php
}

// ═══════════════════════════════════════════════════════════════════════════
// COLOR CUSTOMIZER — Admin page, save handler, AJAX reset
// ═══════════════════════════════════════════════════════════════════════════

// Register the color option
add_action( 'admin_init', 'aspg_register_color_settings' );
function aspg_register_color_settings() {
    register_setting( 'aspg_colors_group', 'aspg_colors', [
        'sanitize_callback' => 'aspg_sanitize_colors',
    ]);
}

function aspg_sanitize_colors( $input ) {
    $clean    = [];
    $defaults = aspg_default_colors();
    foreach ( $defaults as $key => $meta ) {
        if ( isset( $input[ $key ] ) && preg_match( '/^#[0-9a-fA-F]{6}$/', $input[ $key ] ) ) {
            $clean[ $key ] = $input[ $key ];
        } else {
            $clean[ $key ] = $meta['default'];
        }
    }
    return $clean;
}

// AJAX: reset colors to defaults
add_action( 'wp_ajax_aspg_reset_colors', 'aspg_ajax_reset_colors' );
function aspg_ajax_reset_colors() {
    check_ajax_referer( 'aspg_reset_colors_nonce', 'nonce' );
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( [ 'message' => 'Unauthorized.' ] );
    }
    delete_option( 'aspg_colors' );
    $defaults = aspg_default_colors();
    $colors   = [];
    foreach ( $defaults as $key => $meta ) {
        $colors[ $key ] = $meta['default'];
    }
    wp_send_json_success( [ 'colors' => $colors ] );
}

// Enqueue admin color page assets
add_action( 'admin_enqueue_scripts', 'aspg_enqueue_color_admin_assets' );
function aspg_enqueue_color_admin_assets( $hook ) {
    if ( 'toplevel_page_aspg-colors' !== $hook ) return;
    // Google Fonts for preview
    wp_enqueue_style( 'aspg-google-fonts', 'https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,400;0,600;1,400;1,600&family=DM+Sans:wght@400;500&display=swap', [], null );
    // Frontend widget styles (for live preview)
    wp_enqueue_style( 'aspg-style',          ASPG_PLUGIN_URL . 'assets/style.css',       [], ASPG_VERSION );
    wp_enqueue_style( 'aspg-color-admin-css', ASPG_PLUGIN_URL . 'assets/color-admin.css', ['aspg-style'], ASPG_VERSION );
    wp_enqueue_script( 'aspg-color-admin-js',  ASPG_PLUGIN_URL . 'assets/color-admin.js',  [], ASPG_VERSION, true );
    wp_localize_script( 'aspg-color-admin-js', 'ASPG_COLORS', [
        'nonce'      => wp_create_nonce( 'aspg_reset_colors_nonce' ),
        'ajax_url'   => admin_url( 'admin-ajax.php' ),
        'plugin_url' => ASPG_PLUGIN_URL,
        'defaults'   => array_map( function($m) { return $m['default']; }, aspg_default_colors() ),
    ]);
}

// Color admin page renderer
function aspg_render_colors_page() {
    $colors   = aspg_get_colors();
    $defaults = aspg_default_colors();
    $saved    = get_option( 'aspg_colors', [] );
    $is_custom = ! empty( $saved );
    ?>
    <div class="wrap aspg-color-wrap">
        <h1 class="aspg-color-heading">
            <span class="dashicons dashicons-art" style="font-size:1.6rem;height:auto;width:auto;vertical-align:middle;margin-right:6px;"></span>
            Widget Color Customizer
        </h1>
        <p class="aspg-color-intro">Customize every color used in the story prompt and sign-up widgets to match your site's theme. The live preview updates as you pick colors.</p>

        <?php if ( isset( $_GET['settings-updated'] ) ) : ?>
            <div class="notice notice-success is-dismissible"><p>&#10003; Color scheme saved successfully.</p></div>
        <?php endif; ?>

        <div class="aspg-color-layout">

            <!-- Controls panel -->
            <div class="aspg-color-panel">
                <form method="post" action="options.php" id="aspg-color-form">
                    <?php settings_fields( 'aspg_colors_group' ); ?>

                    <?php
                    $groups = [
                        'Brand & Accent' => [ 'accent', 'accent_dark' ],
                        'Backgrounds'    => [ 'background', 'surface' ],
                        'Text'           => [ 'text_main', 'text_muted', 'prompt_text', 'attribution' ],
                        'UI Elements'    => [ 'border', 'button_text' ],
                        'Status Colors'  => [ 'success', 'error' ],
                    ];
                    foreach ( $groups as $group_label => $keys ) :
                    ?>
                        <div class="aspg-color-group">
                            <h3 class="aspg-color-group-label"><?php echo esc_html( $group_label ); ?></h3>
                            <?php foreach ( $keys as $key ) :
                                $meta  = $defaults[ $key ];
                                $value = $colors[ $key ];
                            ?>
                            <div class="aspg-color-row" data-key="<?php echo esc_attr( $key ); ?>">
                                <label class="aspg-color-label" for="aspg-color-<?php echo esc_attr( $key ); ?>">
                                    <?php echo esc_html( $meta['label'] ); ?>
                                </label>
                                <div class="aspg-color-input-wrap">
                                    <input
                                        type="color"
                                        id="aspg-color-<?php echo esc_attr( $key ); ?>"
                                        name="aspg_colors[<?php echo esc_attr( $key ); ?>]"
                                        value="<?php echo esc_attr( $value ); ?>"
                                        class="aspg-color-picker"
                                        data-key="<?php echo esc_attr( $key ); ?>"
                                        data-default="<?php echo esc_attr( $meta['default'] ); ?>"
                                    />
                                    <span class="aspg-color-hex"><?php echo esc_html( strtoupper( $value ) ); ?></span>
                                    <button type="button" class="aspg-reset-single" data-key="<?php echo esc_attr( $key ); ?>" title="Reset to default">&#8635;</button>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endforeach; ?>

                    <div class="aspg-color-actions">
                        <?php submit_button( 'Save Color Scheme', 'primary', 'submit', false ); ?>
                        <button type="button" id="aspg-reset-all" class="button button-secondary">
                            &#8635; Reset All to Defaults
                        </button>
                    </div>

                    <p class="aspg-scheme-status <?php echo $is_custom ? 'is-custom' : 'is-default'; ?>">
                        <?php echo $is_custom ? '&#10022; Custom color scheme active' : 'Using default color scheme'; ?>
                    </p>
                </form>
            </div><!-- .aspg-color-panel -->

            <!-- Live preview panel -->
            <div class="aspg-color-preview-wrap">
                <h3 class="aspg-preview-label">&#9654; Live Preview</h3>

                <style id="aspg-preview-style"></style>

                <!-- Story prompt widget preview -->
                <div class="aspg-widget aspg-preview-widget">
                    <div class="aspg-inner">
                        <div class="aspg-header">
                            <div class="aspg-quill-icon">
                                <svg viewBox="0 0 48 48" fill="none"><path d="M38 6C28 10 18 22 14 38" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/><path d="M38 6C34 16 26 24 14 38" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-dasharray="2 3"/><path d="M14 38 L11 43 L17 40 Z" fill="currentColor"/><path d="M38 6 C42 2 46 4 44 8 C40 8 38 10 38 6Z" fill="currentColor" opacity="0.5"/></svg>
                            </div>
                            <h2 class="aspg-title">Story Prompt Generator</h2>
                            <p class="aspg-subtitle">Pick a genre and let my brain craft your next story spark.</p>
                        </div>
                        <div class="aspg-form">
                            <div class="aspg-select-wrapper">
                                <label class="aspg-label">Story Genre</label>
                                <div class="aspg-select-box">
                                    <select disabled><option>&#8212; Choose a genre &#8212;</option></select>
                                    <span class="aspg-chevron"><svg viewBox="0 0 20 20" fill="none"><path d="M5 7.5L10 12.5L15 7.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
                                </div>
                            </div>
                            <button class="aspg-btn" disabled style="opacity:1;">
                                <span class="aspg-btn-text">Generate Prompt</span>
                                <span class="aspg-btn-icon"><svg viewBox="0 0 20 20" fill="none"><path d="M4 10h12M11 5l5 5-5 5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
                            </button>
                        </div>
                        <div class="aspg-result-area" style="margin:0 2rem 2rem;border-style:solid;">
                            <div style="padding:1.5rem;width:100%;">
                                <div class="aspg-genre-badge">Fantasy</div>
                                <blockquote class="aspg-prompt-text">A cartographer discovers that the blank spaces on ancient maps are not unexplored — they were deliberately erased by someone who needed those places to stay hidden.</blockquote>
                                <button class="aspg-copy-btn" style="pointer-events:none;">
                                    <svg viewBox="0 0 20 20" fill="none" style="width:14px;height:14px;"><rect x="7" y="7" width="10" height="12" rx="2" stroke="currentColor" stroke-width="1.8"/><path d="M13 7V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2h2" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
                                    Copy
                                </button>
                            </div>
                        </div>
                    </div>
                    <p class="aspg-attribution">Writing prompts generated by the mind of Mark Bogner.</p>
                </div>

                <!-- Sign-up widget preview -->
                <div class="aspg-signup-widget aspg-preview-widget" style="margin-top:1.25rem;">
                    <div class="aspg-signup-inner">
                        <div class="aspg-signup-header">
                            <div class="aspg-envelope-icon">
                                <svg viewBox="0 0 48 48" fill="none"><rect x="4" y="10" width="40" height="28" rx="3" stroke="currentColor" stroke-width="2.5"/><path d="M4 13l20 14 20-14" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
                            </div>
                            <h2 class="aspg-signup-title">Mailer Sign Up</h2>
                            <p class="aspg-signup-tagline">Sign up here, to be added to the mailing list &#8212; and receive writing prompts directly in your inbox, weekly.</p>
                        </div>
                        <div class="aspg-signup-form" style="pointer-events:none;">
                            <div class="aspg-field-group">
                                <label class="aspg-label">Your Name</label>
                                <input type="text" class="aspg-input" placeholder="Jane Austen" disabled />
                            </div>
                            <div class="aspg-field-group">
                                <label class="aspg-label">Email Address</label>
                                <input type="email" class="aspg-input" placeholder="jane@example.com" disabled />
                            </div>
                            <button class="aspg-btn" disabled style="opacity:1;">
                                <span class="aspg-btn-text">Join the Mailing List</span>
                                <span class="aspg-btn-icon"><svg viewBox="0 0 20 20" fill="none"><path d="M4 10h12M11 5l5 5-5 5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
                            </button>
                        </div>
                    </div>
                    <p class="aspg-attribution">Writing prompts generated by the mind of Mark Bogner.</p>
                </div>

            </div><!-- .aspg-color-preview-wrap -->

        </div><!-- .aspg-color-layout -->
    </div>
    <?php
}
