<?php
/**
 * Custom Meta Boxes for `proto_project` Post Type
 * High-Impact Interactive Screen & Variation Flow Builder
 * Brand Identity: Bowden Works
 */

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

class Proto_Preview_Meta_Boxes {

    public function init() {
        add_action('add_meta_boxes', [$this, 'register_meta_boxes']);
        add_action('save_post_proto_project', [$this, 'save_meta_boxes']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_meta_box_assets']);
    }

    public function enqueue_meta_box_assets($hook) {
        global $post_type;
        if ($post_type === 'proto_project') {
            wp_enqueue_media();
            wp_enqueue_script('jquery-ui-sortable');
            wp_enqueue_style('proto-preview-fonts', 'https://fonts.googleapis.com/css2?family=EB+Garamond:ital,wght@0,500;0,600;0,700;0,800;1,500;1,600;1,700&family=Radio+Canada:ital,wght@0,400;0,500;0,600;0,700;1,400;1,600&family=JetBrains+Mono:wght@400;500;700&display=swap', [], null);
        }
    }

    public function register_meta_boxes() {
        // 1. Side Meta Box: Client Share & Player Launchpad
        add_meta_box(
            'proto_project_share',
            __('🚀 InVision Prototype Player', 'proto-preview'),
            [$this, 'render_share_meta_box'],
            'proto_project',
            'side',
            'high'
        );

        // 2. Side Meta Box: Stakeholders & Email Notifications
        add_meta_box(
            'proto_project_stakeholders',
            __('👥 Team & Email Notifications', 'proto-preview'),
            [$this, 'render_stakeholders_meta_box'],
            'proto_project',
            'side',
            'default'
        );

        // 3. Main Meta Box: Screens & Variations Builder
        add_meta_box(
            'proto_project_screens',
            __('🖼️ Screen Flows & Design Variations Builder', 'proto-preview'),
            [$this, 'render_screens_meta_box'],
            'proto_project',
            'normal',
            'high'
        );

        // 4. Main Meta Box: Design Story & Client Walkthrough Steps
        add_meta_box(
            'proto_project_story_steps',
            __('🎬 Design Story & Client Walkthrough', 'proto-preview'),
            [$this, 'render_story_steps_meta_box'],
            'proto_project',
            'normal',
            'high'
        );
    }

    public function render_share_meta_box($post) {
        wp_nonce_field('proto_project_meta_save', 'proto_project_meta_nonce');

        $token = get_post_meta($post->ID, '_proto_share_token', true);
        if (empty($token)) {
            $token = bin2hex(random_bytes(16));
        }

        $player_url = home_url('/?proto_preview=1&project_id=' . $post->ID);
        ?>
        <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
            
            <p style="margin-top: 0; font-size: 12px; color: #475569; line-height: 1.4;">
                Launch this project directly inside the full-screen InVision review player.
            </p>

            <a href="<?php echo esc_url($player_url); ?>" target="_blank" class="button button-primary button-large" style="width: 100%; text-align: center; font-weight: bold; background: #b02b2b; border-color: #872e21; box-shadow: 0 2px 6px rgba(176,43,43,0.3); margin-bottom: 12px; display: flex; align-items: center; justify-content: center; gap: 6px;">
                🚀 Open InVision Player ↗
            </a>

            <div style="border-top: 1px solid #e2e8f0; padding-top: 10px; margin-top: 10px;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
                    <label style="font-size: 11px; font-weight: bold; color: #334155;">
                        DIRECT CLIENT LINK
                    </label>
                    <span style="font-size: 10px; color: #059669; font-weight: bold; background: #ecfdf5; padding: 1px 6px; border-radius: 4px; border: 1px solid #a7f3d0;">Live Active</span>
                </div>
                <input type="text" readonly value="<?php echo esc_attr($player_url); ?>" id="proto-share-input" style="width: 100%; font-size: 11px; background: #fff; padding: 6px 8px; border: 1px solid #cbd5e1; border-radius: 6px; font-family: monospace; color: #334155;" onclick="this.select();">
                
                <button type="button" class="button button-secondary" style="width: 100%; margin-top: 8px; font-size: 12px; font-weight: 600;" onclick="navigator.clipboard.writeText(document.getElementById('proto-share-input').value); alert('Client link copied to clipboard!');">
                    📋 Copy Share Link
                </button>
            </div>

            <input type="hidden" name="proto_share_token" value="<?php echo esc_attr($token); ?>">
        </div>
        <?php
    }

    public function render_stakeholders_meta_box($post) {
        $assigned_users = get_post_meta($post->ID, '_proto_assigned_users', true);
        if (!is_array($assigned_users)) {
            $current_u = get_current_user_id();
            $assigned_users = $current_u ? [$current_u] : [1];
        }

        $notification_emails = get_post_meta($post->ID, '_proto_notification_emails', true);
        $enable_notifications = get_post_meta($post->ID, '_proto_enable_notifications', true);
        if ($enable_notifications === '') {
            $enable_notifications = '1';
        }

        $client_name = get_post_meta($post->ID, '_proto_client_name', true);
        if (empty($client_name)) {
            $client_terms = wp_get_post_terms($post->ID, 'proto_client', ['fields' => 'names']);
            $client_name = !empty($client_terms) ? $client_terms[0] : '';
        }

        $all_users = get_users(['orderby' => 'display_name', 'order' => 'ASC']);
        ?>
        <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
            
            <!-- Client Organization / Company Name -->
            <div style="margin-bottom: 14px;">
                <label style="display: block; font-size: 11px; font-weight: bold; color: #334155; margin-bottom: 4px; text-transform: uppercase; letter-spacing: 0.3px;">
                    Client Organization / Company
                </label>
                <input type="text" name="proto_client_name" value="<?php echo esc_attr($client_name); ?>" placeholder="e.g. Nexus Financial Inc., Acme Corp" style="width: 100%; font-size: 12px; padding: 6px 8px; border: 1px solid #cbd5e1; border-radius: 6px; color: #1e293b; background: #fff;">
                <p style="margin: 3px 0 0 0; font-size: 10px; color: #64748b;">The client organization or company this prototype belongs to.</p>
            </div>

            <!-- Global Notification Toggle -->
            <div style="margin-bottom: 14px; background: #fbeeed; border: 1px solid rgba(176,43,43,0.25); border-radius: 8px; padding: 10px 12px;">
                <label style="font-size: 12px; font-weight: 700; color: #b02b2b; cursor: pointer; display: flex; align-items: center; gap: 6px;">
                    <input type="checkbox" name="proto_enable_notifications" value="1" <?php checked($enable_notifications, '1'); ?>>
                    <span>🔔 Enable Email Notifications</span>
                </label>
                <p style="margin: 4px 0 0 22px; font-size: 10px; color: #7f1d1d; line-height: 1.3;">
                    Sends instant, branded email alerts when someone leaves a review pin or replies.
                </p>
            </div>

            <!-- Assigned Team Members / WP Users -->
            <div style="margin-bottom: 14px;">
                <label style="display: block; font-size: 11px; font-weight: bold; color: #334155; margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.3px;">
                    Assigned Stakeholders & Roles
                </label>
                <div style="max-height: 200px; overflow-y: auto; background: #ffffff; border: 1px solid #cbd5e1; border-radius: 6px; padding: 6px;">
                    <?php if (!empty($all_users)): ?>
                        <?php 
                        $user_project_roles = get_post_meta($post->ID, '_proto_user_project_roles', true) ?: [];
                        ?>
                        <?php foreach ($all_users as $u): ?>
                            <?php 
                            $is_checked = in_array($u->ID, $assigned_users);
                            $current_role = $user_project_roles[$u->ID] ?? ($u->ID == 1 ? 'Designer' : ($u->user_email === 'rian@rian.ca' ? 'Project Manager' : (user_can($u->ID, 'manage_options') ? 'Designer' : 'Client Reviewer')));
                            ?>
                            <div style="display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 5px 8px; border-radius: 6px; font-size: 11px; color: #1e293b; margin-bottom: 4px; background: <?php echo $is_checked ? '#f8fafc' : '#ffffff'; ?>; border: 1px solid <?php echo $is_checked ? '#cbd5e1' : '#f1f5f9'; ?>;">
                                <label style="display: flex; align-items: center; gap: 8px; cursor: pointer; min-width: 0; flex: 1;">
                                    <input type="checkbox" name="proto_assigned_users[]" value="<?php echo esc_attr($u->ID); ?>" <?php checked($is_checked); ?>>
                                    <div style="min-width: 0;">
                                        <strong style="display: block; font-size: 11px; color: #0f172a; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"><?php echo esc_html($u->display_name); ?></strong>
                                        <span style="color: #64748b; font-size: 9.5px; font-family: monospace;"><?php echo esc_html($u->user_email); ?></span>
                                    </div>
                                </label>
                                <select name="proto_user_project_roles[<?php echo esc_attr($u->ID); ?>]" style="font-size: 10px; font-weight: 600; padding: 1px 4px; border: 1px solid #cbd5e1; border-radius: 4px; background: #ffffff; color: #334155; height: 22px; line-height: 1.2;">
                                    <option value="Decision Maker" <?php selected($current_role, 'Decision Maker'); ?>>⭐ Decision Maker</option>
                                    <option value="Client Reviewer" <?php selected($current_role, 'Client Reviewer'); ?>>Client Reviewer</option>
                                    <option value="Client" <?php selected($current_role, 'Client'); ?>>Client</option>
                                    <option value="Designer" <?php selected($current_role, 'Designer'); ?>>Designer</option>
                                    <option value="Project Manager" <?php selected($current_role, 'Project Manager'); ?>>Project Manager</option>
                                    <option value="Product Lead" <?php selected($current_role, 'Product Lead'); ?>>Product Lead</option>
                                    <option value="Lead Developer" <?php selected($current_role, 'Lead Developer'); ?>>Lead Developer</option>
                                </select>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p style="font-size: 11px; color: #94a3b8; margin: 0;">No users found.</p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Client Stakeholders & Reviewers Repeater -->
            <div style="margin-bottom: 12px;">
                <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px;">
                    <label style="font-size: 11px; font-weight: bold; color: #334155; text-transform: uppercase; letter-spacing: 0.3px;">
                        Client Stakeholders (Emails)
                    </label>
                    <button type="button" class="button button-small" onclick="window.protoAddStakeholderRow()" style="font-size: 10.5px; font-weight: 700; height: 22px; line-height: 20px; padding: 0 8px; background: #f8fafc; border-color: #cbd5e1; color: #0f172a;">
                        + Add Stakeholder
                    </button>
                </div>

                <div id="proto-stakeholders-repeater-container" style="display: flex; flex-direction: column; gap: 6px;">
                    <!-- Javascript populates repeater rows -->
                </div>
                <p style="margin: 4px 0 0 0; font-size: 10px; color: #64748b;">Add external client team members, emails, and their review role.</p>
            </div>

            <?php
            $client_stakeholders = get_post_meta($post->ID, '_proto_client_stakeholders', true);
            if (!is_array($client_stakeholders) || empty($client_stakeholders)) {
                $notification_emails_raw = get_post_meta($post->ID, '_proto_notification_emails', true);
                if (!empty($notification_emails_raw)) {
                    $raw_list = explode(',', $notification_emails_raw);
                    $client_stakeholders = [];
                    foreach ($raw_list as $em) {
                        $em_clean = trim($em);
                        if (!empty($em_clean)) {
                            $client_stakeholders[] = [
                                'name'  => ucwords(str_replace(['.', '_', '-'], ' ', explode('@', $em_clean)[0])),
                                'email' => $em_clean,
                                'role'  => 'Client Reviewer'
                            ];
                        }
                    }
                } else {
                    $client_stakeholders = [];
                }
            }
            ?>

            <script>
            (function() {
                const initialStakeholders = <?php echo json_encode($client_stakeholders); ?>;
                const container = document.getElementById('proto-stakeholders-repeater-container');

                window.protoAddStakeholderRow = function(data = {}) {
                    if (!container) return;
                    const idx = container.querySelectorAll('.proto-stakeholder-row').length;
                    const name = data.name || '';
                    const email = data.email || '';
                    const role = data.role || 'Client Reviewer';

                    const row = document.createElement('div');
                    row.className = 'proto-stakeholder-row';
                    row.style = 'background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 6px 8px; display: flex; flex-direction: column; gap: 4px;';
                    row.innerHTML = `
                        <div style="display: flex; gap: 4px;">
                            <input type="text" name="proto_client_stakeholders[${idx}][name]" value="${name.replace(/"/g, '&quot;')}" placeholder="Name (e.g. John Doe)" style="flex: 1; font-size: 11px; padding: 2px 6px; border: 1px solid #cbd5e1; border-radius: 4px; background: #fff; height: 24px;">
                            <select name="proto_client_stakeholders[${idx}][role]" style="font-size: 10px; font-weight: 600; padding: 1px 4px; border: 1px solid #cbd5e1; border-radius: 4px; background: #fff; height: 24px;">
                                <option value="Decision Maker" ${role === 'Decision Maker' ? 'selected' : ''}>⭐ Decision Maker</option>
                                <option value="Client Reviewer" ${role === 'Client Reviewer' ? 'selected' : ''}>Client Reviewer</option>
                                <option value="Client" ${role === 'Client' ? 'selected' : ''}>Client</option>
                                <option value="Product Lead" ${role === 'Product Lead' ? 'selected' : ''}>Product Lead</option>
                                <option value="Lead Developer" ${role === 'Lead Developer' ? 'selected' : ''}>Lead Developer</option>
                            </select>
                        </div>
                        <div style="display: flex; align-items: center; gap: 4px;">
                            <input type="email" name="proto_client_stakeholders[${idx}][email]" value="${email.replace(/"/g, '&quot;')}" placeholder="Email (e.g. john@nexuspay.io)" style="flex: 1; font-size: 11px; font-family: monospace; padding: 2px 6px; border: 1px solid #cbd5e1; border-radius: 4px; background: #fff; height: 24px;">
                            <button type="button" onclick="this.closest('.proto-stakeholder-row').remove(); window.protoReindexStakeholderRows();" style="background: none; border: none; color: #94a3b8; font-size: 14px; cursor: pointer; padding: 2px 6px; border-radius: 4px; line-height: 1;" title="Remove stakeholder" onmouseover="this.style.color='#b02b2b'" onmouseout="this.style.color='#94a3b8'">
                                ✕
                            </button>
                        </div>
                    `;
                    container.appendChild(row);
                    window.protoReindexStakeholderRows();
                };

                window.protoReindexStakeholderRows = function() {
                    if (!container) return;
                    const rows = container.querySelectorAll('.proto-stakeholder-row');
                    rows.forEach((row, i) => {
                        const nameInput = row.querySelector('input[name*="[name]"]');
                        const roleSelect = row.querySelector('select[name*="[role]"]');
                        const emailInput = row.querySelector('input[name*="[email]"]');
                        if (nameInput) nameInput.name = `proto_client_stakeholders[${i}][name]`;
                        if (roleSelect) roleSelect.name = `proto_client_stakeholders[${i}][role]`;
                        if (emailInput) emailInput.name = `proto_client_stakeholders[${i}][email]`;
                    });
                };

                if (Array.isArray(initialStakeholders) && initialStakeholders.length > 0) {
                    initialStakeholders.forEach(stk => window.protoAddStakeholderRow(stk));
                }
            })();
            </script>

        </div>
        <?php
    }

    public function render_screens_meta_box($post) {
        $screens = get_post_meta($post->ID, '_proto_screens', true);
        $plugin_url = PROTO_PREVIEW_PLUGIN_URL;

        if (!is_array($screens) || empty($screens)) {
            $screens = [
                [
                    'id' => 1,
                    'name' => 'Homepage',
                    'slug' => 'home',
                    'layouts' => [
                        [
                            'id' => 1,
                            'version' => 'Option 1',
                            'name' => 'Homepage 1 (Modern SaaS)',
                            'file_path' => $plugin_url . 'layouts/saas-v1.html',
                            'badge' => 'Clean & High Conversion',
                            'color' => 'red',
                            'is_selected_choice' => 1
                        ],
                        [
                            'id' => 2,
                            'version' => 'Option 2',
                            'name' => 'Homepage 2 (Dark Cyber AI)',
                            'file_path' => $plugin_url . 'layouts/dark-v2.html',
                            'badge' => 'Dark Mode & High Tech',
                            'color' => 'cyan',
                            'is_selected_choice' => 0
                        ]
                    ]
                ]
            ];
        }
        ?>
        <div id="proto-screens-builder-wrapper" style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: -6px -12px -12px -12px; background: #f8fafc; padding: 20px; border-radius: 0 0 4px 4px;">
            
            <!-- Step-by-Step Workflow Banner -->
            <div style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); color: #ffffff; border-radius: 12px; padding: 18px 22px; margin-bottom: 24px; box-shadow: 0 4px 14px rgba(15,23,42,0.15);">
                <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px;">
                    <div>
                        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px;">
                            <span style="background: #b02b2b; color: #fff; font-size: 11px; font-weight: 800; padding: 2px 8px; border-radius: 4px; text-transform: uppercase;">InVision Workflow</span>
                            <h3 style="margin: 0; font-size: 15px; font-weight: bold; color: #ffffff;">How Prototype Presentations Work</h3>
                        </div>
                        <p style="margin: 0; font-size: 12px; color: #94a3b8; max-width: 780px; line-height: 1.4;">
                            1. Define user journey screens (e.g. <strong>Homepage</strong>, <strong>Pricing</strong>) ➔ 
                            2. Attach design options (Option A, Option B) with prototype HTML files ➔ 
                            3. Share client link for interactive playback, visual pin commenting, and 1-click option approval.
                        </p>
                    </div>

                    <button type="button" class="button button-primary button-large" onclick="window.protoAddScreen();" style="background: #b02b2b; border-color: #872e21; font-weight: bold; font-size: 13px; padding: 8px 18px; height: auto; box-shadow: 0 2px 8px rgba(176,43,43,0.4);">
                        + Add Screen Flow
                    </button>
                </div>
            </div>

            <!-- Screens List Container -->
            <div id="proto-screens-list" style="display: flex; flex-direction: column; gap: 24px;">
                <?php foreach ($screens as $s_idx => $screen) : 
                    $screen_name = $screen['name'] ?? 'Screen';
                    $screen_slug = $screen['slug'] ?? 'screen';
                    $layouts = $screen['layouts'] ?? [];
                ?>
                    <div class="proto-screen-block" data-screen-index="<?php echo $s_idx; ?>" style="background: #ffffff; border: 2px solid #e2e8f0; border-radius: 14px; padding: 20px; box-shadow: 0 4px 14px rgba(15,23,42,0.04);">
                        
                        <!-- Screen Header Bar -->
                        <div style="display: flex; align-items: center; justify-content: space-between; border-bottom: 2px solid #f1f5f9; padding-bottom: 16px; margin-bottom: 18px; flex-wrap: wrap; gap: 12px;">
                            <div style="display: flex; align-items: center; gap: 14px; flex-wrap: wrap;">
                                <span style="background: #0f172a; color: #ffffff; font-size: 12px; font-weight: 800; padding: 7px 14px; border-radius: 8px; letter-spacing: 0.5px; display: inline-flex; align-items: center; gap: 4px;">
                                    📁 SCREEN #<span class="screen-num-badge"><?php echo ($s_idx + 1); ?></span>
                                </span>
                                
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">Screen Flow Title</label>
                                    <input type="text" name="proto_screens[<?php echo $s_idx; ?>][name]" value="<?php echo esc_attr($screen_name); ?>" placeholder="e.g. 01. Homepage, 02. Pricing & Plans" style="font-weight: bold; font-size: 14px; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 6px 12px; width: 240px; color: #0f172a;" required>
                                </div>

                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">URL Slug</label>
                                    <div style="display: flex; align-items: center; background: #f8fafc; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 0 8px;">
                                        <span style="color: #94a3b8; font-size: 13px; font-family: monospace; font-weight: bold;">/</span>
                                        <input type="text" name="proto_screens[<?php echo $s_idx; ?>][slug]" value="<?php echo esc_attr($screen_slug); ?>" placeholder="slug" style="font-size: 12px; border: none; background: transparent; padding: 6px 4px; width: 100px; color: #475569; font-family: monospace; outline: none;">
                                    </div>
                                </div>

                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">Sitemap Nav Group</label>
                                    <select name="proto_screens[<?php echo $s_idx; ?>][nav_group]" style="font-size: 11px; font-weight: 700; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 4px 6px; color: #0f172a; height: 32px; background: #fff;">
                                        <option value="primary" <?php selected($screen['nav_group'] ?? 'primary', 'primary'); ?>>🏛️ Primary Nav</option>
                                        <option value="subpage" <?php selected($screen['nav_group'] ?? '', 'subpage'); ?>>↳ Sub-page</option>
                                        <option value="footer" <?php selected($screen['nav_group'] ?? '', 'footer'); ?>>📄 Footer & Legal</option>
                                    </select>
                                </div>

                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">Parent Page</label>
                                    <input type="text" name="proto_screens[<?php echo $s_idx; ?>][parent_name]" value="<?php echo esc_attr($screen['parent_name'] ?? ''); ?>" placeholder="e.g. Services" style="font-size: 11px; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 5px 8px; width: 110px; color: #334155;">
                                </div>

                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">Dev / Staging URL</label>
                                    <input type="url" name="proto_screens[<?php echo $s_idx; ?>][dev_url]" value="<?php echo esc_url($screen['dev_url'] ?? ''); ?>" placeholder="https://staging.site.com/page" style="font-size: 11px; font-family: monospace; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 5px 8px; width: 170px; color: #334155;">
                                </div>

                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">Workflow Phase</label>
                                    <select name="proto_screens[<?php echo $s_idx; ?>][status]" style="font-size: 11px; font-weight: 700; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 4px 6px; color: #0f172a; height: 32px; background: #fff;">
                                        <option value="building_prototype" <?php selected($screen['status'] ?? 'building_prototype', 'building_prototype'); ?>>🎨 Building Prototype</option>
                                        <option value="waiting_approval" <?php selected($screen['status'] ?? '', 'waiting_approval'); ?>>⏳ Waiting for Approval</option>
                                        <option value="building_page" <?php selected($screen['status'] ?? '', 'building_page'); ?>>⚡ Building Page</option>
                                        <option value="waiting_review" <?php selected($screen['status'] ?? '', 'waiting_review'); ?>>🔍 Waiting for Review</option>
                                        <option value="done" <?php selected($screen['status'] ?? '', 'done'); ?>>✅ Done</option>
                                        <option value="later" <?php selected($screen['status'] ?? '', 'later'); ?>>⏸️ Later</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <button type="button" class="button button-secondary" onclick="window.protoAddVariation(this);" style="font-size: 12px; font-weight: 700; border-color: #cbd5e1; padding: 4px 12px; height: auto;">
                                    + Add Variation Option
                                </button>
                                <button type="button" class="button button-link-delete" style="color: #ef4444; font-size: 12px; font-weight: 700; padding: 4px 8px;" onclick="if(confirm('Delete this entire screen and its variations?')) { this.closest('.proto-screen-block').remove(); window.protoReindex(); }">
                                    Delete Screen
                                </button>
                            </div>
                        </div>

                        <!-- Variations Grid under this Screen -->
                        <div class="proto-variations-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 16px;">
                            <?php foreach ($layouts as $l_idx => $layout) : 
                                $v_name = $layout['name'] ?? 'Variation';
                                $v_ver = $layout['version'] ?? ('Option ' . ($l_idx + 1));
                                $v_file = $layout['file_path'] ?? '';
                                $v_badge = $layout['badge'] ?? '';
                                $v_chosen = !empty($layout['is_selected_choice']);
                            ?>
                                <div class="proto-variation-card" style="background: #f8fafc; border: 2px solid #e2e8f0; border-radius: 12px; padding: 16px; display: flex; flex-direction: column; justify-content: space-between; box-shadow: 0 2px 6px rgba(0,0,0,0.03); transition: all 0.2s ease;">
                                    
                                    <div>
                                        <!-- Header Pill -->
                                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
                                            <span style="background: #fbeeed; color: #b02b2b; font-size: 11px; font-weight: 800; padding: 3px 10px; border-radius: 6px; border: 1px solid rgba(176,43,43,0.25);">
                                                <?php echo esc_html($v_ver); ?>
                                            </span>
                                            <span style="font-size: 10px; font-weight: 700; color: #64748b; background: #ffffff; padding: 2px 8px; border-radius: 4px; border: 1px solid #e2e8f0;">Option #<?php echo ($l_idx + 1); ?></span>
                                        </div>

                                        <?php 
                                        $is_img = preg_match('/\.(png|jpe?g|webp|svg|gif)($|\?)/i', $v_file); 
                                        ?>
                                        <!-- Live Mockup Thumbnail -->
                                        <div class="proto-thumb-preview-box" style="margin-bottom: 12px; <?php echo empty($v_file) ? 'display:none;' : ''; ?>">
                                            <div style="width: 100%; height: 110px; background: #e2e8f0; border-radius: 8px; overflow: hidden; display: flex; align-items: center; justify-content: center; border: 1px solid #cbd5e1; position: relative;">
                                                <img src="<?php echo esc_url($v_file); ?>" class="proto-img-thumb" style="width: 100%; height: 100%; object-fit: cover; object-position: top; <?php echo $is_img ? '' : 'display:none;'; ?>">
                                                <div class="proto-html-thumb" style="font-size: 11px; color: #475569; font-weight: bold; <?php echo $is_img ? 'display:none;' : 'display:flex;'; ?> align-items: center; gap: 6px;">
                                                    <span style="font-size: 16px;">🌐</span> HTML Prototype
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Variation Title -->
                                        <div style="margin-bottom: 12px;">
                                            <label style="display: block; font-size: 11px; font-weight: bold; color: #334155; margin-bottom: 4px;">VARIATION TITLE</label>
                                            <input type="text" name="proto_screens[<?php echo $s_idx; ?>][layouts][<?php echo $l_idx; ?>][name]" value="<?php echo esc_attr($v_name); ?>" placeholder="e.g. Option A (Modern SaaS Clean)" style="width: 100%; font-size: 13px; font-weight: bold; padding: 7px 10px; border: 1px solid #cbd5e1; border-radius: 6px; color: #0f172a;" required>
                                        </div>

                                        <!-- Prototype File Path / URL with Media Uploader Button -->
                                        <div style="margin-bottom: 12px;">
                                            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
                                                <label style="font-size: 11px; font-weight: bold; color: #334155;">SOURCE (IMAGE MOCKUP / HTML / URL)</label>
                                                <button type="button" class="button button-small" onclick="window.protoOpenMediaUploader(this);" style="font-size: 10px; font-weight: 600; color: #b02b2b;">
                                                    📁 Choose / Upload Image
                                                </button>
                                            </div>
                                            
                                            <input type="text" name="proto_screens[<?php echo $s_idx; ?>][layouts][<?php echo $l_idx; ?>][file_path]" value="<?php echo esc_attr($v_file); ?>" placeholder="e.g. https://.../mockup.png or layouts/saas-v1.html" style="width: 100%; font-size: 11px; font-family: monospace; padding: 6px 8px; border: 1px solid #cbd5e1; border-radius: 6px; color: #334155; background: #fff;" onchange="window.protoUpdateCardThumb(this);" required>
                                        </div>

                                        <!-- Badge / Tag -->
                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: bold; color: #334155; margin-bottom: 4px;">DESIGN CONCEPT TAG / BADGE</label>
                                            <input type="text" name="proto_screens[<?php echo $s_idx; ?>][layouts][<?php echo $l_idx; ?>][badge]" value="<?php echo esc_attr($v_badge); ?>" placeholder="e.g. Clean & High Conversion" style="width: 100%; font-size: 12px; padding: 6px 10px; border: 1px solid #cbd5e1; border-radius: 6px; color: #334155; background: #fff;">
                                        </div>

                                        <input type="hidden" name="proto_screens[<?php echo $s_idx; ?>][layouts][<?php echo $l_idx; ?>][version]" value="<?php echo esc_attr($v_ver); ?>">
                                    </div>

                                    <!-- Card Footer Actions -->
                                    <div style="margin-top: 16px; padding-top: 12px; border-top: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: space-between;">
                                        <?php if (!empty($v_file)) : ?>
                                            <a href="<?php echo esc_url($v_file); ?>" target="_blank" style="font-size: 11px; color: #0284c7; text-decoration: none; font-weight: 600;">
                                                🔍 Preview Source ↗
                                            </a>
                                        <?php else: ?>
                                            <span></span>
                                        <?php endif; ?>

                                        <button type="button" class="button button-small button-link-delete" style="color: #ef4444; font-weight: 600;" onclick="this.closest('.proto-variation-card').remove();">
                                            Delete Option
                                        </button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Bottom Add Screen Button -->
            <div style="margin-top: 24px; text-align: center; background: #ffffff; padding: 22px; border-radius: 12px; border: 2px dashed #cbd5e1;">
                <button type="button" class="button button-primary button-large" onclick="window.protoAddScreen();" style="background: #b02b2b; border-color: #872e21; font-weight: bold; font-size: 14px; padding: 8px 28px; height: auto; box-shadow: 0 2px 6px rgba(176,43,43,0.3);">
                    + Add Another Screen Flow
                </button>
            </div>

        </div>

        <script>
        (function() {
            var pluginUrl = '<?php echo esc_js($plugin_url); ?>';

            window.protoUpdateCardThumb = function(input) {
                var card = input.closest('.proto-variation-card');
                if (!card) return;
                var url = input.value.trim();
                var thumbBox = card.querySelector('.proto-thumb-preview-box');
                var imgThumb = card.querySelector('.proto-img-thumb');
                var htmlThumb = card.querySelector('.proto-html-thumb');
                if (!url) {
                    if (thumbBox) thumbBox.style.display = 'none';
                    return;
                }
                var isImage = /\.(png|jpe?g|webp|svg|gif)($|\?)/i.test(url);
                if (thumbBox) thumbBox.style.display = 'block';
                if (imgThumb) {
                    imgThumb.src = url;
                    imgThumb.style.display = isImage ? 'block' : 'none';
                }
                if (htmlThumb) {
                    htmlThumb.style.display = isImage ? 'none' : 'flex';
                }
            };

            // Media Uploader Integration
            window.protoOpenMediaUploader = function(btn) {
                var card = btn.closest('.proto-variation-card');
                var inputField = card.querySelector('input[name*="file_path"]');
                var mediaFrame = wp.media({
                    title: 'Select or Upload Prototype Image Mockup or HTML File',
                    button: { text: 'Use as Prototype Source' },
                    multiple: false
                });

                mediaFrame.on('select', function() {
                    var attachment = mediaFrame.state().get('selection').first().toJSON();
                    if (inputField && attachment && attachment.url) {
                        inputField.value = attachment.url;
                        window.protoUpdateCardThumb(inputField);
                        
                        // Auto-fill title if empty
                        var nameInput = card.querySelector('input[name*="[name]"]');
                        if (nameInput && (!nameInput.value || nameInput.value.startsWith('Option '))) {
                            if (attachment.title) {
                                nameInput.value = attachment.title;
                            }
                        }
                    }
                });

                mediaFrame.open();
            };

            window.protoReindex = function() {
                var screens = document.querySelectorAll('.proto-screen-block');
                screens.forEach(function(screen, sIdx) {
                    screen.setAttribute('data-screen-index', sIdx);
                    screen.querySelector('.screen-num-badge').textContent = (sIdx + 1);

                    var nameInput = screen.querySelector('input[name*="[name]"]');
                    if (nameInput) nameInput.name = 'proto_screens[' + sIdx + '][name]';

                    var slugInput = screen.querySelector('input[name*="[slug]"]');
                    if (slugInput) slugInput.name = 'proto_screens[' + sIdx + '][slug]';

                    var navSelect = screen.querySelector('select[name*="[nav_group]"]');
                    if (navSelect) navSelect.name = 'proto_screens[' + sIdx + '][nav_group]';

                    var parentInput = screen.querySelector('input[name*="[parent_name]"]');
                    if (parentInput) parentInput.name = 'proto_screens[' + sIdx + '][parent_name]';

                    var devUrlInput = screen.querySelector('input[name*="[dev_url]"]');
                    if (devUrlInput) devUrlInput.name = 'proto_screens[' + sIdx + '][dev_url]';

                    var statusSelect = screen.querySelector('select[name*="[status]"]');
                    if (statusSelect) statusSelect.name = 'proto_screens[' + sIdx + '][status]';

                    var vars = screen.querySelectorAll('.proto-variation-card');
                    vars.forEach(function(vCard, vIdx) {
                        var radio = vCard.querySelector('input[type="radio"]');
                        if (radio) {
                            radio.name = 'proto_screens[' + sIdx + '][chosen_variation]';
                            radio.value = vIdx;
                        }

                        var vName = vCard.querySelector('input[name*="[name]"]');
                        if (vName) vName.name = 'proto_screens[' + sIdx + '][layouts][' + vIdx + '][name]';

                        var vFile = vCard.querySelector('input[name*="[file_path]"]');
                        if (vFile) vFile.name = 'proto_screens[' + sIdx + '][layouts][' + vIdx + '][file_path]';

                        var vBadge = vCard.querySelector('input[name*="[badge]"]');
                        if (vBadge) vBadge.name = 'proto_screens[' + sIdx + '][layouts][' + vIdx + '][badge]';

                        var vVer = vCard.querySelector('input[name*="[version]"]');
                        if (vVer) vVer.name = 'proto_screens[' + sIdx + '][layouts][' + vIdx + '][version]';
                    });
                });
            };

            window.protoHighlightChoice = function(radio) {
                var screenBlock = radio.closest('.proto-screen-block');
                var cards = screenBlock.querySelectorAll('.proto-variation-card');
                cards.forEach(function(c) {
                    c.style.background = '#f8fafc';
                    c.style.borderColor = '#e2e8f0';
                });
                var chosenCard = radio.closest('.proto-variation-card');
                if (chosenCard) {
                    chosenCard.style.background = '#fffbeb';
                    chosenCard.style.borderColor = '#f59e0b';
                }
            };

            window.protoAddScreen = function() {
                var container = document.getElementById('proto-screens-list');
                var sIdx = container.querySelectorAll('.proto-screen-block').length;
                var sNum = sIdx + 1;

                var html = `
                    <div class="proto-screen-block" data-screen-index="${sIdx}" style="background: #ffffff; border: 2px solid #e2e8f0; border-radius: 14px; padding: 20px; box-shadow: 0 4px 14px rgba(15,23,42,0.04);">
                        <div style="display: flex; align-items: center; justify-content: space-between; border-bottom: 2px solid #f1f5f9; padding-bottom: 16px; margin-bottom: 18px; flex-wrap: wrap; gap: 12px;">
                            <div style="display: flex; align-items: center; gap: 14px; flex-wrap: wrap;">
                                <span style="background: #0f172a; color: #ffffff; font-size: 12px; font-weight: 800; padding: 7px 14px; border-radius: 8px; letter-spacing: 0.5px; display: inline-flex; align-items: center; gap: 4px;">
                                    📁 SCREEN #<span class="screen-num-badge">${sNum}</span>
                                </span>
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">Screen Flow Title</label>
                                    <input type="text" name="proto_screens[${sIdx}][name]" value="Screen ${sNum}" placeholder="e.g. 02. Pricing & Plans" style="font-weight: bold; font-size: 14px; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 6px 12px; width: 240px; color: #0f172a;" required>
                                </div>
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">URL Slug</label>
                                    <div style="display: flex; align-items: center; background: #f8fafc; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 0 8px;">
                                        <span style="color: #94a3b8; font-size: 13px; font-family: monospace; font-weight: bold;">/</span>
                                        <input type="text" name="proto_screens[${sIdx}][slug]" value="screen-${sNum}" placeholder="slug" style="font-size: 12px; border: none; background: transparent; padding: 6px 4px; width: 100px; color: #475569; font-family: monospace; outline: none;">
                                    </div>
                                </div>
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">Sitemap Nav Group</label>
                                    <select name="proto_screens[${sIdx}][nav_group]" style="font-size: 11px; font-weight: 700; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 4px 6px; color: #0f172a; height: 32px; background: #fff;">
                                        <option value="primary">🏛️ Primary Nav</option>
                                        <option value="subpage">↳ Sub-page</option>
                                        <option value="footer">📄 Footer & Legal</option>
                                    </select>
                                </div>
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">Parent Page</label>
                                    <input type="text" name="proto_screens[${sIdx}][parent_name]" value="" placeholder="e.g. Services" style="font-size: 11px; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 5px 8px; width: 110px; color: #334155;">
                                </div>
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">Dev / Staging URL</label>
                                    <input type="url" name="proto_screens[${sIdx}][dev_url]" value="" placeholder="https://staging.site.com/page" style="font-size: 11px; font-family: monospace; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 5px 8px; width: 170px; color: #334155;">
                                </div>
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #475569; margin-bottom: 3px; text-transform: uppercase;">Workflow Phase</label>
                                    <select name="proto_screens[${sIdx}][status]" style="font-size: 11px; font-weight: 700; border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 4px 6px; color: #0f172a; height: 32px; background: #fff;">
                                        <option value="building_prototype">🎨 Building Prototype</option>
                                        <option value="waiting_approval">⏳ Waiting for Approval</option>
                                        <option value="building_page">⚡ Building Page</option>
                                        <option value="waiting_review">🔍 Waiting for Review</option>
                                        <option value="done">✅ Done</option>
                                        <option value="later">⏸️ Later</option>
                                    </select>
                                </div>
                            </div>
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <button type="button" class="button button-secondary" onclick="window.protoAddVariation(this);" style="font-size: 12px; font-weight: 700; border-color: #cbd5e1; padding: 4px 12px; height: auto;">
                                    + Add Variation Option
                                </button>
                                <button type="button" class="button button-link-delete" style="color: #ef4444; font-size: 12px; font-weight: 700; padding: 4px 8px;" onclick="if(confirm('Delete this entire screen and its variations?')) { this.closest('.proto-screen-block').remove(); window.protoReindex(); }">
                                    Delete Screen
                                </button>
                            </div>
                        </div>
                        <div class="proto-variations-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 16px;">
                            <div class="proto-variation-card" style="background: #f8fafc; border: 2px solid #e2e8f0; border-radius: 12px; padding: 16px; display: flex; flex-direction: column; justify-content: space-between; box-shadow: 0 2px 6px rgba(0,0,0,0.03);">
                                <div>
                                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
                                        <span style="background: #fbeeed; color: #b02b2b; font-size: 11px; font-weight: 800; padding: 3px 10px; border-radius: 6px; border: 1px solid rgba(176,43,43,0.25);">Option 1</span>
                                        <span style="font-size: 10px; font-weight: 700; color: #64748b; background: #ffffff; padding: 2px 8px; border-radius: 4px; border: 1px solid #e2e8f0;">Option #1</span>
                                    </div>
                                    <div class="proto-thumb-preview-box" style="margin-bottom: 12px;">
                                        <div style="width: 100%; height: 110px; background: #e2e8f0; border-radius: 8px; overflow: hidden; display: flex; align-items: center; justify-content: center; border: 1px solid #cbd5e1; position: relative;">
                                            <img src="" class="proto-img-thumb" style="width: 100%; height: 100%; object-fit: cover; object-position: top; display: none;">
                                            <div class="proto-html-thumb" style="font-size: 11px; color: #475569; font-weight: bold; display: flex; align-items: center; gap: 6px;">
                                                <span style="font-size: 16px;">🌐</span> HTML Prototype
                                            </div>
                                        </div>
                                    </div>
                                    <div style="margin-bottom: 12px;">
                                        <label style="display: block; font-size: 11px; font-weight: bold; color: #334155; margin-bottom: 4px;">VARIATION TITLE</label>
                                        <input type="text" name="proto_screens[${sIdx}][layouts][0][name]" value="Screen ${sNum} Option 1" style="width: 100%; font-size: 13px; font-weight: bold; padding: 7px 10px; border: 1px solid #cbd5e1; border-radius: 6px; color: #0f172a;" required>
                                    </div>
                                    <div style="margin-bottom: 12px;">
                                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
                                            <label style="font-size: 11px; font-weight: bold; color: #334155;">SOURCE (IMAGE MOCKUP / HTML / URL)</label>
                                            <button type="button" class="button button-small" onclick="window.protoOpenMediaUploader(this);" style="font-size: 10px; font-weight: 600; color: #b02b2b;">📁 Choose / Upload Image</button>
                                        </div>
                                        <input type="text" name="proto_screens[${sIdx}][layouts][0][file_path]" value="${pluginUrl}layouts/saas-v1.html" onchange="window.protoUpdateCardThumb(this);" style="width: 100%; font-size: 11px; font-family: monospace; padding: 6px 8px; border: 1px solid #cbd5e1; border-radius: 6px; color: #334155; background: #fff;" required>
                                    </div>
                                    <div>
                                        <label style="display: block; font-size: 11px; font-weight: bold; color: #334155; margin-bottom: 4px;">DESIGN CONCEPT TAG / BADGE</label>
                                        <input type="text" name="proto_screens[${sIdx}][layouts][0][badge]" value="Initial Exploration" style="width: 100%; font-size: 12px; padding: 6px 10px; border: 1px solid #cbd5e1; border-radius: 6px; color: #334155; background: #fff;">
                                    </div>
                                    <input type="hidden" name="proto_screens[${sIdx}][layouts][0][version]" value="Option 1">
                                </div>
                                <div style="margin-top: 16px; padding-top: 12px; border-top: 1px solid #e2e8f0; display: flex; justify-content: flex-end;">
                                    <button type="button" class="button button-small button-link-delete" style="color: #ef4444; font-weight: 600;" onclick="this.closest('.proto-variation-card').remove();">Delete Option</button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;

                var temp = document.createElement('div');
                temp.innerHTML = html;
                container.appendChild(temp.firstElementChild);
            };

            window.protoAddVariation = function(btn) {
                var screenBlock = btn.closest('.proto-screen-block');
                var grid = screenBlock.querySelector('.proto-variations-grid');
                var sIdx = screenBlock.getAttribute('data-screen-index');
                var vIdx = grid.querySelectorAll('.proto-variation-card').length;
                var vNum = vIdx + 1;

                var vCard = document.createElement('div');
                vCard.className = 'proto-variation-card';
                vCard.style.cssText = 'background: #f8fafc; border: 2px solid #e2e8f0; border-radius: 12px; padding: 16px; display: flex; flex-direction: column; justify-content: space-between; box-shadow: 0 2px 6px rgba(0,0,0,0.03);';
                vCard.innerHTML = `
                    <div>
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
                            <span style="background: #fbeeed; color: #b02b2b; font-size: 11px; font-weight: 800; padding: 3px 10px; border-radius: 6px; border: 1px solid rgba(176,43,43,0.25);">Option ${vNum}</span>
                            <span style="font-size: 10px; font-weight: 700; color: #64748b; background: #ffffff; padding: 2px 8px; border-radius: 4px; border: 1px solid #e2e8f0;">Option #${vNum}</span>
                        </div>
                        <div class="proto-thumb-preview-box" style="margin-bottom: 12px;">
                            <div style="width: 100%; height: 110px; background: #e2e8f0; border-radius: 8px; overflow: hidden; display: flex; align-items: center; justify-content: center; border: 1px solid #cbd5e1; position: relative;">
                                <img src="" class="proto-img-thumb" style="width: 100%; height: 100%; object-fit: cover; object-position: top; display: none;">
                                <div class="proto-html-thumb" style="font-size: 11px; color: #475569; font-weight: bold; display: flex; align-items: center; gap: 6px;">
                                    <span style="font-size: 16px;">🌐</span> HTML Prototype
                                </div>
                            </div>
                        </div>
                        <div style="margin-bottom: 12px;">
                            <label style="display: block; font-size: 11px; font-weight: bold; color: #334155; margin-bottom: 4px;">VARIATION TITLE</label>
                            <input type="text" name="proto_screens[${sIdx}][layouts][${vIdx}][name]" value="Option ${vNum}" style="width: 100%; font-size: 13px; font-weight: bold; padding: 7px 10px; border: 1px solid #cbd5e1; border-radius: 6px; color: #0f172a;" required>
                        </div>
                        <div style="margin-bottom: 12px;">
                            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
                                <label style="font-size: 11px; font-weight: bold; color: #334155;">SOURCE (IMAGE MOCKUP / HTML / URL)</label>
                                <button type="button" class="button button-small" onclick="window.protoOpenMediaUploader(this);" style="font-size: 10px; font-weight: 600; color: #b02b2b;">📁 Choose / Upload Image</button>
                            </div>
                            <input type="text" name="proto_screens[${sIdx}][layouts][${vIdx}][file_path]" value="${pluginUrl}layouts/dark-v2.html" onchange="window.protoUpdateCardThumb(this);" style="width: 100%; font-size: 11px; font-family: monospace; padding: 6px 8px; border: 1px solid #cbd5e1; border-radius: 6px; color: #334155; background: #fff;" required>
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: bold; color: #334155; margin-bottom: 4px;">DESIGN CONCEPT TAG / BADGE</label>
                            <input type="text" name="proto_screens[${sIdx}][layouts][${vIdx}][badge]" value="Exploration Concept" style="width: 100%; font-size: 12px; padding: 6px 10px; border: 1px solid #cbd5e1; border-radius: 6px; color: #334155; background: #fff;">
                        </div>
                        <input type="hidden" name="proto_screens[${sIdx}][layouts][${vIdx}][version]" value="Option ${vNum}">
                    </div>
                    <div style="margin-top: 16px; padding-top: 12px; border-top: 1px solid #e2e8f0; display: flex; justify-content: flex-end;">
                        <button type="button" class="button button-small button-link-delete" style="color: #ef4444; font-weight: 600;" onclick="this.closest('.proto-variation-card').remove();">Delete Option</button>
                    </div>
                `;
                grid.appendChild(vCard);
            };
        })();
        </script>
        <?php
    }

    public function render_story_steps_meta_box($post) {
        $steps = get_post_meta($post->ID, '_proto_story_steps', true);
        $player_url = home_url('/?proto_preview=1&project_id=' . $post->ID . '&mode=story');

        if (!is_array($steps) || empty($steps)) {
            $steps = [
                [
                    'title' => 'Welcome & High-Impact Value Proposition',
                    'content' => 'We kept the headline bold and concise above the fold so clients immediately understand the core service offerings within 3 seconds.',
                    'target_selector' => 'h1, .hero-title, header',
                    'action_type' => 'pulse_beacon',
                    'tip' => 'Notice the high-contrast typography hierarchy.'
                ],
                [
                    'title' => 'Streamlined Primary Action',
                    'content' => 'Positioned this primary call-to-action with clear visual affordance to maximize direct user conversions without friction.',
                    'target_selector' => 'button, .cta-btn, .btn-primary',
                    'action_type' => 'virtual_hover',
                    'tip' => 'Try hovering over the button to see the micro-interaction.'
                ]
            ];
        }
        ?>
        <div id="proto-story-builder-wrapper" style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: -6px -12px -12px -12px; background: #f8fafc; padding: 20px; border-radius: 0 0 4px 4px;">
            
            <!-- Storytelling Guide Banner -->
            <div style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); color: #ffffff; border-radius: 12px; padding: 18px 22px; margin-bottom: 20px; box-shadow: 0 4px 14px rgba(15,23,42,0.15); display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px;">
                <div>
                    <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px;">
                        <span style="background: #b02b2b; color: #fff; font-size: 11px; font-weight: 800; padding: 2px 8px; border-radius: 4px; text-transform: uppercase;">Storytelling</span>
                        <h3 style="margin: 0; font-size: 15px; font-weight: bold; color: #ffffff;">Design Story & Client Walkthrough</h3>
                    </div>
                    <p style="margin: 0; font-size: 12px; color: #94a3b8; max-width: 760px; line-height: 1.4;">
                        Walk your client through the design step-by-step. Tell the story behind each section, decision, or feature. Clients can read your thoughts, view virtual hover/click interactions, and leave feedback.
                    </p>
                </div>

                <div style="display: flex; align-items: center; gap: 8px;">
                    <a href="<?php echo esc_url($player_url); ?>" target="_blank" class="button button-primary button-large" style="background: #b02b2b; border-color: #872e21; font-weight: bold; font-size: 12px; padding: 6px 14px; height: auto; box-shadow: 0 2px 8px rgba(176,43,43,0.4);">
                        🚀 Test Walkthrough in Player ↗
                    </a>
                </div>
            </div>

            <!-- Steps Sortable Container -->
            <div id="proto-story-steps-container" style="display: flex; flex-direction: column; gap: 14px; margin-bottom: 16px;">
                <?php foreach ($steps as $idx => $step) : 
                    $title = $step['title'] ?? '';
                    $content = $step['content'] ?? ($step['description'] ?? '');
                    $target = $step['target_selector'] ?? '';
                    $action = $step['action_type'] ?? 'none';
                    $tip = $step['tip'] ?? '';
                ?>
                    <div class="proto-story-step-card" data-index="<?php echo $idx; ?>" style="background: #ffffff; border: 1.5px solid #e2e8f0; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(15,23,42,0.04); transition: border-color 0.2s ease;">
                        
                        <!-- Step Accordion Header -->
                        <div class="proto-step-card-header" style="background: #f8fafc; border-bottom: 1px solid #e2e8f0; padding: 12px 16px; display: flex; align-items: center; justify-content: space-between; cursor: pointer; user-select: none;">
                            <div style="display: flex; align-items: center; gap: 10px; min-width: 0;">
                                <span class="dashicons dashicons-menu proto-step-drag-handle" style="color: #94a3b8; cursor: grab;" title="Drag to reorder"></span>
                                <span style="background: #fbeeed; color: #b02b2b; font-size: 11px; font-weight: 800; padding: 2px 8px; border-radius: 6px; border: 1px solid rgba(176,43,43,0.25); shrink-0;">
                                    Step #<span class="proto-step-num"><?php echo ($idx + 1); ?></span>
                                </span>
                                <span class="proto-step-title-label" style="font-size: 13px; font-weight: 700; color: #1e293b; truncate; max-width: 480px;">
                                    <?php echo esc_html(!empty($title) ? $title : '(Untitled Story Step)'); ?>
                                </span>
                                <span class="proto-step-target-badge" style="font-size: 10px; font-family: monospace; color: #64748b; background: #ffffff; border: 1px solid #cbd5e1; padding: 1px 6px; border-radius: 4px;">
                                    <?php echo !empty($target) ? esc_html($target) : 'Centered Story Modal'; ?>
                                </span>
                            </div>

                            <div style="display: flex; align-items: center; gap: 8px;">
                                <button type="button" class="button button-small proto-step-toggle-btn" onclick="window.protoToggleStepBody(this);" style="font-size: 11px; padding: 2px 8px;">
                                    Expand / Collapse
                                </button>
                                <button type="button" class="button button-small button-link-delete" onclick="window.protoDeleteStoryStep(this);" style="color: #ef4444; font-size: 11px; font-weight: bold;">
                                    Delete
                                </button>
                            </div>
                        </div>

                        <!-- Step Card Body -->
                        <div class="proto-step-card-body" style="padding: 16px; background: #ffffff;">
                            <div style="margin-bottom: 12px;">
                                <label style="display: block; font-size: 11px; font-weight: 800; color: #334155; margin-bottom: 4px; text-transform: uppercase;">
                                    Step Title / Headline <span style="color: #b02b2b;">*</span>
                                </label>
                                <input type="text" name="proto_story_steps[<?php echo $idx; ?>][title]" value="<?php echo esc_attr($title); ?>" oninput="window.protoUpdateStepTitle(this);" placeholder="e.g. Why we placed the primary action here..." style="width: 100%; font-size: 13px; font-weight: bold; padding: 8px 12px; border: 1.5px solid #cbd5e1; border-radius: 8px; color: #0f172a;" required>
                            </div>

                            <div style="margin-bottom: 12px;">
                                <label style="display: block; font-size: 11px; font-weight: 800; color: #334155; margin-bottom: 4px; text-transform: uppercase;">
                                    Story & Design Rationale (What you want to tell the client) <span style="color: #b02b2b;">*</span>
                                </label>
                                <textarea name="proto_story_steps[<?php echo $idx; ?>][content]" rows="3" placeholder="Tell the story behind this design decision in simple, clear words..." style="width: 100%; font-size: 12px; padding: 10px 12px; border: 1.5px solid #cbd5e1; border-radius: 8px; line-height: 1.5; color: #334155; resize: vertical;" required><?php echo esc_textarea($content); ?></textarea>
                            </div>

                            <div style="display: grid; grid-template-columns: 1.2fr 1fr; gap: 14px; margin-bottom: 6px;">
                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #334155; margin-bottom: 4px; text-transform: uppercase;">
                                        Target Element Selector (HTML) or Area
                                    </label>
                                    <input type="text" name="proto_story_steps[<?php echo $idx; ?>][target_selector]" value="<?php echo esc_attr($target); ?>" oninput="window.protoUpdateStepTarget(this);" placeholder="e.g. header, .nav-menu, #hero-cta (leave empty for modal)" style="width: 100%; font-size: 11px; font-family: monospace; padding: 7px 10px; border: 1.5px solid #cbd5e1; border-radius: 8px; color: #334155;">
                                    <p style="margin: 3px 0 0 0; font-size: 10px; color: #64748b;">Enter CSS selector for HTML elements, or leave empty for a centered story card.</p>
                                </div>

                                <div>
                                    <label style="display: block; font-size: 11px; font-weight: 800; color: #334155; margin-bottom: 4px; text-transform: uppercase;">
                                        Optional Tip / Quick Note
                                    </label>
                                    <input type="text" name="proto_story_steps[<?php echo $idx; ?>][tip]" value="<?php echo esc_attr($tip); ?>" placeholder="e.g. Tip: Try hovering over the icons" style="width: 100%; font-size: 11px; padding: 7px 10px; border: 1.5px solid #cbd5e1; border-radius: 8px; color: #334155;">
                                    <p style="margin: 3px 0 0 0; font-size: 10px; color: #64748b;">Subtle hint shown to the client on this step.</p>
                                </div>
                            </div>
                            <input type="hidden" name="proto_story_steps[<?php echo $idx; ?>][action_type]" value="none">
                        </div>

                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Footer: Add Step Button -->
            <div style="display: flex; align-items: center; justify-content: space-between; padding-top: 6px;">
                <button type="button" class="button button-primary button-large" onclick="window.protoAddStoryStep();" style="background: #b02b2b; border-color: #872e21; font-weight: bold; font-size: 12px; padding: 6px 16px; height: auto;">
                    <span class="dashicons dashicons-plus-alt2" style="vertical-align: middle; margin-top: -2px;"></span>
                    Add Story Step
                </button>

                <p style="margin: 0; font-size: 11px; color: #64748b;">
                    Drag steps using the <span class="dashicons dashicons-menu" style="font-size: 14px; vertical-align: middle;"></span> handle to reorder the walkthrough narrative.
                </p>
            </div>

        </div>

        <script>
        (function() {
            // Drag and drop sortable
            if (window.jQuery && jQuery.fn.sortable) {
                jQuery('#proto-story-steps-container').sortable({
                    handle: '.proto-step-drag-handle',
                    placeholder: 'proto-step-placeholder',
                    opacity: 0.85,
                    update: function() {
                        window.protoReindexStorySteps();
                    }
                });
            }

            window.protoReindexStorySteps = function() {
                const container = document.getElementById('proto-story-steps-container');
                if (!container) return;
                const cards = container.querySelectorAll('.proto-story-step-card');
                cards.forEach((card, idx) => {
                    card.setAttribute('data-index', idx);
                    const numBadge = card.querySelector('.proto-step-num');
                    if (numBadge) numBadge.textContent = (idx + 1);

                    card.querySelectorAll('[name]').forEach(input => {
                        const name = input.getAttribute('name');
                        if (name) {
                            input.setAttribute('name', name.replace(/proto_story_steps\[\d+\]/, 'proto_story_steps[' + idx + ']'));
                        }
                    });
                });
            };

            window.protoUpdateStepTitle = function(input) {
                const card = input.closest('.proto-story-step-card');
                if (!card) return;
                const label = card.querySelector('.proto-step-title-label');
                if (label) {
                    label.textContent = input.value.trim() || '(Untitled Story Step)';
                }
            };

            window.protoUpdateStepTarget = function(input) {
                const card = input.closest('.proto-story-step-card');
                if (!card) return;
                const badge = card.querySelector('.proto-step-target-badge');
                if (badge) {
                    badge.textContent = input.value.trim() || 'Centered Story Modal';
                }
            };

            window.protoToggleStepBody = function(btn) {
                const card = btn.closest('.proto-story-step-card');
                if (!card) return;
                const body = card.querySelector('.proto-step-card-body');
                if (body) {
                    body.style.display = (body.style.display === 'none') ? 'block' : 'none';
                }
            };

            window.protoDeleteStoryStep = function(btn) {
                const card = btn.closest('.proto-story-step-card');
                if (!card) return;
                const title = card.querySelector('.proto-step-title-label')?.textContent || 'this step';
                if (confirm('Delete step "' + title.trim() + '"?')) {
                    card.remove();
                    window.protoReindexStorySteps();
                }
            };

            window.protoAddStoryStep = function() {
                const container = document.getElementById('proto-story-steps-container');
                if (!container) return;
                const idx = container.querySelectorAll('.proto-story-step-card').length;

                const stepDiv = document.createElement('div');
                stepDiv.className = 'proto-story-step-card';
                stepDiv.setAttribute('data-index', idx);
                stepDiv.style.cssText = 'background: #ffffff; border: 1.5px solid #e2e8f0; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(15,23,42,0.04);';

                stepDiv.innerHTML = `
                    <div class="proto-step-card-header" style="background: #f8fafc; border-bottom: 1px solid #e2e8f0; padding: 12px 16px; display: flex; align-items: center; justify-content: space-between; cursor: pointer; user-select: none;">
                        <div style="display: flex; align-items: center; gap: 10px; min-width: 0;">
                            <span class="dashicons dashicons-menu proto-step-drag-handle" style="color: #94a3b8; cursor: grab;" title="Drag to reorder"></span>
                            <span style="background: #fbeeed; color: #b02b2b; font-size: 11px; font-weight: 800; padding: 2px 8px; border-radius: 6px; border: 1px solid rgba(176,43,43,0.25); shrink-0;">
                                Step #<span class="proto-step-num">${idx + 1}</span>
                            </span>
                            <span class="proto-step-title-label" style="font-size: 13px; font-weight: 700; color: #1e293b; truncate; max-width: 480px;">
                                (New Story Step)
                            </span>
                            <span class="proto-step-target-badge" style="font-size: 10px; font-family: monospace; color: #64748b; background: #ffffff; border: 1px solid #cbd5e1; padding: 1px 6px; border-radius: 4px;">
                                Centered Story Modal
                            </span>
                        </div>

                        <div style="display: flex; align-items: center; gap: 8px;">
                            <button type="button" class="button button-small proto-step-toggle-btn" onclick="window.protoToggleStepBody(this);" style="font-size: 11px; padding: 2px 8px;">
                                Expand / Collapse
                            </button>
                            <button type="button" class="button button-small button-link-delete" onclick="window.protoDeleteStoryStep(this);" style="color: #ef4444; font-size: 11px; font-weight: bold;">
                                Delete
                            </button>
                        </div>
                    </div>

                    <div class="proto-step-card-body" style="padding: 16px; background: #ffffff;">
                        <div style="margin-bottom: 12px;">
                            <label style="display: block; font-size: 11px; font-weight: 800; color: #334155; margin-bottom: 4px; text-transform: uppercase;">
                                Step Title / Headline <span style="color: #b02b2b;">*</span>
                            </label>
                            <input type="text" name="proto_story_steps[${idx}][title]" value="" oninput="window.protoUpdateStepTitle(this);" placeholder="e.g. Navigation Bar & Quick Access" style="width: 100%; font-size: 13px; font-weight: bold; padding: 8px 12px; border: 1.5px solid #cbd5e1; border-radius: 8px; color: #0f172a;" required>
                        </div>

                        <div style="margin-bottom: 12px;">
                            <label style="display: block; font-size: 11px; font-weight: 800; color: #334155; margin-bottom: 4px; text-transform: uppercase;">
                                Story & Design Rationale (What you want to tell the client) <span style="color: #b02b2b;">*</span>
                            </label>
                            <textarea name="proto_story_steps[${idx}][content]" rows="3" placeholder="Tell the story behind this design decision in simple, clear words..." style="width: 100%; font-size: 12px; padding: 10px 12px; border: 1.5px solid #cbd5e1; border-radius: 8px; line-height: 1.5; color: #334155; resize: vertical;" required></textarea>
                        </div>

                        <div style="display: grid; grid-template-columns: 1.2fr 1fr; gap: 14px; margin-bottom: 6px;">
                            <div>
                                <label style="display: block; font-size: 11px; font-weight: 800; color: #334155; margin-bottom: 4px; text-transform: uppercase;">
                                    Target Element Selector (HTML) or Area
                                </label>
                                <input type="text" name="proto_story_steps[${idx}][target_selector]" value="" oninput="window.protoUpdateStepTarget(this);" placeholder="e.g. header, .nav-menu, #hero-cta (leave empty for modal)" style="width: 100%; font-size: 11px; font-family: monospace; padding: 7px 10px; border: 1.5px solid #cbd5e1; border-radius: 8px; color: #334155;">
                                <p style="margin: 3px 0 0 0; font-size: 10px; color: #64748b;">Enter CSS selector for HTML elements, or leave empty for a centered story card.</p>
                            </div>

                            <div>
                                <label style="display: block; font-size: 11px; font-weight: 800; color: #334155; margin-bottom: 4px; text-transform: uppercase;">
                                    Optional Tip / Quick Note
                                </label>
                                <input type="text" name="proto_story_steps[${idx}][tip]" value="" placeholder="e.g. Tip: Try hovering over the icons" style="width: 100%; font-size: 11px; padding: 7px 10px; border: 1.5px solid #cbd5e1; border-radius: 8px; color: #334155;">
                                <p style="margin: 3px 0 0 0; font-size: 10px; color: #64748b;">Subtle hint shown to the client on this step.</p>
                            </div>
                        </div>
                        <input type="hidden" name="proto_story_steps[${idx}][action_type]" value="none">
                    </div>
                `;

                container.appendChild(stepDiv);
                window.protoReindexStorySteps();
                stepDiv.querySelector('input[name*="[title]"]')?.focus();
            };
        })();
        </script>
        <?php
    }

    public function save_meta_boxes($post_id) {
        if (!isset($_POST['proto_project_meta_nonce']) || !wp_verify_nonce($_POST['proto_project_meta_nonce'], 'proto_project_meta_save')) {
            return;
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        if (isset($_POST['proto_share_token'])) {
            update_post_meta($post_id, '_proto_share_token', sanitize_text_field($_POST['proto_share_token']));
        }

        // Save Client Organization / Company Name
        if (isset($_POST['proto_client_name'])) {
            update_post_meta($post_id, '_proto_client_name', sanitize_text_field($_POST['proto_client_name']));
        }

        // Save Assigned Stakeholders / Users
        if (isset($_POST['proto_assigned_users']) && is_array($_POST['proto_assigned_users'])) {
            $clean_user_ids = array_map('intval', $_POST['proto_assigned_users']);
            update_post_meta($post_id, '_proto_assigned_users', array_values(array_unique($clean_user_ids)));
        } else {
            update_post_meta($post_id, '_proto_assigned_users', []);
        }

        // Save User Project Roles
        if (isset($_POST['proto_user_project_roles']) && is_array($_POST['proto_user_project_roles'])) {
            $clean_roles = [];
            foreach ($_POST['proto_user_project_roles'] as $u_id => $r_val) {
                $clean_roles[(int)$u_id] = sanitize_text_field($r_val);
            }
            update_post_meta($post_id, '_proto_user_project_roles', $clean_roles);
        }

        // Save Client Stakeholders Repeater & sync Notification Emails
        if (isset($_POST['proto_client_stakeholders']) && is_array($_POST['proto_client_stakeholders'])) {
            $clean_stakeholders = [];
            $all_emails = [];
            foreach ($_POST['proto_client_stakeholders'] as $s_item) {
                if (!is_array($s_item)) continue;
                $em = sanitize_email($s_item['email'] ?? '');
                $nm = sanitize_text_field($s_item['name'] ?? '');
                $rl = sanitize_text_field($s_item['role'] ?? 'Client Reviewer');
                if (!empty($em) || !empty($nm)) {
                    $clean_stakeholders[] = [
                        'name'  => $nm ?: (!empty($em) ? explode('@', $em)[0] : 'Client Reviewer'),
                        'email' => $em,
                        'role'  => $rl
                    ];
                    if (!empty($em)) {
                        $all_emails[] = $em;
                    }
                }
            }
            update_post_meta($post_id, '_proto_client_stakeholders', $clean_stakeholders);
            update_post_meta($post_id, '_proto_notification_emails', implode(', ', array_unique($all_emails)));
        } else {
            update_post_meta($post_id, '_proto_client_stakeholders', []);
            update_post_meta($post_id, '_proto_notification_emails', '');
        }

        // Save Email Notification Preference
        $enable_notifications = isset($_POST['proto_enable_notifications']) ? '1' : '0';
        update_post_meta($post_id, '_proto_enable_notifications', $enable_notifications);

        // Save Screens & Variations
        if (isset($_POST['proto_screens']) && is_array($_POST['proto_screens'])) {
            $sanitized_screens = [];
            foreach ($_POST['proto_screens'] as $s_idx => $s_data) {
                $clean_layouts = [];

                if (isset($s_data['layouts']) && is_array($s_data['layouts'])) {
                    $l_count = 0;
                    foreach ($s_data['layouts'] as $l_idx => $l_data) {
                        $clean_layouts[] = [
                            'id' => ($l_count + 1),
                            'version' => sanitize_text_field($l_data['version'] ?? ('Option ' . ($l_count + 1))),
                            'name' => sanitize_text_field($l_data['name'] ?? 'Variation'),
                            'file_path' => esc_url_raw($l_data['file_path'] ?? ''),
                            'badge' => sanitize_text_field($l_data['badge'] ?? ''),
                            'color' => 'red',
                            'is_selected_choice' => ($l_count === 0) ? 1 : 0
                        ];
                        $l_count++;
                    }
                }

                $sanitized_screens[] = [
                    'id' => ($s_idx + 1),
                    'name' => sanitize_text_field($s_data['name'] ?? 'Screen'),
                    'slug' => sanitize_title($s_data['slug'] ?? 'screen'),
                    'nav_group' => sanitize_text_field($s_data['nav_group'] ?? 'primary'),
                    'parent_name' => sanitize_text_field($s_data['parent_name'] ?? ''),
                    'dev_url' => esc_url_raw($s_data['dev_url'] ?? ''),
                    'status' => sanitize_text_field($s_data['status'] ?? 'mockup'),
                    'layouts' => $clean_layouts
                ];
            }

            update_post_meta($post_id, '_proto_screens', $sanitized_screens);
        }

        // Save Story Steps (and sync to custom DB table wp_pp_story_steps)
        if (isset($_POST['proto_story_steps']) && is_array($_POST['proto_story_steps'])) {
            global $wpdb;
            $sanitized_steps = [];
            $table_story_steps = $wpdb->prefix . 'pp_story_steps';
            $has_table = ($wpdb->get_var("SHOW TABLES LIKE '$table_story_steps'") === $table_story_steps);

            // Optional cleanup existing for this project in DB table
            if ($has_table) {
                $wpdb->delete($table_story_steps, ['project_id' => $post_id]);
            }

            $order = 1;
            foreach ($_POST['proto_story_steps'] as $step_raw) {
                if (!is_array($step_raw)) continue;
                $title = sanitize_text_field($step_raw['title'] ?? '');
                $content = wp_kses_post($step_raw['content'] ?? '');
                if (empty($title) && empty($content)) continue;

                $target = sanitize_text_field($step_raw['target_selector'] ?? '');
                $action = sanitize_text_field($step_raw['action_type'] ?? 'none');
                $tip = sanitize_text_field($step_raw['tip'] ?? '');

                $clean_step = [
                    'id' => $order,
                    'step_order' => $order,
                    'title' => $title,
                    'content' => $content,
                    'description' => $content,
                    'target_selector' => $target,
                    'action_type' => $action,
                    'tip' => $tip
                ];

                $sanitized_steps[] = $clean_step;

                if ($has_table) {
                    $wpdb->insert($table_story_steps, [
                        'project_id' => $post_id,
                        'page_id' => 1,
                        'layout_id' => 1,
                        'step_order' => $order,
                        'title' => $title,
                        'description' => $content,
                        'category' => 'story',
                        'target_type' => !empty($target) ? 'selector' : 'modal',
                        'target_selector' => $target,
                        'rect_data' => null,
                        'action_type' => $action,
                        'action_target' => '',
                        'requires_approval' => 0,
                        'author_id' => get_current_user_id() ?: 1,
                        'created_at' => current_time('mysql')
                    ]);
                }

                $order++;
            }

            update_post_meta($post_id, '_proto_story_steps', $sanitized_steps);
        }
    }
}
