<?php
/**
 * Form Builder/Editor View
 *
 * @package Freelance_Studio
 */

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

$form_fields = $form ? $form->fields : array();
$form_settings = $form ? $form->settings : array();
?>
<div class="wrap fs-wrap fs-form-builder">
    <form method="post" id="fs-form-form">
        <?php wp_nonce_field('fs_save_form', 'fs_form_nonce'); ?>
        <input type="hidden" name="action" value="<?php echo $is_new ? 'create' : 'update'; ?>">
        <?php if (!$is_new): ?>
            <input type="hidden" name="form_id" value="<?php echo esc_attr($form->id); ?>">
        <?php endif; ?>

        <div class="fs-page-header">
            <div class="fs-page-header-left">
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-forms') ); ?>" class="fs-back-link">
                    <span class="dashicons dashicons-arrow-left-alt2"></span>
                    <?php esc_html_e('Forms', 'freelance-studio'); ?>
                </a>
                <h1><?php echo  esc_html( $is_new ? __('New Form', 'freelance-studio') : __('Edit Form', 'freelance-studio') ); ?></h1>
            </div>
            <div class="fs-page-header-actions">
                <?php if ($is_new): ?>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-forms&action=templates') ); ?>" class="button">
                        <span class="dashicons dashicons-layout"></span> <?php esc_html_e('Use Template', 'freelance-studio'); ?>
                    </a>
                <?php endif; ?>
                <?php if (!$is_new): ?>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-forms&action=save-as-template&id=' . $form->id) ); ?>" class="button">
                        <span class="dashicons dashicons-archive"></span> <?php esc_html_e('Save as Template', 'freelance-studio'); ?>
                    </a>
                    <?php if ($form->status === 'active'): ?>
                        <a href="<?php echo esc_url(FS_Form::get_public_url($form)); ?>" target="_blank" class="button">
                            <span class="dashicons dashicons-external"></span> <?php esc_html_e('View Form', 'freelance-studio'); ?>
                        </a>
                    <?php endif; ?>
                <?php endif; ?>
                <button type="submit" class="button button-primary"><?php esc_html_e('Save Form', 'freelance-studio'); ?></button>
            </div>
        </div>

        <?php if (!empty($message) && isset($messages[$message])): ?>
            <div class="notice notice-success is-dismissible"><p><?php echo esc_html($messages[$message]); ?></p></div>
        <?php endif; ?>

        <div class="fs-form-builder-layout">
            <div class="fs-form-builder-main">
                <div class="fs-card">
                    <div class="fs-card-header"><h2><?php esc_html_e('Form Details', 'freelance-studio'); ?></h2></div>
                    <div class="fs-card-body">
                        <div class="fs-form-row">
                            <label for="form-name"><?php esc_html_e('Form Name', 'freelance-studio'); ?> <span class="required">*</span></label>
                            <input type="text" id="form-name" name="name" value="<?php echo esc_attr($form ? $form->name : ''); ?>" required class="large-text">
                        </div>
                        <div class="fs-form-row">
                            <label for="form-description"><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                            <textarea id="form-description" name="description" rows="2" class="large-text"><?php echo esc_textarea($form ? $form->description : ''); ?></textarea>
                        </div>
                        <div class="fs-form-row-inline">
                            <div class="fs-form-col">
                                <label for="form-client"><?php esc_html_e('Client', 'freelance-studio'); ?></label>
                                <select id="form-client" name="client_id">
                                    <option value=""><?php esc_html_e('— No specific client —', 'freelance-studio'); ?></option>
                                    <?php foreach ($clients as $client): ?>
                                        <option value="<?php echo esc_attr($client->id); ?>" <?php selected($form ? $form->client_id : ($selected_client_id ?? 0), $client->id); ?>><?php echo esc_html($client->company_name ?: $client->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="fs-form-col">
                                <label for="form-project"><?php esc_html_e('Project', 'freelance-studio'); ?></label>
                                <select id="form-project" name="project_id">
                                    <option value=""><?php esc_html_e('— No specific project —', 'freelance-studio'); ?></option>
                                    <?php foreach ($projects as $project): ?>
                                        <option value="<?php echo esc_attr($project->id); ?>" data-client="<?php echo esc_attr($project->client_id); ?>" <?php selected($form ? $form->project_id : ($selected_project_id ?? 0), $project->id); ?>><?php echo esc_html($project->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="fs-card">
                    <div class="fs-card-header">
                        <h2><?php esc_html_e('Form Fields', 'freelance-studio'); ?></h2>
                        <?php if (!$is_new && isset($response_count) && $response_count > 0): ?>
                            <?php /* translators: 1. count/number */ ?>
                            <span class="fs-badge fs-badge-info"><?php echo wp_kses_post( sprintf( _n('%d response', '%d responses', $response_count, 'freelance-studio'), $response_count) ); ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="fs-card-body">
                        <div id="fs-form-fields" class="fs-form-fields-list">
                            <?php if (empty($form_fields)): ?>
                                <div class="fs-empty-fields-message">
                                    <span class="dashicons dashicons-plus-alt2"></span>
                                    <p><?php esc_html_e('Click a field type on the right to add it to your form.', 'freelance-studio'); ?></p>
                                </div>
                            <?php else: ?>
                                <?php foreach ($form_fields as $index => $field): ?>
                                    <div class="fs-form-field-item" data-field-id="<?php echo esc_attr($field['id']); ?>" data-field-type="<?php echo esc_attr($field['type']); ?>">
                                        <div class="fs-field-header">
                                            <span class="fs-field-drag-handle dashicons dashicons-menu"></span>
                                            <span class="fs-field-type-name"><?php echo esc_html(FS_Form::get_question_types_flat()[$field['type']]['label'] ?? $field['type']); ?></span>
                                            <div class="fs-field-actions">
                                                <button type="button" class="fs-field-toggle" title="<?php esc_attr_e('Expand/Collapse', 'freelance-studio'); ?>"><span class="dashicons dashicons-arrow-down-alt2"></span></button>
                                                <button type="button" class="fs-field-duplicate" title="<?php esc_attr_e('Duplicate', 'freelance-studio'); ?>"><span class="dashicons dashicons-admin-page"></span></button>
                                                <button type="button" class="fs-field-delete" title="<?php esc_attr_e('Delete', 'freelance-studio'); ?>"><span class="dashicons dashicons-trash"></span></button>
                                            </div>
                                        </div>
                                        <div class="fs-field-preview">
                                            <span class="fs-field-label-preview"><?php echo esc_html($field['label']); ?></span>
                                            <?php if (!empty($field['required'])): ?><span class="required">*</span><?php endif; ?>
                                        </div>
                                        <div class="fs-field-settings" style="display: none;">
                                            <input type="hidden" name="fields[<?php echo  esc_attr( $index ); ?>][id]" value="<?php echo esc_attr($field['id']); ?>">
                                            <input type="hidden" name="fields[<?php echo  esc_attr( $index ); ?>][type]" value="<?php echo esc_attr($field['type']); ?>">
                                            
                                            <?php if (!in_array($field['type'], array('heading', 'paragraph', 'divider'))): ?>
                                            <div class="fs-field-setting-row">
                                                <label><?php esc_html_e('Label', 'freelance-studio'); ?></label>
                                                <input type="text" name="fields[<?php echo  esc_attr( $index ); ?>][label]" value="<?php echo esc_attr($field['label']); ?>" class="fs-field-label-input large-text">
                                            </div>
                                            <div class="fs-field-setting-row">
                                                <label><?php esc_html_e('Placeholder', 'freelance-studio'); ?></label>
                                                <input type="text" name="fields[<?php echo  esc_attr( $index ); ?>][placeholder]" value="<?php echo esc_attr($field['placeholder'] ?? ''); ?>" class="regular-text">
                                            </div>
                                            <div class="fs-field-setting-row">
                                                <label><?php esc_html_e('Help Text', 'freelance-studio'); ?></label>
                                                <input type="text" name="fields[<?php echo  esc_attr( $index ); ?>][help_text]" value="<?php echo esc_attr($field['help_text'] ?? ''); ?>" class="large-text">
                                            </div>
                                            <div class="fs-field-setting-row">
                                                <label><input type="checkbox" name="fields[<?php echo  esc_attr( $index ); ?>][required]" value="1" <?php checked(!empty($field['required'])); ?> class="fs-field-required-input"> <?php esc_html_e('Required field', 'freelance-studio'); ?></label>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($field['type'] === 'heading'): ?>
                                            <div class="fs-field-setting-row">
                                                <label><?php esc_html_e('Heading Text', 'freelance-studio'); ?></label>
                                                <input type="text" name="fields[<?php echo  esc_attr( $index ); ?>][label]" value="<?php echo esc_attr($field['label']); ?>" class="fs-field-label-input large-text">
                                            </div>
                                            <?php elseif ($field['type'] === 'paragraph'): ?>
                                            <div class="fs-field-setting-row">
                                                <label><?php esc_html_e('Content', 'freelance-studio'); ?></label>
                                                <textarea name="fields[<?php echo  esc_attr( $index ); ?>][content]" rows="3" class="large-text"><?php echo esc_textarea($field['content'] ?? ''); ?></textarea>
                                                <input type="hidden" name="fields[<?php echo  esc_attr( $index ); ?>][label]" value="<?php esc_attr_e('Paragraph', 'freelance-studio'); ?>">
                                            </div>
                                            <?php elseif ($field['type'] === 'divider'): ?>
                                            <input type="hidden" name="fields[<?php echo  esc_attr( $index ); ?>][label]" value="<?php esc_attr_e('Divider', 'freelance-studio'); ?>">
                                            <?php endif; ?>
                                            
                                            <?php if (in_array($field['type'], array('single_choice', 'multiple_choice', 'dropdown'))): ?>
                                            <div class="fs-field-setting-row fs-field-options-container">
                                                <label><?php esc_html_e('Options', 'freelance-studio'); ?></label>
                                                <div class="fs-field-options-list">
                                                    <?php $options = $field['options'] ?? array(''); foreach ($options as $opt): ?>
                                                    <div class="fs-field-option-row">
                                                        <input type="text" name="fields[<?php echo  esc_attr( $index ); ?>][options][]" value="<?php echo esc_attr($opt); ?>" class="regular-text">
                                                        <button type="button" class="fs-remove-option button-link"><span class="dashicons dashicons-no-alt"></span></button>
                                                    </div>
                                                    <?php endforeach; ?>
                                                </div>
                                                <button type="button" class="button fs-add-option"><?php esc_html_e('Add Option', 'freelance-studio'); ?></button>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($field['type'] === 'scale'): ?>
                                            <div class="fs-field-setting-row">
                                                <div class="fs-inline-fields">
                                                    <div><label><?php esc_html_e('Min', 'freelance-studio'); ?></label><input type="number" name="fields[<?php echo  esc_attr( $index ); ?>][min]" value="<?php echo esc_attr($field['min'] ?? 1); ?>" class="small-text"></div>
                                                    <div><label><?php esc_html_e('Max', 'freelance-studio'); ?></label><input type="number" name="fields[<?php echo  esc_attr( $index ); ?>][max]" value="<?php echo esc_attr($field['max'] ?? 10); ?>" class="small-text"></div>
                                                </div>
                                                <div class="fs-inline-fields">
                                                    <div><label><?php esc_html_e('Min Label', 'freelance-studio'); ?></label><input type="text" name="fields[<?php echo  esc_attr( $index ); ?>][min_label]" value="<?php echo esc_attr($field['min_label'] ?? ''); ?>" class="regular-text"></div>
                                                    <div><label><?php esc_html_e('Max Label', 'freelance-studio'); ?></label><input type="text" name="fields[<?php echo  esc_attr( $index ); ?>][max_label]" value="<?php echo esc_attr($field['max_label'] ?? ''); ?>" class="regular-text"></div>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($field['type'] === 'file_upload'): ?>
                                            <div class="fs-field-setting-row">
                                                <label><?php esc_html_e('Allowed File Types', 'freelance-studio'); ?></label>
                                                <input type="text" name="fields[<?php echo  esc_attr( $index ); ?>][allowed_types]" value="<?php echo esc_attr($field['allowed_types'] ?? 'pdf,doc,docx,jpg,png'); ?>" class="regular-text">
                                                <p class="description"><?php esc_html_e('Comma-separated list of extensions.', 'freelance-studio'); ?></p>
                                            </div>
                                            <div class="fs-field-setting-row">
                                                <label><?php esc_html_e('Max File Size (MB)', 'freelance-studio'); ?></label>
                                                <input type="number" name="fields[<?php echo  esc_attr( $index ); ?>][max_size]" value="<?php echo esc_attr($field['max_size'] ?? 10); ?>" class="small-text" min="1" max="100">
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($field['type'] === 'file_download'): ?>
                                            <div class="fs-field-setting-row">
                                                <label><?php esc_html_e('File to Download', 'freelance-studio'); ?></label>
                                                <div class="fs-file-upload-field">
                                                    <input type="hidden" name="fields[<?php echo  esc_attr( $index ); ?>][file_id]" value="<?php echo esc_attr($field['file_id'] ?? 0); ?>" class="fs-file-id">
                                                    <input type="text" name="fields[<?php echo  esc_attr( $index ); ?>][file_url]" value="<?php echo esc_attr($field['file_url'] ?? ''); ?>" class="regular-text fs-file-url" readonly>
                                                    <button type="button" class="button fs-select-file"><?php esc_html_e('Select File', 'freelance-studio'); ?></button>
                                                </div>
                                                <input type="text" name="fields[<?php echo  esc_attr( $index ); ?>][file_name]" value="<?php echo esc_attr($field['file_name'] ?? ''); ?>" class="regular-text" placeholder="<?php esc_attr_e('Display name', 'freelance-studio'); ?>">
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php 
                                            // Conditional logic section
                                            $conditional = $field['conditional_logic'] ?? array();
                                            $has_conditional = !empty($conditional['enabled']);
                                            ?>
                                            <div class="fs-field-conditional-logic">
                                                <div class="fs-conditional-toggle">
                                                    <label>
                                                        <input type="checkbox" name="fields[<?php echo  esc_attr( $index ); ?>][conditional_logic][enabled]" value="1" class="fs-conditional-enabled" <?php checked($has_conditional); ?>>
                                                        <?php esc_html_e('Add Conditional Logic', 'freelance-studio'); ?>
                                                    </label>
                                                </div>
                                                <div class="fs-conditional-settings" style="<?php echo $has_conditional ? '' : 'display:none;'; ?>">
                                                    <div class="fs-conditional-action-row">
                                                        <select name="fields[<?php echo  esc_attr( $index ); ?>][conditional_logic][action]" class="fs-conditional-action">
                                                            <option value="show" <?php selected($conditional['action'] ?? 'show', 'show'); ?>><?php esc_html_e('Show', 'freelance-studio'); ?></option>
                                                            <option value="hide" <?php selected($conditional['action'] ?? '', 'hide'); ?>><?php esc_html_e('Hide', 'freelance-studio'); ?></option>
                                                        </select>
                                                        <span><?php esc_html_e('this field if', 'freelance-studio'); ?></span>
                                                        <select name="fields[<?php echo  esc_attr( $index ); ?>][conditional_logic][logic]" class="fs-conditional-logic-type">
                                                            <option value="all" <?php selected($conditional['logic'] ?? 'all', 'all'); ?>><?php esc_html_e('all', 'freelance-studio'); ?></option>
                                                            <option value="any" <?php selected($conditional['logic'] ?? '', 'any'); ?>><?php esc_html_e('any', 'freelance-studio'); ?></option>
                                                        </select>
                                                        <span><?php esc_html_e('of these rules match:', 'freelance-studio'); ?></span>
                                                    </div>
                                                    <div class="fs-conditional-rules">
                                                        <?php 
                                                        $rules = $conditional['rules'] ?? array(array('field_id' => '', 'operator' => 'equals', 'value' => ''));
                                                        foreach ($rules as $rule_index => $rule): 
                                                        ?>
                                                        <div class="fs-conditional-rule">
                                                            <select name="fields[<?php echo  esc_attr( $index ); ?>][conditional_logic][rules][<?php echo  esc_attr( $rule_index ); ?>][field_id]" class="fs-conditional-field-select">
                                                                <option value=""><?php esc_html_e('Select a field...', 'freelance-studio'); ?></option>
                                                            </select>
                                                            <select name="fields[<?php echo  esc_attr( $index ); ?>][conditional_logic][rules][<?php echo  esc_attr( $rule_index ); ?>][operator]" class="fs-conditional-operator">
                                                                <option value="equals" <?php selected($rule['operator'] ?? 'equals', 'equals'); ?>><?php esc_html_e('equals', 'freelance-studio'); ?></option>
                                                                <option value="not_equals" <?php selected($rule['operator'] ?? '', 'not_equals'); ?>><?php esc_html_e('does not equal', 'freelance-studio'); ?></option>
                                                                <option value="contains" <?php selected($rule['operator'] ?? '', 'contains'); ?>><?php esc_html_e('contains', 'freelance-studio'); ?></option>
                                                                <option value="not_contains" <?php selected($rule['operator'] ?? '', 'not_contains'); ?>><?php esc_html_e('does not contain', 'freelance-studio'); ?></option>
                                                                <option value="is_empty" <?php selected($rule['operator'] ?? '', 'is_empty'); ?>><?php esc_html_e('is empty', 'freelance-studio'); ?></option>
                                                                <option value="is_not_empty" <?php selected($rule['operator'] ?? '', 'is_not_empty'); ?>><?php esc_html_e('is not empty', 'freelance-studio'); ?></option>
                                                            </select>
                                                            <input type="text" name="fields[<?php echo  esc_attr( $index ); ?>][conditional_logic][rules][<?php echo  esc_attr( $rule_index ); ?>][value]" value="<?php echo esc_attr($rule['value'] ?? ''); ?>" class="fs-conditional-value" placeholder="<?php esc_attr_e('Value', 'freelance-studio'); ?>">
                                                            <button type="button" class="fs-remove-rule button-link"><span class="dashicons dashicons-no-alt"></span></button>
                                                        </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                    <button type="button" class="button fs-add-rule"><?php esc_html_e('+ Add Rule', 'freelance-studio'); ?></button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <div class="fs-form-builder-sidebar">
                <div class="fs-card fs-field-types-card">
                    <div class="fs-card-header"><h2><?php esc_html_e('Add Fields', 'freelance-studio'); ?></h2></div>
                    <div class="fs-card-body">
                        <?php foreach ($question_types as $group_key => $group): ?>
                            <div class="fs-field-type-group">
                                <h4><?php echo esc_html($group['label']); ?></h4>
                                <div class="fs-field-type-buttons">
                                    <?php foreach ($group['types'] as $type_key => $type_info): ?>
                                        <button type="button" class="fs-add-field-btn" data-type="<?php echo esc_attr($type_key); ?>" title="<?php echo esc_attr($type_info['description']); ?>">
                                            <span class="dashicons <?php echo esc_attr($type_info['icon']); ?>"></span>
                                            <span class="fs-field-type-label"><?php echo esc_html($type_info['label']); ?></span>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="fs-card">
                    <div class="fs-card-header"><h2><?php esc_html_e('Form Settings', 'freelance-studio'); ?></h2></div>
                    <div class="fs-card-body">
                        <div class="fs-form-row">
                            <label for="submit-button-text"><?php esc_html_e('Submit Button Text', 'freelance-studio'); ?></label>
                            <input type="text" id="submit-button-text" name="settings[submit_button_text]" value="<?php echo esc_attr($form_settings['submit_button_text'] ?? __('Submit', 'freelance-studio')); ?>" class="regular-text">
                        </div>
                        <div class="fs-form-row">
                            <label for="success-message"><?php esc_html_e('Success Message', 'freelance-studio'); ?></label>
                            <textarea id="success-message" name="settings[success_message]" rows="2" class="large-text"><?php echo esc_textarea($form_settings['success_message'] ?? __('Thank you for your submission!', 'freelance-studio')); ?></textarea>
                        </div>
                        <div class="fs-form-row">
                            <label><input type="checkbox" name="settings[show_in_portal]" value="1" <?php checked(!empty($form_settings['show_in_portal'])); ?>> <?php esc_html_e('Show in Client Portal', 'freelance-studio'); ?></label>
                        </div>
                    </div>
                </div>
                
                <?php if (!$is_new): ?>
                <div class="fs-card">
                    <div class="fs-card-header"><h2><?php esc_html_e('Share Form', 'freelance-studio'); ?></h2></div>
                    <div class="fs-card-body">
                        <div class="fs-form-row">
                            <label><?php esc_html_e('Public Link', 'freelance-studio'); ?></label>
                            <div class="fs-input-group">
                                <input type="text" value="<?php echo esc_url(FS_Form::get_public_url($form)); ?>" readonly class="regular-text" id="fs-form-public-url">
                                <button type="button" class="button" id="fs-copy-link-btn"><?php esc_html_e('Copy', 'freelance-studio'); ?></button>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </form>
</div>

<script>
jQuery(document).ready(function($) {
    var fieldIndex = <?php echo count($form_fields); ?>;
    var fieldTypeInfo = <?php echo wp_json_encode(FS_Form::get_question_types_flat()); ?>;
    var contentTypes = ['heading', 'paragraph', 'divider'];
    var optionTypes = ['single_choice', 'multiple_choice', 'dropdown'];
    
    // Sortable fields
    $('#fs-form-fields').sortable({
        handle: '.fs-field-drag-handle',
        placeholder: 'fs-field-placeholder',
        update: updateFieldIndexes
    });
    
    function updateFieldIndexes() {
        $('#fs-form-fields .fs-form-field-item').each(function(i) {
            $(this).find('input, select, textarea').each(function() {
                var name = $(this).attr('name');
                if (name) {
                    $(this).attr('name', name.replace(/fields\[\d+\]/, 'fields[' + i + ']'));
                }
            });
        });
    }
    
    // Update conditional field selects with available fields
    var isUpdatingSelects = false;
    function updateConditionalFieldSelects() {
        if (isUpdatingSelects) return;
        isUpdatingSelects = true;
        
        var fields = [];
        $('#fs-form-fields .fs-form-field-item').each(function() {
            var type = $(this).data('field-type');
            // Only allow certain field types as conditions
            if (['short_text', 'long_text', 'email', 'phone', 'number', 'url', 'single_choice', 'multiple_choice', 'dropdown', 'yes_no', 'scale'].indexOf(type) !== -1) {
                var id = $(this).data('field-id');
                var label = $(this).find('.fs-field-label-input').val() || $(this).find('.fs-field-label-preview').text();
                if (id && label) {
                    fields.push({id: id, label: label, type: type});
                }
            }
        });
        
        $('.fs-conditional-field-select').each(function() {
            var currentVal = $(this).val();
            var $field = $(this).closest('.fs-form-field-item');
            var currentFieldId = $field.data('field-id');
            var html = '<option value=""><?php esc_html_e('Select a field...', 'freelance-studio'); ?></option>';
            
            $.each(fields, function(i, f) {
                if (f.id !== currentFieldId) {
                    var selected = (f.id === currentVal) ? ' selected' : '';
                    html += '<option value="' + f.id + '"' + selected + '>' + f.label + '</option>';
                }
            });
            
            $(this).html(html);
        });
        
        isUpdatingSelects = false;
    }
    
    // Add field
    $('.fs-add-field-btn').on('click', function() {
        var type = $(this).data('type');
        var info = fieldTypeInfo[type] || {label: type, icon: 'dashicons-edit'};
        var fieldId = 'field_' + Date.now();
        var isContent = contentTypes.indexOf(type) !== -1;
        var hasOptions = optionTypes.indexOf(type) !== -1;
        
        var html = '<div class="fs-form-field-item" data-field-id="' + fieldId + '" data-field-type="' + type + '">';
        html += '<div class="fs-field-header">';
        html += '<span class="fs-field-drag-handle dashicons dashicons-menu"></span>';
        html += '<span class="fs-field-type-name">' + info.label + '</span>';
        html += '<div class="fs-field-actions">';
        html += '<button type="button" class="fs-field-toggle"><span class="dashicons dashicons-arrow-up-alt2"></span></button>';
        html += '<button type="button" class="fs-field-duplicate"><span class="dashicons dashicons-admin-page"></span></button>';
        html += '<button type="button" class="fs-field-delete"><span class="dashicons dashicons-trash"></span></button>';
        html += '</div></div>';
        html += '<div class="fs-field-preview"><span class="fs-field-label-preview">' + info.label + '</span></div>';
        html += '<div class="fs-field-settings">';
        html += '<input type="hidden" name="fields[' + fieldIndex + '][id]" value="' + fieldId + '">';
        html += '<input type="hidden" name="fields[' + fieldIndex + '][type]" value="' + type + '">';
        
        if (!isContent) {
            html += '<div class="fs-field-setting-row"><label><?php esc_html_e('Label', 'freelance-studio'); ?></label>';
            html += '<input type="text" name="fields[' + fieldIndex + '][label]" value="' + info.label + '" class="fs-field-label-input large-text"></div>';
            html += '<div class="fs-field-setting-row"><label><?php esc_html_e('Placeholder', 'freelance-studio'); ?></label>';
            html += '<input type="text" name="fields[' + fieldIndex + '][placeholder]" class="regular-text"></div>';
            html += '<div class="fs-field-setting-row"><label><?php esc_html_e('Help Text', 'freelance-studio'); ?></label>';
            html += '<input type="text" name="fields[' + fieldIndex + '][help_text]" class="large-text"></div>';
            html += '<div class="fs-field-setting-row"><label><input type="checkbox" name="fields[' + fieldIndex + '][required]" value="1" class="fs-field-required-input"> <?php esc_html_e('Required field', 'freelance-studio'); ?></label></div>';
        }
        
        if (type === 'heading') {
            html += '<div class="fs-field-setting-row"><label><?php esc_html_e('Heading Text', 'freelance-studio'); ?></label>';
            html += '<input type="text" name="fields[' + fieldIndex + '][label]" value="<?php esc_attr_e('Section Title', 'freelance-studio'); ?>" class="fs-field-label-input large-text"></div>';
        } else if (type === 'paragraph') {
            html += '<div class="fs-field-setting-row"><label><?php esc_html_e('Content', 'freelance-studio'); ?></label>';
            html += '<textarea name="fields[' + fieldIndex + '][content]" rows="3" class="large-text"></textarea>';
            html += '<input type="hidden" name="fields[' + fieldIndex + '][label]" value="Paragraph"></div>';
        } else if (type === 'divider') {
            html += '<input type="hidden" name="fields[' + fieldIndex + '][label]" value="Divider">';
        }
        
        if (hasOptions) {
            html += '<div class="fs-field-setting-row fs-field-options-container"><label><?php esc_html_e('Options', 'freelance-studio'); ?></label>';
            html += '<div class="fs-field-options-list">';
            html += '<div class="fs-field-option-row"><input type="text" name="fields[' + fieldIndex + '][options][]" class="regular-text" placeholder="<?php esc_attr_e('Option 1', 'freelance-studio'); ?>"><button type="button" class="fs-remove-option button-link"><span class="dashicons dashicons-no-alt"></span></button></div>';
            html += '</div><button type="button" class="button fs-add-option"><?php esc_html_e('Add Option', 'freelance-studio'); ?></button></div>';
        }
        
        if (type === 'scale') {
            html += '<div class="fs-field-setting-row"><div class="fs-inline-fields">';
            html += '<div><label><?php esc_html_e('Min', 'freelance-studio'); ?></label><input type="number" name="fields[' + fieldIndex + '][min]" value="1" class="small-text"></div>';
            html += '<div><label><?php esc_html_e('Max', 'freelance-studio'); ?></label><input type="number" name="fields[' + fieldIndex + '][max]" value="10" class="small-text"></div>';
            html += '</div><div class="fs-inline-fields">';
            html += '<div><label><?php esc_html_e('Min Label', 'freelance-studio'); ?></label><input type="text" name="fields[' + fieldIndex + '][min_label]" class="regular-text"></div>';
            html += '<div><label><?php esc_html_e('Max Label', 'freelance-studio'); ?></label><input type="text" name="fields[' + fieldIndex + '][max_label]" class="regular-text"></div>';
            html += '</div></div>';
        }
        
        if (type === 'file_upload') {
            html += '<div class="fs-field-setting-row"><label><?php esc_html_e('Allowed File Types', 'freelance-studio'); ?></label>';
            html += '<input type="text" name="fields[' + fieldIndex + '][allowed_types]" value="pdf,doc,docx,jpg,png" class="regular-text"></div>';
            html += '<div class="fs-field-setting-row"><label><?php esc_html_e('Max File Size (MB)', 'freelance-studio'); ?></label>';
            html += '<input type="number" name="fields[' + fieldIndex + '][max_size]" value="10" class="small-text" min="1" max="100"></div>';
        }
        
        if (type === 'file_download') {
            html += '<div class="fs-field-setting-row"><label><?php esc_html_e('File to Download', 'freelance-studio'); ?></label>';
            html += '<div class="fs-file-upload-field"><input type="hidden" name="fields[' + fieldIndex + '][file_id]" value="0" class="fs-file-id">';
            html += '<input type="text" name="fields[' + fieldIndex + '][file_url]" class="regular-text fs-file-url" readonly>';
            html += '<button type="button" class="button fs-select-file"><?php esc_html_e('Select File', 'freelance-studio'); ?></button></div>';
            html += '<input type="text" name="fields[' + fieldIndex + '][file_name]" class="regular-text" placeholder="<?php esc_attr_e('Display name', 'freelance-studio'); ?>"></div>';
        }
        
        // Conditional logic section
        html += '<div class="fs-field-conditional-logic">';
        html += '<div class="fs-conditional-toggle"><label>';
        html += '<input type="checkbox" name="fields[' + fieldIndex + '][conditional_logic][enabled]" value="1" class="fs-conditional-enabled"> <?php esc_html_e('Add Conditional Logic', 'freelance-studio'); ?>';
        html += '</label></div>';
        html += '<div class="fs-conditional-settings" style="display:none;">';
        html += '<div class="fs-conditional-action-row">';
        html += '<select name="fields[' + fieldIndex + '][conditional_logic][action]" class="fs-conditional-action">';
        html += '<option value="show"><?php esc_html_e('Show', 'freelance-studio'); ?></option><option value="hide"><?php esc_html_e('Hide', 'freelance-studio'); ?></option></select>';
        html += ' <span><?php esc_html_e('this field if', 'freelance-studio'); ?></span> ';
        html += '<select name="fields[' + fieldIndex + '][conditional_logic][logic]" class="fs-conditional-logic-type">';
        html += '<option value="all"><?php esc_html_e('all', 'freelance-studio'); ?></option><option value="any"><?php esc_html_e('any', 'freelance-studio'); ?></option></select>';
        html += ' <span><?php esc_html_e('of these rules match:', 'freelance-studio'); ?></span></div>';
        html += '<div class="fs-conditional-rules">';
        html += '<div class="fs-conditional-rule">';
        html += '<select name="fields[' + fieldIndex + '][conditional_logic][rules][0][field_id]" class="fs-conditional-field-select"><option value=""><?php esc_html_e('Select a field...', 'freelance-studio'); ?></option></select>';
        html += '<select name="fields[' + fieldIndex + '][conditional_logic][rules][0][operator]" class="fs-conditional-operator">';
        html += '<option value="equals"><?php esc_html_e('equals', 'freelance-studio'); ?></option><option value="not_equals"><?php esc_html_e('does not equal', 'freelance-studio'); ?></option>';
        html += '<option value="contains"><?php esc_html_e('contains', 'freelance-studio'); ?></option><option value="not_contains"><?php esc_html_e('does not contain', 'freelance-studio'); ?></option>';
        html += '<option value="is_empty"><?php esc_html_e('is empty', 'freelance-studio'); ?></option><option value="is_not_empty"><?php esc_html_e('is not empty', 'freelance-studio'); ?></option></select>';
        html += '<input type="text" name="fields[' + fieldIndex + '][conditional_logic][rules][0][value]" class="fs-conditional-value" placeholder="<?php esc_attr_e('Value', 'freelance-studio'); ?>">';
        html += '<button type="button" class="fs-remove-rule button-link"><span class="dashicons dashicons-no-alt"></span></button>';
        html += '</div></div>';
        html += '<button type="button" class="button fs-add-rule"><?php esc_html_e('+ Add Rule', 'freelance-studio'); ?></button>';
        html += '</div></div>';
        
        html += '</div></div>';
        
        $('.fs-empty-fields-message').remove();
        $('#fs-form-fields').append(html);
        fieldIndex++;
        
        var $newField = $('#fs-form-fields .fs-form-field-item').last();
        $('html, body').animate({scrollTop: $newField.offset().top - 100}, 300);
        
        // Update conditional field selects after adding new field
        setTimeout(updateConditionalFieldSelects, 50);
    });
    
    // Toggle field settings
    $(document).on('click', '.fs-field-toggle', function() {
        var $settings = $(this).closest('.fs-form-field-item').find('.fs-field-settings');
        var $icon = $(this).find('.dashicons');
        $settings.slideToggle(200);
        $icon.toggleClass('dashicons-arrow-down-alt2 dashicons-arrow-up-alt2');
    });
    
    // Delete field
    $(document).on('click', '.fs-field-delete', function() {
        if (confirm('<?php esc_html_e('Delete this field?', 'freelance-studio'); ?>')) {
            $(this).closest('.fs-form-field-item').slideUp(200, function() {
                $(this).remove();
                updateFieldIndexes();
                updateConditionalFieldSelects();
                if ($('#fs-form-fields .fs-form-field-item').length === 0) {
                    $('#fs-form-fields').html('<div class="fs-empty-fields-message"><span class="dashicons dashicons-plus-alt2"></span><p><?php esc_html_e('Click a field type on the right to add it to your form.', 'freelance-studio'); ?></p></div>');
                }
            });
        }
    });
    
    // Duplicate field
    $(document).on('click', '.fs-field-duplicate', function() {
        var $field = $(this).closest('.fs-form-field-item');
        var $clone = $field.clone();
        var newId = 'field_' + Date.now();
        $clone.attr('data-field-id', newId);
        $clone.find('input[name*="[id]"]').val(newId);
        $clone.insertAfter($field);
        updateFieldIndexes();
        updateConditionalFieldSelects();
        fieldIndex++;
    });
    
    // Update label preview
    $(document).on('input', '.fs-field-label-input', function() {
        $(this).closest('.fs-form-field-item').find('.fs-field-label-preview').text($(this).val());
    });
    
    // Update required indicator
    $(document).on('change', '.fs-field-required-input', function() {
        var $preview = $(this).closest('.fs-form-field-item').find('.fs-field-preview');
        if ($(this).is(':checked')) {
            if (!$preview.find('.required').length) $preview.append('<span class="required">*</span>');
        } else {
            $preview.find('.required').remove();
        }
    });
    
    // Add option
    $(document).on('click', '.fs-add-option', function() {
        var $list = $(this).siblings('.fs-field-options-list');
        var $first = $list.find('.fs-field-option-row').first();
        var name = $first.find('input').attr('name');
        var optNum = $list.find('.fs-field-option-row').length + 1;
        $list.append('<div class="fs-field-option-row"><input type="text" name="' + name + '" class="regular-text" placeholder="<?php esc_attr_e('Option', 'freelance-studio'); ?> ' + optNum + '"><button type="button" class="fs-remove-option button-link"><span class="dashicons dashicons-no-alt"></span></button></div>');
    });
    
    // Remove option
    $(document).on('click', '.fs-remove-option', function() {
        var $list = $(this).closest('.fs-field-options-list');
        if ($list.find('.fs-field-option-row').length > 1) {
            $(this).closest('.fs-field-option-row').remove();
        }
    });
    
    // Select file (media library)
    $(document).on('click', '.fs-select-file', function() {
        var $btn = $(this);
        var frame = wp.media({title: '<?php esc_html_e('Select File', 'freelance-studio'); ?>', multiple: false});
        frame.on('select', function() {
            var attachment = frame.state().get('selection').first().toJSON();
            $btn.siblings('.fs-file-id').val(attachment.id);
            $btn.siblings('.fs-file-url').val(attachment.url);
        });
        frame.open();
    });
    
    // Copy link button
    $('#fs-copy-link-btn').on('click', function() {
        var url = $('#fs-form-public-url').val();
        navigator.clipboard.writeText(url);
        $(this).text('<?php esc_html_e('Copied!', 'freelance-studio'); ?>');
        setTimeout(function() { $('#fs-copy-link-btn').text('<?php esc_html_e('Copy', 'freelance-studio'); ?>'); }, 2000);
    });
    
    // Toggle conditional logic settings
    $(document).on('change', '.fs-conditional-enabled', function() {
        var $settings = $(this).closest('.fs-field-conditional-logic').find('.fs-conditional-settings');
        if ($(this).is(':checked')) {
            $settings.slideDown(200);
            updateConditionalFieldSelects();
        } else {
            $settings.slideUp(200);
        }
    });
    
    // Add conditional rule
    $(document).on('click', '.fs-add-rule', function() {
        var $rules = $(this).siblings('.fs-conditional-rules');
        var ruleIndex = $rules.find('.fs-conditional-rule').length;
        var $field = $(this).closest('.fs-form-field-item');
        var fieldIdx = $field.index();
        
        var html = '<div class="fs-conditional-rule">';
        html += '<select name="fields[' + fieldIdx + '][conditional_logic][rules][' + ruleIndex + '][field_id]" class="fs-conditional-field-select"><option value=""><?php esc_html_e('Select a field...', 'freelance-studio'); ?></option></select>';
        html += '<select name="fields[' + fieldIdx + '][conditional_logic][rules][' + ruleIndex + '][operator]" class="fs-conditional-operator">';
        html += '<option value="equals"><?php esc_html_e('equals', 'freelance-studio'); ?></option><option value="not_equals"><?php esc_html_e('does not equal', 'freelance-studio'); ?></option>';
        html += '<option value="contains"><?php esc_html_e('contains', 'freelance-studio'); ?></option><option value="not_contains"><?php esc_html_e('does not contain', 'freelance-studio'); ?></option>';
        html += '<option value="is_empty"><?php esc_html_e('is empty', 'freelance-studio'); ?></option><option value="is_not_empty"><?php esc_html_e('is not empty', 'freelance-studio'); ?></option></select>';
        html += '<input type="text" name="fields[' + fieldIdx + '][conditional_logic][rules][' + ruleIndex + '][value]" class="fs-conditional-value" placeholder="<?php esc_attr_e('Value', 'freelance-studio'); ?>">';
        html += '<button type="button" class="fs-remove-rule button-link"><span class="dashicons dashicons-no-alt"></span></button>';
        html += '</div>';
        
        $rules.append(html);
        updateConditionalFieldSelects();
    });
    
    // Remove conditional rule
    $(document).on('click', '.fs-remove-rule', function() {
        var $rules = $(this).closest('.fs-conditional-rules');
        if ($rules.find('.fs-conditional-rule').length > 1) {
            $(this).closest('.fs-conditional-rule').remove();
        }
    });
    
    // Update selects when field label changes
    $(document).on('input', '.fs-field-label-input', function() {
        updateConditionalFieldSelects();
    });
    
    // Initial population of conditional field selects
    setTimeout(updateConditionalFieldSelects, 100);
});
</script>
