<?php
// components/Form/ScheduleConfig.php
// Composite scheduling UI element: flow-like left-to-right layout
// with Start condition box (Now / On Date) and End condition box
// (varies per schedule_type: Bulk?Completed/Date, Scheduled?Date, Automation?Never/Date).
// Fully Alpine.js-driven reactivity.

namespace Components\Form;

use Components\Ui\TabsGroup;

class ScheduleConfig extends BaseField
{
    /**
     * Render the schedule configuration composite element.
     *
     * Expected form fields (managed via Alpine x-model on the parent form):
     *   - schedule_type:          'bulk_mail' | 'scheduled_window' | 'automation'
     *   - start_mode:             'now' | 'date'
     *   - newsletter_item_start:  date string (when start_mode=date)
     *   - newsletter_item_end:    date string (when end requires a date)
     *   - automation_end_mode:    'never' | 'date' (for automation schedule_type)
     *
     * Field name mappings can be overridden via $def keys.
     */
    public static function render(string $name, string $label, $value, array $def, array $opts): string
    {
        $errors = $opts['errors'] ?? [];

        // Field name mappings (configurable via YAML def)
        $f = [
            'schedule_type'     => (string)($def['schedule_type_field']     ?? 'schedule_type'),
            'start_mode'        => (string)($def['start_mode_field']        ?? 'start_mode'),
            'start_date'        => (string)($def['start_date_field']        ?? 'newsletter_item_start'),
            'end_date'          => (string)($def['end_date_field']          ?? 'newsletter_item_end'),
            'automation_end'    => (string)($def['automation_end_mode_field'] ?? 'automation_end_mode'),
        ];

        // Translated labels
        $t = array(
            'start'             => self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_START', 'Start')),
            'start_text'        => self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_START_TEXT', 'Sending starts')),
            'end'               => self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_END', 'End')),
            'end_text'          => self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_END_TEXT', 'Sending ends')),
            'now'               => self::h((string)\mh_lng('MAILBEEZ_NEWSLETTER_START_NOW', 'Now')),
            'on_date'           => self::h((string)\mh_lng('MAILBEEZ_NEWSLETTER_START_DATE', 'On Date')),
            'completed'         => self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_COMPLETED_SHORT', 'Completed')),
            'completed_date'    => self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_COMPLETED_DATE_SHORT', 'Not later than')),
            'never'             => self::h((string)\mh_lng('MAILBEEZ_NEWSLETTER_AUTOMATION_END_NEVER', 'Never')),
            'date'              => self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_DATE', 'Date')),
            'not_later_than'    => self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_NOT_LATER', 'but not later than')),
            'customize'         => self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_CUSTOMIZE', 'Anpassen')),
            // Inline explainers to reduce visual clutter when inputs are not needed
            'start_now_hint'    => self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_HINT_START_NOW', 'Sending starts as soon as you set the newsletter active.')),
            'end_completed_hint'=> self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_HINT_END_COMPLETED', 'Sending stops automatically when all recipients are processed.')),
            'end_never_hint'    => self::h((string)\mh_lng('MAILBEEZ_SCHEDULE_HINT_END_NEVER', 'This automation keeps running until you stop it.')),
            // Summary tokens
            'starts_now'        => (string)\mh_lng('MAILBEEZ_SCHEDULE_SUMMARY_STARTS_NOW', 'Starts immediately'),
            'starts_on'         => (string)\mh_lng('MAILBEEZ_SCHEDULE_SUMMARY_STARTS_ON', 'Starts'),
            'stops_finished'    => (string)\mh_lng('MAILBEEZ_SCHEDULE_SUMMARY_STOPS_FINISHED', 'Stops when finished'),
            'stops_on'          => (string)\mh_lng('MAILBEEZ_SCHEDULE_SUMMARY_STOPS_ON', 'Stops'),
            'runs_indefinitely' => (string)\mh_lng('MAILBEEZ_SCHEDULE_SUMMARY_RUNS_INDEFINITELY', 'Runs indefinitely'),
        );

        // JSON-safe versions for Alpine
        $fJson = htmlspecialchars(json_encode($f, JSON_UNESCAPED_UNICODE), ENT_QUOTES);
        $tJson = htmlspecialchars(json_encode($t, JSON_UNESCAPED_UNICODE), ENT_QUOTES);

        $errorHtml = self::errorsHtml($errors);

        $startTabs = TabsGroup::render([
            ['label' => $t['now'], 'click' => "setStart('now')", 'active' => "sm === 'now'"],
            ['label' => $t['on_date'], 'click' => "setStart('date')", 'active' => "sm === 'date'"]
        ], [
            'fullWidth' => true,
            'model' => 'sm'
        ]);

        $bulkEndTabs = TabsGroup::render([
            ['label' => $t['completed'], 'click' => "setEndTab('completed')", 'active' => "endTab === 'completed'"],
            ['label' => $t['completed_date'], 'click' => "setEndTab('date')", 'active' => "endTab === 'date'"]
        ], [
            'fullWidth' => true,
            'model' => 'endTab'
        ]);

        $scheduledEndTabs = TabsGroup::render([
            ['label' => $t['date'], 'active' => 'true']
        ], ['fullWidth' => true]);

        $automationEndTabs = TabsGroup::render([
            ['label' => $t['never'], 'click' => "setEndTab('never')", 'active' => "ae === 'never'"],
            ['label' => $t['date'], 'click' => "setEndTab('date')", 'active' => "ae === 'date'"]
        ], [
            'fullWidth' => true,
            'model' => 'ae'
        ]);

        // Picker open JS snippet
        $pickerJs = "if (\$event.target && typeof \$event.target.showPicker === 'function') { \$event.target.showPicker() }";

        // Date input renderers (using Input UI for visual alignment)
        $startInput = Input::render($f['start_date'], '', '', [
            'no_label'        => true,
            'input_type'      => 'date',
            'input_class'     => '!w-32',
            'input_attrs'     => ':name="f.start_date" x-model="form[f.start_date]" @input="validateField(f.start_date); _ensureEndDate()" @change="validateField(f.start_date); _ensureEndDate()" @click="' . $pickerJs . '"',
            'container_class' => 'flex-none',
        ]);

        $endInput = Input::render($f['end_date'], '', '', [
            'no_label'        => true,
            'input_type'      => 'date',
            'input_class'     => '!w-32',
            'input_attrs'     => ':name="f.end_date" x-model="form[f.end_date]" :min="_addDays(sd, 1)" @input="validateField(f.end_date); _ensureEndDate()" @change="validateField(f.end_date); _ensureEndDate()" @click="' . $pickerJs . '"',
            'container_class' => 'flex-none',
        ]);

        // Arrow SVG connector
        $arrowSvg = '<svg class="shrink-0 w-8 h-8 text-gray-300 dark:text-gray-600" fill="none" viewBox="0 0 32 32"><path d="M8 16h16m0 0l-5-5m5 5l-5 5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';

        return <<<HTML
<div x-data="{
    f: {$fJson},
    t: {$tJson},
    showAdvanced: false,
    get st()    { return (typeof form!=='undefined' && form) ? (form[this.f.schedule_type] || 'bulk_mail') : 'bulk_mail'; },
    get sm()    { return (typeof form!=='undefined' && form) ? (form[this.f.start_mode] || 'now') : 'now'; },
    get sd()    { return (typeof form!=='undefined' && form) ? (form[this.f.start_date] || '') : ''; },
    get ed()    { return (typeof form!=='undefined' && form) ? (form[this.f.end_date] || '') : ''; },
    get ae()    { return (typeof form!=='undefined' && form) ? (form[this.f.automation_end] || 'never') : 'never'; },
    get isDefault() {
        if (this.sm !== 'now') return false;
        if (this.st === 'bulk_mail') return this.endTab === 'completed';
        if (this.st === 'automation') return this.ae === 'never';
        return false;
    },
    get isCollapsed() { return this.isDefault && !this.showAdvanced; },
    _bulkEnd: null,
    _fmtDateLocal(d) {
        var y = d.getFullYear();
        var m = String(d.getMonth() + 1).padStart(2, '0');
        var da = String(d.getDate()).padStart(2, '0');
        return y + '-' + m + '-' + da;
    },
    _isInvalidDate(v) {
        return !v || v === '1000-01-01' || v === '0000-00-00' || String(v).startsWith('0000');
    },
    _tomorrow() {
        var d = new Date();
        d.setHours(0,0,0,0);
        d.setDate(d.getDate() + 1);
        return this._fmtDateLocal(d);
    },
    _addDays(dateStr, days) {
        if (this._isInvalidDate(dateStr)) return '';
        var ds = String(dateStr).slice(0, 10);
        var d = new Date(ds + 'T00:00:00');
        if (isNaN(d.getTime())) return '';
        d.setHours(0,0,0,0);
        d.setDate(d.getDate() + days);
        return this._fmtDateLocal(d);
    },
    _ensureEndDate() {
        if (!(typeof form!=='undefined' && form)) return;
        var sd = form[this.f.start_date];
        // If start date is missing or sentinel, seed it (it's always needed for relative end calculations)
        if (this._isInvalidDate(sd)) {
            sd = this._tomorrow();
            form[this.f.start_date] = sd;
        }

        var st = this.st;
        var requireDate = false;
        if (st === 'scheduled_window') {
            requireDate = true;
        } else if (st === 'bulk_mail') {
            requireDate = (this.endTab === 'date');
        } else if (st === 'automation') {
            requireDate = (this.ae === 'date');
        }
        if (!requireDate) return;

        var ed = form[this.f.end_date];
        var minEnd = this._addDays(sd, 1);
        var defaultEnd = this._addDays(sd, 7);
        if (this._isInvalidDate(ed)) {
            form[this.f.end_date] = defaultEnd;
        }
        else if (ed < minEnd) {
            form[this.f.end_date] = minEnd;
        }
    },
    setStart(v) {
        if (!(typeof form!=='undefined' && form)) return;
        form[this.f.start_mode] = v;
        if (v === 'now') { /* keep previously chosen date to preserve user intent */ }
        else if (this._isInvalidDate(form[this.f.start_date])) { form[this.f.start_date] = this._tomorrow(); this._ensureEndDate(); }
    },
    setEndTab(v) {
        var st = this.st;
        if (st === 'bulk_mail') {
            this._bulkEnd = v;
            if (!(typeof form!=='undefined' && form)) return;
            if (v === 'completed') {
                form[this.f.end_date] = '';
            }
            else if (v === 'date' && this._isInvalidDate(form[this.f.end_date])) {
                var sd = form[this.f.start_date];
                form[this.f.end_date] = sd ? this._addDays(sd, 7) : this._addDays(this._tomorrow(), 7);
            }
        } else if (st === 'automation') {
            if (!(typeof form!=='undefined' && form)) return;
            form[this.f.automation_end] = v;
            if (v === 'never') {
                form[this.f.end_date] = '';
            }
            else if (v === 'date' && this._isInvalidDate(form[this.f.end_date])) {
                var sd = form[this.f.start_date];
                form[this.f.end_date] = sd ? this._addDays(sd, 7) : this._addDays(this._tomorrow(), 7);
            }
        }
    },
    get endTab() {
        var st = this.st;
        if (st === 'bulk_mail') {
            if (this._bulkEnd !== null) return this._bulkEnd;
            return (this.ed && !this._isInvalidDate(this.ed)) ? 'date' : 'completed';
        }
        if (st === 'automation') { return this.ae; }
        return 'completed'; // scheduled_window
    },
    get showEndDate() {
        var st = this.st;
        if (st === 'scheduled_window') return true;
        if (st === 'bulk_mail') return this.endTab === 'date';
        if (st === 'automation') return this.ae === 'date';
        return false;
    },
    // summary computed by shared BeezUI helper; keep getter for compatibility but delegate
    get summaryText() {
        var hasBeez = (typeof window!=='undefined' && window.BeezUI && typeof window.BeezUI.scheduleSummary==='function');
        var f = (typeof form!=='undefined' && form) ? form : {};
        return hasBeez ? window.BeezUI.scheduleSummary(this.f, this.t, f) : '';
    }
}"
    x-init="setTimeout(() => {
        if (f && typeof form!=='undefined' && form) {
            _ensureEndDate();
        }
    }, 0);
    \$watch('st', () => { _ensureEndDate(); });
    \$watch('ae', () => { _ensureEndDate(); });
    \$watch('sm', () => { _ensureEndDate(); });
    \$watch('sd', () => { _ensureEndDate(); });"
    class="space-y-3">

    <!-- Component Label -->
    <div class="flex items-center justify-between gap-4">
        <template x-if="'{$label}' !== 'schedule_config' && '{$label}' !== ''">
            <div class="block text-sm/6 font-medium text-gray-900 dark:text-white  truncate">{$label}</div>
        </template>
        <button type="button" x-show="isCollapsed" @click="showAdvanced = true" 
                class="text-sm font-medium text-brand hover:text-brand-dark transition-colors shrink-0">
            {$t['customize']}
        </button>
    </div>

    <!-- Summary line (Static Subtitle for the whole component) -->
    <div class="text-sm text-secondary leading-relaxed" x-text="summaryText"></div>

    <!-- Flow: Start ? End -->
    <!-- Stack vertically on small screens, side-by-side from sm+ -->
    <div x-show="!isCollapsed" x-collapse
         class="flex flex-col sm:flex-row items-stretch gap-1">

        <!-- ?? START BOX ?? -->
        <div class="flex-1 rounded-lg border border-gray-200 dark:border-white/10 dark:bg-gray-800/40 p-4 space-y-2 overflow-hidden flex flex-col">
            <!-- Header with Title and Static Subtitle -->
            <div>
<!--                <div class="text-sm font-semibold text-gray-900 dark:text-gray-100 ">{$t['start']}</div>-->
                <div class="text-sm text-gray-500 dark:text-gray-400">{$t['start_text']}</div>
            </div>

            {$startTabs}

            <!-- Body: dynamic subtitle and input -->
            <div class="flex-1 flex flex-col justify-start pt-1">
                <!-- Hint for 'now' mode -->
                <template x-if="sm === 'now'">
                    <div class="flex items-start">
                        <div class="text-sm text-gray-500 dark:text-gray-400" x-text="t.start_now_hint"></div>
                    </div>
                </template>

                <!-- Inline Label + Date Picker for 'date' mode -->
                <div x-show="sm === 'date'" class="flex flex-col flex-1">
                    <div class="flex items-start gap-2">
                        <span class="text-sm text-gray-500 dark:text-gray-400 pt-1.5 flex-1" x-text="t.on_date"></span>
                        {$startInput}
                    </div>
                    <!-- Hidden inputs to persist values -->
                    <input type="hidden" :name="f.start_mode" x-model="form[f.start_mode]" />
                </div>
            </div>
        </div>

        <!-- Arrow connector: rotates downwards on small screens when stacked -->
        <div class="flex items-center justify-center shrink-0 self-center sm:self-start mt-4 sm:rotate-0 rotate-90 transition-transform">
            {$arrowSvg}
        </div>

        <!-- ?? END BOX ?? -->
        <div class="flex-1 rounded-lg border border-gray-200 dark:border-white/10 dark:bg-gray-800/40 p-4 space-y-2 overflow-hidden flex flex-col">
            <!-- Header with Title and Static Subtitle -->
            <div>
<!--                <div class="text-sm font-semibold text-gray-900 dark:text-gray-100">{$t['end']}</div>-->
                <div class="text-sm text-gray-500 dark:text-gray-400">{$t['end_text']}</div>
            </div>

            <!-- Tabs (vary by schedule_type) -->
            <div>
                <!-- Bulk Mail: Completed | Date -->
                <template x-if="st === 'bulk_mail'">
                    {$bulkEndTabs}
                </template>

                <!-- Scheduled Window: always Date (no tabs needed) -->
                <template x-if="st === 'scheduled_window'">
                    {$scheduledEndTabs}
                </template>

                <!-- Automation: Never | Date -->
                <template x-if="st === 'automation'">
                    {$automationEndTabs}
                </template>
            </div>

            <!-- Body: dynamic subtitle and input -->
            <div class="flex-1 flex flex-col justify-start pt-1">
                <!-- Hints for 'completed' / 'never' -->
                <template x-if="st === 'bulk_mail' && endTab === 'completed'">
                    <div class="flex items-start ">
                        <div class="text-sm text-gray-500 dark:text-gray-400" x-text="t.end_completed_hint"></div>
                    </div>
                </template>
                <template x-if="st === 'automation' && ae === 'never'">
                    <div class="flex items-start">
                        <div class="text-sm text-gray-500 dark:text-gray-400" x-text="t.end_never_hint"></div>
                    </div>
                </template>

                <!-- Inline Label + Date Picker for date modes -->
                <div x-show="showEndDate" class="flex flex-col flex-1">
                    <div class="flex items-start gap-2">
                        <span class="text-sm text-gray-500 dark:text-gray-400 pt-1.5 flex-1"
                              x-text="st === 'bulk_mail' ? t.completed_date : t.date"></span>
                        {$endInput}
                    </div>

                    <!-- Hidden inputs for end mode persistence -->
                    <input type="hidden" :name="f.automation_end" x-model="form[f.automation_end]" />
                </div>
            </div>
        </div>
    </div>

    {$errorHtml}
</div>
HTML;
    }
}
