<?php

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

$id          = $field['id'];
$name        = $field['name'] ?? $id;
$label       = $field['label'] ?? '';
$type        = $field['type'];
$options     = $field['options'] ?? [];
$default     = $field['default'] ?? '';
$placeholder = $field['placeholder'] ?? '';
$description = $field['description'] ?? '';
$help        = $field['help'] ?? '';
$is_pro      = !empty($field['pro']) && !fast_fuzzy_search_is_pro();

// WordPress array-format name so options.php writes into the option
$input_name  = $option_name . '[' . $name . ']';
$input_name_esc = esc_attr( $input_name );

$placeholder_attr = $placeholder !== '' ? ' placeholder="' . esc_attr($placeholder) . '"' : '';

?>

<?php if ($type === 'text'): ?>
    <input
        type="text"
        id="<?php echo esc_attr($id); ?>"
        name="<?php echo $input_name_esc; ?>"
        value="<?php echo esc_attr($value); ?>"
        class="ffs-input"
        <?php echo $placeholder_attr; ?>
    />

<?php elseif ($type === 'number'): ?>
    <?php
    $unit      = $field['unit']      ?? '';
    $min_attr  = isset($field['min'])  ? ' min="' . esc_attr($field['min']) . '"'  : '';
    $max_attr  = isset($field['max'])  ? ' max="' . esc_attr($field['max']) . '"'  : '';
    $step_attr = isset($field['step']) ? ' step="' . esc_attr($field['step']) . '"' : '';
    ?>
    <div class="ffs-range">
        <input
            type="number"
            id="<?php echo esc_attr($id); ?>"
            name="<?php echo $input_name_esc; ?>"
            value="<?php echo esc_attr($value); ?>"
            class="ffs-input"
            <?php echo $placeholder_attr . $min_attr . $max_attr . $step_attr; ?>
        />
        <?php if ($unit): ?>
            <span class="ffs-form-row__help ffs-min-w-0" aria-hidden="true"><?php echo esc_html($unit); ?></span>
        <?php endif; ?>
    </div>

<?php elseif ($type === 'textarea'): ?>
    <textarea
        id="<?php echo esc_attr($id); ?>"
        name="<?php echo $input_name_esc; ?>"
        class="ffs-input ffs-input--textarea"
        rows="5"
        <?php echo $placeholder_attr; ?>
    ><?php echo esc_textarea($value); ?></textarea>

<?php elseif ($type === 'checkbox'): ?>
    <label class="ffs-choice-card" style="max-width:480px;">
        <input
            type="checkbox"
            id="<?php echo esc_attr($id); ?>"
            name="<?php echo $input_name_esc; ?>"
            value="1"
            <?php checked($value, '1'); ?>
        />
        <div class="ffs-choice-card__body">
            <span class="ffs-choice-card__title"><?php echo esc_html($label); ?></span>
            <?php if ($description): ?>
                <span class="ffs-choice-card__description"><?php echo esc_html($description); ?></span>
            <?php endif; ?>
        </div>
    </label>

<?php elseif ($type === 'checkbox_group'): ?>
    <?php $current_values = is_array( $value ) ? $value : (array) $value; ?>
    <div class="ffs-flex ffs-flex-col" style="gap:var(--ffs-space-2);">
    <?php foreach ($options as $option_value => $option_label):
        $opt_label = is_array($option_label) ? ($option_label['label'] ?? '') : $option_label;
        $opt_desc  = is_array($option_label) ? ($option_label['description'] ?? '') : '';
    ?>
        <label class="ffs-choice-card">
            <input
                type="checkbox"
                id="<?php echo esc_attr($option_value); ?>"
                value="<?php echo esc_attr($option_value); ?>"
                name="<?php echo $input_name_esc; ?>[]"
                <?php checked( in_array( (string) $option_value, $current_values, true ) ); ?>
            />
            <div class="ffs-choice-card__body">
                <span class="ffs-choice-card__title"><?php echo esc_html($opt_label); ?></span>
                <?php if ($opt_desc): ?>
                    <span class="ffs-choice-card__description"><?php echo esc_html($opt_desc); ?></span>
                <?php endif; ?>
            </div>
        </label>
    <?php endforeach; ?>
    </div>

<?php elseif ($type === 'radio'): ?>
    <div class="ffs-flex ffs-flex-col" style="gap:var(--ffs-space-2);">
        <?php foreach ($options as $option_value => $option_label):
            $opt_label = is_array($option_label) ? ($option_label['label'] ?? '') : $option_label;
            $opt_desc  = is_array($option_label) ? ($option_label['description'] ?? '') : '';
            $is_selected = (string) $value === (string) $option_value;
        ?>
            <label class="ffs-choice-card<?php echo $is_selected ? ' is-selected' : ''; ?>">
                <input
                    type="radio"
                    name="<?php echo $input_name_esc; ?>"
                    value="<?php echo esc_attr($option_value); ?>"
                    <?php checked($is_selected); ?>
                />
                <div class="ffs-choice-card__body">
                    <span class="ffs-choice-card__title"><?php echo esc_html($opt_label); ?></span>
                    <?php if ($opt_desc): ?>
                        <span class="ffs-choice-card__description"><?php echo esc_html($opt_desc); ?></span>
                    <?php endif; ?>
                </div>
            </label>
        <?php endforeach; ?>
    </div>

<?php elseif ($type === 'select'): ?>
    <select
        id="<?php echo esc_attr($id); ?>"
        name="<?php echo $input_name_esc; ?>"
        class="ffs-input ffs-input--select"
    >
        <?php foreach ($options as $option_value => $option_label):
            $opt_label = is_array($option_label) ? ($option_label['label'] ?? '') : $option_label;
        ?>
            <option value="<?php echo esc_attr($option_value); ?>" <?php selected($value, $option_value); ?>>
                <?php echo esc_html($opt_label); ?>
            </option>
        <?php endforeach; ?>
    </select>

<?php elseif ($type === 'color_picker'): ?>
    <label class="ffs-color-label">
        <input
            class="ffs-color-input"
            type="color"
            id="<?php echo esc_attr($id); ?>"
            name="<?php echo $input_name_esc; ?>"
            value="<?php echo esc_attr($value); ?>"
        />
        <span class="ffs-color-text"><?php esc_html_e('Pick a color', 'fast-fuzzy-search'); ?></span>
    </label>

<?php elseif ($type === 'range'): ?>
    <?php
    $min_attr  = isset($field['min'])  ? (int) $field['min']  : 0;
    $max_attr  = isset($field['max'])  ? (int) $field['max']  : 100;
    $step_attr = isset($field['step']) ? (int) $field['step'] : 1;
    $unit      = $field['unit'] ?? '';
    ?>
    <div class="ffs-range" x-data="{ rangeVal: <?php echo (int) $value; ?> }">
        <input
            type="range"
            x-model.number="rangeVal"
            id="<?php echo esc_attr($id); ?>"
            name="<?php echo $input_name_esc; ?>"
            min="<?php echo esc_attr($min_attr); ?>"
            max="<?php echo esc_attr($max_attr); ?>"
            step="<?php echo esc_attr($step_attr); ?>"
            value="<?php echo esc_attr($value); ?>"
            class="ffs-range__slider"
        />
        <span class="ffs-range__value">
            <span x-text="rangeVal"></span><?php if ($unit): ?><span><?php echo esc_html($unit); ?></span><?php endif; ?>
        </span>
    </div>

<?php elseif ($type === 'switch'): ?>
    <label class="ffs-switch">
        <input
            type="checkbox"
            id="<?php echo esc_attr($id); ?>"
            name="<?php echo $input_name_esc; ?>"
            value="1"
            <?php checked($value, '1'); ?>
            class="ffs-switch__input"
        />
        <span class="ffs-switch__track">
            <span class="ffs-switch__thumb"></span>
        </span>
        <span class="ffs-switch__label">
            <?php echo esc_html($field['switch_label'] ?? $field['description'] ?? ''); ?>
        </span>
    </label>

<?php elseif ($type === 'image_radio'): ?>
    <?php
    $is_aesthetic = $id === 'aesthetic';
    $aesthetic_val = is_array( $value ) ? ( $value['aesthetic'] ?? 'minimal-light' ) : (string) $value;

    // Read initial CSS content from the generated file in uploads, falling back to the saved option from the option, and the generated file content for initial editor fill
    $custom_css_opt = '';
    $upload_css_content = '';
    if ( $is_aesthetic ) {
        $saved = get_option( 'fast_fuzzy_search_options', [] );
        $custom_css_opt = isset( $saved['custom_css'] ) ? $saved['custom_css'] : '';
        // Read the generated file from uploads, if it exists
        $upload_dir = wp_upload_dir();
        $upload_css_path = $upload_dir['basedir'] . '/fast-fuzzy-search/custom.css';
        if ( file_exists( $upload_css_path ) ) {
            $upload_css_content = file_get_contents( $upload_css_path );
        }
    }
    $initial_css = $upload_css_content !== '' ? $upload_css_content : $custom_css_opt;
    ?>
    <?php if ( $is_aesthetic ): ?>
    <div
        class="ffs-flex ffs-flex-wrap ffs-gap-4"
        x-data="aestheticPicker(
            '<?php echo esc_js( $aesthetic_val ); ?>',
            true,
            <?php echo esc_attr( json_encode( $initial_css ) ); ?>
        )"
    >
    <?php else: ?>
    <div
        class="ffs-flex ffs-flex-wrap ffs-gap-4"
        x-data="{ selected: '<?php echo esc_js($value); ?>' }"
    >
    <?php endif; ?>

        <?php foreach ($options as $option_value => $option):
            $is_option_pro = !empty($option['pro']) && !fast_fuzzy_search_is_pro();
            $opt_label     = $option['label'] ?? '';
            $opt_image     = $option['image'] ?? '';
            $opt_desc      = $option['description'] ?? '';
        ?>
            <label
                class="ffs-img-radio <?php echo $is_option_pro ? 'ffs-pro-label' : ''; ?>"
                x-bind:class="{ 'ffs-img-radio--selected': selected === '<?php echo esc_js($option_value); ?>' }"
            >
                <div class="ffs-flex-start ffs-gap-2 ffs-mb-3">
                    <input
                        type="radio"
                        name="<?php echo $input_name_esc; ?>"
                        value="<?php echo esc_attr($option_value); ?>"
                        <?php disabled($is_option_pro); ?>
                        <?php checked( $is_aesthetic ? $aesthetic_val : $value, $option_value ); ?>
                        x-on:change="selected = '<?php echo esc_js($option_value); ?>'"
                    />
                    <h3 style="margin:0;padding:0;font-size:var(--ffs-font-size-small);font-weight:var(--ffs-font-weight-medium);">
                        <?php echo esc_html($opt_label); ?>
                    </h3>
                </div>
                <?php if ($opt_image): ?>
                    <img
                        src="<?php echo esc_url($opt_image); ?>"
                        alt="<?php echo esc_attr($opt_label); ?>"
                        x-bind:class="{
                            'ffs-img-radio-img--selected': selected === '<?php echo esc_js($option_value); ?>',
                            'ffs-img-radio-img--default': selected !== '<?php echo esc_js($option_value); ?>'
                        }"
                    />
                <?php endif; ?>
                <?php if ($opt_desc): ?>
                    <p class="ffs-form-row__help ffs-mt-2 ffs-mb-0"><?php echo esc_html($opt_desc); ?></p>
                <?php endif; ?>
            </label>
        <?php endforeach; ?>

        <?php if ($is_aesthetic): ?>
        <div x-show="isCustom" x-cloak class="ffs-card ffs-card--compact" style="width:100%;margin-top:var(--ffs-space-4);">
            <label for="custom_base_theme" style="display:block;font-weight:500;margin-bottom:4px;">
                <?php esc_html_e( 'Base theme', 'fast-fuzzy-search' ); ?>
            </label>
            <p style="font-size:13px;color:var(--ffs-gray-700);margin:0 0 12px;">
                <?php esc_html_e( 'Select a built-in theme and click "Load" to import its CSS as a starting point.', 'fast-fuzzy-search' ); ?>
            </p>
            <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
                <select id="custom_base_theme"
                        x-model="baseTheme"
                        style="max-width:320px;">
                    <option value="">— <?php esc_html_e( 'Select base theme', 'fast-fuzzy-search' ); ?> —</option>
                    <?php
                    $base_themes = [
                        'free' => [
                            'minimal-light' => __('Minimal Light', 'fast-fuzzy-search'),
                            'minimal-dark'  => __('Minimal Dark', 'fast-fuzzy-search'),
                        ],
                    ];
                    if ( fast_fuzzy_search_is_pro() ) {
                        $base_themes['pro'] = [
                            'material-light' => __('Material Light', 'fast-fuzzy-search'),
                            'material-dark'  => __('Material Dark', 'fast-fuzzy-search'),
                            'glassmorphic'   => __('Glassmorphic', 'fast-fuzzy-search'),
                            'brutal'         => __('Brutal', 'fast-fuzzy-search'),
                            'iris'           => __('Iris', 'fast-fuzzy-search'),
                            'crisp'          => __('Crisp', 'fast-fuzzy-search'),
                            'terracotta'     => __('Terracotta', 'fast-fuzzy-search'),
                            'editorial'      => __('Editorial', 'fast-fuzzy-search'),
                        ];
                    }
                    ?>
                    <?php foreach ( $base_themes as $group_label => $group ): ?>
                    <optgroup label="<?php echo esc_attr( ucwords( $group_label ) ); ?>">
                        <?php foreach ( $group as $slug => $label ): ?>
                        <option value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $label ); ?></option>
                        <?php endforeach; ?>
                    </optgroup>
                    <?php endforeach; ?>
                </select>
                <button type="button" class="button button-primary" x-on:click="loadBaseTheme" x-bind:disabled="!baseTheme">
                    <?php esc_html_e( 'Load Base Theme', 'fast-fuzzy-search' ); ?>
                </button>
                <p x-show="baseTheme && cssContent.length > 0" x-cloak class="notice notice-warning">
                    <?php esc_html_e( 'Loading a new base theme will replace your current CSS. Save your changes first if you want to keep them.', 'fast-fuzzy-search' ); ?>
                </p>
            </div>

            <label for="custom_css" style="display:block;font-weight:500;margin-top:16px;margin-bottom:4px;">
                <?php esc_html_e( 'Custom CSS', 'fast-fuzzy-search' ); ?>
            </label>
            <textarea id="custom_css"
                      name="<?php echo esc_attr( $option_name . '[custom_css]' ); ?>"
                      class="ffs-input ffs-input--textarea"
                      rows="15"
                      x-model="cssContent"
                      placeholder=".fast-fuzzy-search--custom { /* your overrides */ }"></textarea>
            <p style="font-size:12px;color:var(--ffs-gray-600);margin-top:4px;">
                <?php esc_html_e( 'Your CSS is saved to wp-content/uploads/fast-fuzzy-search/custom.css and loaded on the front end.', 'fast-fuzzy-search' ); ?>
            </p>
        </div>
        <?php endif; ?>

    </div>

<?php elseif ($type === 'tabbed_radio'): ?>
    <?php
    $tab_ns = 'ffs_tab_' . preg_replace( '/[^a-zA-Z0-9_]/', '_', $name );
    $tab_id_base = 'ffs-seg-' . esc_attr($name);
    ?>
    <div class="ffs-tab-radio" x-data="{ <?php echo $tab_ns; ?>: '<?php echo esc_js($value); ?>' }">
        <div class="ffs-segmented" role="tablist">
            <?php foreach ($options as $option_value => $option):
                $is_option_pro = !empty($option['pro']) && !fast_fuzzy_search_is_pro();
                $opt_label     = $option['label'] ?? '';
                $tab_id        = $tab_id_base . '-' . esc_attr($option_value);
                $panel_id      = $tab_id_base . '-panel-' . esc_attr($option_value);
            ?>
                <label
                    role="tab"
                    class="ffs-segmented__option<?php echo $is_option_pro ? ' ffs-pro-label' : ''; ?>"
                    id="<?php echo $tab_id; ?>"
                    x-bind:class="{ 'is-active': <?php echo $tab_ns; ?> === '<?php echo esc_js($option_value); ?>' }"
                    x-bind:aria-selected="<?php echo $tab_ns; ?> === '<?php echo esc_js($option_value); ?>' ? 'true' : 'false'"
                >
                    <input
                        type="radio"
                        name="<?php echo $input_name_esc; ?>"
                        value="<?php echo esc_attr($option_value); ?>"
                        class="ffs-sr-only"
                        aria-labelledby="<?php echo $tab_id; ?>"
                        <?php checked( $value, $option_value ); ?>
                        x-on:change="<?php echo $tab_ns; ?> = $event.target.value"
                    />
                    <?php echo esc_html($opt_label); ?>
                </label>
            <?php endforeach; ?>
        </div>

        <div class="ffs-w-full">
            <?php foreach ($options as $option_value => $option):
                $opt_template = $option['template'] ?? '';
                $panel_id     = $tab_id_base . '-panel-' . esc_attr($option_value);
                $tab_id       = $tab_id_base . '-' . esc_attr($option_value);
            ?>
                <div
                    class="ffs-tab-radio__content"
                    id="<?php echo $panel_id; ?>"
                    role="tabpanel"
                    aria-labelledby="<?php echo $tab_id; ?>"
                    x-show="<?php echo $tab_ns; ?> === '<?php echo esc_js($option_value); ?>'"
                    x-cloak
                >
                    <?php if ($opt_template): ?>
                        <?php fast_fuzzy_search_get_template_part($opt_template); ?>
                    <?php else: ?>
                        <p class="ffs-form-row__help ffs-mt-3"><?php esc_html_e('No additional options for this choice.', 'fast-fuzzy-search'); ?></p>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

<?php elseif ($type === 'file'): ?>
    <input
        type="file"
        id="<?php echo esc_attr($id); ?>"
        name="<?php echo $input_name_esc; ?>"
        class="ffs-file-input"
    />

<?php elseif ($type === 'date'): ?>
    <input
        type="date"
        id="<?php echo esc_attr($id); ?>"
        name="<?php echo $input_name_esc; ?>"
        value="<?php echo esc_attr($value); ?>"
        class="ffs-date-input"
    />

<?php elseif ($type === 'repeater'): ?>
    <div x-data="{ items: <?php echo json_encode($value ? json_decode($value) : []); ?> }">
        <template x-for="(item, index) in items" :key="index">
            <div class="ffs-repeater">
                <input
                    type="text"
                    x-model="items[index]"
                    name="<?php echo $input_name_esc; ?>[]"
                />
                <button type="button" x-on:click="items.splice(index, 1)">
                    <span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
                    <?php esc_html_e('Remove', 'fast-fuzzy-search'); ?>
                </button>
            </div>
        </template>
        <button type="button" class="button button-secondary ffs-mt-2" x-on:click="items.push('')">
            <span class="dashicons dashicons-plus-alt2" aria-hidden="true"></span>
            <?php esc_html_e('Add item', 'fast-fuzzy-search'); ?>
        </button>
    </div>
<?php endif; ?>
