<?php
$placeholderMap = mkt_dynamic_placeholders();
$errors = $errors ?? [];
$tiers = $tiers ?? [];
$productsForAccess = $productsForAccess ?? [];
$thresholdPromotionsForAccess = $thresholdPromotionsForAccess ?? [];
$stage2Ready = isset($form_schema_ready) ? (bool)$form_schema_ready : mkt_schema_ready($db ?? null);
$form_submit_label = $form_submit_label ?? 'حفظ الحملة';
$form_back_href = $form_back_href ?? 'index.php';
$form_back_label = $form_back_label ?? 'رجوع';
?>

<?php if ($errors): ?>
    <div class="flash flash-error" style="margin-bottom:16px">
        <strong>يرجى معالجة الملاحظات التالية:</strong>
        <ul style="margin:8px 0 0;padding-right:18px">
            <?php foreach ($errors as $error): ?>
                <li><?= mkt_h($error) ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<form method="post" class="nay-form-grid" data-mkt-form="1">
    <div class="nay-card section-card" style="grid-column:1/-1">
        <h3>البيانات العامة</h3>
        <div class="nay-form-grid">
            <div>
                <label class="nay-label">اسم الحملة</label>
                <input class="nay-input" type="text" id="mkt_name" name="name" value="<?= mkt_h($form['name']) ?>" required>
            </div>
            <div>
                <label class="nay-label">الكود الداخلي</label>
                <input class="nay-input" type="text" name="code" value="<?= mkt_h($form['code']) ?>" placeholder="يُولَّد تلقائيًا إذا تركته فارغًا">
            </div>
            <div>
                <label class="nay-label">نوع الحملة</label>
                <select class="nay-input" name="campaign_type">
                    <?php foreach (mkt_campaign_types() as $key => $label): ?>
                        <option value="<?= mkt_h($key) ?>" <?= $form['campaign_type'] === $key ? 'selected' : '' ?>><?= mkt_h($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="nay-label">الجمهور المستهدف</label>
                <select class="nay-input" name="audience_type">
                    <?php foreach (mkt_audience_types() as $key => $label): ?>
                        <option value="<?= mkt_h($key) ?>" <?= $form['audience_type'] === $key ? 'selected' : '' ?>><?= mkt_h($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="nay-label">نوع المكافأة</label>
                <select class="nay-input" id="mkt_reward_type" name="reward_type">
                    <?php foreach (mkt_reward_types() as $key => $label): ?>
                        <option value="<?= mkt_h($key) ?>" <?= $form['reward_type'] === $key ? 'selected' : '' ?>><?= mkt_h($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="nay-label">قناة التنفيذ</label>
                <select class="nay-input" name="channel_type">
                    <?php foreach (mkt_channel_types() as $key => $label): ?>
                        <option value="<?= mkt_h($key) ?>" <?= $form['channel_type'] === $key ? 'selected' : '' ?>><?= mkt_h($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="nay-label">الحالة</label>
                <select class="nay-input" name="status">
                    <?php foreach (mkt_status_types() as $key => $label): ?>
                        <option value="<?= mkt_h($key) ?>" <?= $form['status'] === $key ? 'selected' : '' ?>><?= mkt_h($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="nay-label">الأولوية</label>
                <input class="nay-input" type="number" name="priority" value="<?= mkt_h($form['priority']) ?>">
            </div>
            <div style="grid-column:1/-1">
                <label class="nay-label">وصف مختصر</label>
                <textarea class="nay-input" name="description" rows="2"><?= mkt_h($form['description']) ?></textarea>
            </div>
        </div>
    </div>

    <div class="nay-card section-card" style="grid-column:1/-1">
        <h3>الشروط المركبة (AND)</h3>
        <div class="nay-form-grid">
            <div>
                <label class="nay-label">أيام عدم النشاط</label>
                <input class="nay-input" type="number" name="inactive_days" value="<?= mkt_h($form['inactive_days']) ?>" placeholder="مثال: 45">
                <div class="nay-help">مفيد مع جمهور الزبائن غير النشطين.</div>
            </div>
            <div>
                <label class="nay-label">عدد الأيام منذ التسجيل</label>
                <input class="nay-input" type="number" name="registration_days" value="<?= mkt_h($form['registration_days']) ?>" placeholder="مثال: 3">
            </div>
            <div>
                <label class="nay-label">المستوى المطلوب</label>
                <select class="nay-input" id="mkt_tier_id" name="tier_id">
                    <option value="">بدون</option>
                    <?php foreach ($tiers as $tier): ?>
                        <option value="<?= (int)$tier['id'] ?>" <?= (string)$form['tier_id'] === (string)$tier['id'] ? 'selected' : '' ?>><?= mkt_h($tier['title']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="nay-label">الحد الأدنى للصرف</label>
                <input class="nay-input" type="number" step="0.01" id="mkt_min_total_spent" name="min_total_spent" value="<?= mkt_h($form['min_total_spent']) ?>" placeholder="مثال: 250000">
            </div>
            <div>
                <label class="nay-label">الحد الأدنى لعدد الطلبات</label>
                <input class="nay-input" type="number" name="min_total_orders" value="<?= mkt_h($form['min_total_orders']) ?>" placeholder="مثال: 1">
            </div>
            <div>
                <label class="nay-label">الحد الأعلى لعدد الطلبات</label>
                <input class="nay-input" type="number" name="max_total_orders" value="<?= mkt_h($form['max_total_orders']) ?>" placeholder="مثال: 3">
            </div>
            <div>
                <label class="nay-label">مؤهل لمنتج ذكي</label>
                <select class="nay-input" name="eligible_product_id">
                    <option value="">بدون</option>
                    <?php foreach ($productsForAccess as $productOption): ?>
                        <option value="<?= (int)$productOption['id'] ?>" <?= (string)$form['eligible_product_id'] === (string)$productOption['id'] ? 'selected' : '' ?>><?= mkt_h($productOption['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <div class="nay-help">يفيد عند الحملات الخاصة بالمنتجات المقيدة بالمستوى أو الوصول الذكي.</div>
            </div>
            <div>
                <label class="nay-label">ضمن جمهور عرض حد أدنى</label>
                <select class="nay-input" name="eligible_threshold_promotion_id">
                    <option value="">بدون</option>
                    <?php foreach ($thresholdPromotionsForAccess as $promotionOption): ?>
                        <option value="<?= (int)$promotionOption['id'] ?>" <?= (string)$form['eligible_threshold_promotion_id'] === (string)$promotionOption['id'] ? 'selected' : '' ?>><?= mkt_h($promotionOption['title']) ?></option>
                    <?php endforeach; ?>
                </select>
                <div class="nay-help">يركز على جمهور العرض حسب المستوى/الجمهور، أما شرط مبلغ السلة فيبقى داخل checkout.</div>
            </div>
        </div>
        <div class="nay-help" style="margin-top:10px">كل شرط تمليه هنا يُحسب مع غيره بصيغة AND، يعني الزبون لازم يحققها كلها حتى يكون جاهزًا للحملة.</div>
    </div>

    <div class="nay-card section-card" style="grid-column:1/-1">
        <h3>الاستثناءات</h3>
        <div class="nay-form-grid">
            <div>
                <label class="nay-label">استثناء غير الموثقين</label>
                <label class="nay-checkbox"><input type="checkbox" name="exclude_unverified" value="1" <?= !empty($form['exclude_unverified']) ? 'checked' : '' ?>> <span>لا تشمل الزبائن غير الموثقين</span></label>
            </div>
            <div>
                <label class="nay-label">استثناء من لديه طلب معلق حديث (بالأيام)</label>
                <input class="nay-input" type="number" name="exclude_recent_pending_days" value="<?= mkt_h($form['exclude_recent_pending_days']) ?>" placeholder="مثال: 7">
            </div>
            <div>
                <label class="nay-label">استثناء مستوى معيّن</label>
                <select class="nay-input" name="exclude_tier_id">
                    <option value="">بدون</option>
                    <?php foreach ($tiers as $tier): ?>
                        <option value="<?= (int)$tier['id'] ?>" <?= (string)$form['exclude_tier_id'] === (string)$tier['id'] ? 'selected' : '' ?>><?= mkt_h($tier['title']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="nay-label">استثناء زبائن محددين</label>
                <input class="nay-input" type="text" name="exclude_customer_ids" value="<?= mkt_h($form['exclude_customer_ids']) ?>" placeholder="مثال: 4, 12, 19">
                <div class="nay-help">اكتب المعرفات مفصولة بفاصلة أو مسافة.</div>
            </div>
        </div>
    </div>

    <div class="nay-card section-card" style="grid-column:1/-1">
        <h3>المكافأة</h3>
        <div class="nay-form-grid">
            <div>
                <label class="nay-label">نوع خصم الكوبون</label>
                <select class="nay-input" id="mkt_coupon_discount_type" name="coupon_discount_type">
                    <option value="percent" <?= $form['coupon_discount_type'] === 'percent' ? 'selected' : '' ?>>نسبة مئوية</option>
                    <option value="fixed" <?= $form['coupon_discount_type'] === 'fixed' ? 'selected' : '' ?>>مبلغ ثابت</option>
                </select>
            </div>
            <div>
                <label class="nay-label">قيمة خصم الكوبون</label>
                <input class="nay-input" type="number" step="0.01" id="mkt_coupon_discount_value" name="coupon_discount_value" value="<?= mkt_h($form['coupon_discount_value']) ?>">
            </div>
            <div>
                <label class="nay-label">حد أدنى للطلب</label>
                <input class="nay-input" type="number" step="0.01" id="mkt_coupon_minimum_order_amount" name="coupon_minimum_order_amount" value="<?= mkt_h($form['coupon_minimum_order_amount']) ?>">
            </div>
            <div>
                <label class="nay-label">حد أعلى للخصم</label>
                <input class="nay-input" type="number" step="0.01" name="coupon_maximum_discount_amount" value="<?= mkt_h($form['coupon_maximum_discount_amount']) ?>">
            </div>
            <div>
                <label class="nay-label">صلاحية الكوبون بالأيام</label>
                <input class="nay-input" type="number" id="mkt_coupon_valid_days" name="coupon_valid_days" value="<?= mkt_h($form['coupon_valid_days']) ?>">
            </div>
            <div>
                <label class="nay-label">عدد مرات الاستخدام</label>
                <input class="nay-input" type="number" name="coupon_usage_limit" value="<?= mkt_h($form['coupon_usage_limit']) ?>">
            </div>
            <div>
                <label class="nay-label">عدد النقاط</label>
                <input class="nay-input" type="number" id="mkt_points_amount" name="points_amount" value="<?= mkt_h($form['points_amount']) ?>">
            </div>
        </div>
    </div>

    <div class="nay-card section-card" style="grid-column:1/-1">
        <h3>الإشعار</h3>
        <div class="nay-form-grid">
            <div>
                <label class="nay-label">عنوان الإشعار</label>
                <input class="nay-input" type="text" id="mkt_notification_title" name="notification_title" value="<?= mkt_h($form['notification_title']) ?>" placeholder="مثال: هدية خاصة إلك">
            </div>
            <div>
                <label class="nay-label">إدراج مفتاح داخل العنوان</label>
                <div class="mkt-inline-insert">
                    <select class="nay-input" id="mkt_title_token_select">
                        <option value="">اختر مفتاحًا...</option>
                        <?php foreach ($placeholderMap as $token => $info): ?>
                            <option value="<?= mkt_h($token) ?>"><?= mkt_h($info['label']) ?> — <?= mkt_h($token) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" class="nay-btn" id="mkt_insert_title_token">إدراج</button>
                </div>
            </div>
            <div style="grid-column:1/-1">
                <label class="nay-label">نص الإشعار</label>
                <textarea class="nay-input" id="mkt_notification_message" name="notification_message" rows="4" placeholder="مثال: أهلًا {name}، عندك مكافأة جديدة من حملة {campaign}."><?= mkt_h($form['notification_message']) ?></textarea>
            </div>
            <div style="grid-column:1/-1">
                <label class="nay-label">إدراج مفتاح داخل النص</label>
                <div class="mkt-inline-insert">
                    <select class="nay-input" id="mkt_message_token_select">
                        <option value="">اختر مفتاحًا...</option>
                        <?php foreach ($placeholderMap as $token => $info): ?>
                            <option value="<?= mkt_h($token) ?>"><?= mkt_h($info['label']) ?> — <?= mkt_h($token) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" class="nay-btn" id="mkt_insert_message_token">إدراج</button>
                </div>
            </div>
            <div>
                <label class="nay-label">معاينة العنوان</label>
                <div class="mkt-preview-box" id="mkt_preview_title">—</div>
            </div>
            <div>
                <label class="nay-label">معاينة النص النهائي</label>
                <div class="mkt-preview-box mkt-preview-message" id="mkt_preview_message">—</div>
            </div>
        </div>
    </div>

    <div class="nay-card section-card" style="grid-column:1/-1">
        <h3>التشغيل والجدولة</h3>
        <div class="nay-form-grid">
            <div>
                <label class="nay-label">نوع التشغيل</label>
                <select class="nay-input" id="mkt_run_mode" name="run_mode">
                    <?php foreach (mkt_run_mode_types() as $key => $label): ?>
                        <option value="<?= mkt_h($key) ?>" <?= $form['run_mode'] === $key ? 'selected' : '' ?>><?= mkt_h($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mkt-trigger-only">
                <label class="nay-label">نوع الحدث المحفّز</label>
                <select class="nay-input" id="mkt_trigger_event" name="trigger_event">
                    <?php foreach (mkt_trigger_event_types() as $key => $label): ?>
                        <option value="<?= mkt_h($key) ?>" <?= $form['trigger_event'] === $key ? 'selected' : '' ?>><?= mkt_h($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mkt-schedule-only">
                <label class="nay-label">نوع الجدولة</label>
                <select class="nay-input" id="mkt_schedule_frequency" name="schedule_frequency">
                    <?php foreach (mkt_schedule_frequency_types() as $key => $label): ?>
                        <option value="<?= mkt_h($key) ?>" <?= $form['schedule_frequency'] === $key ? 'selected' : '' ?>><?= mkt_h($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mkt-schedule-only mkt-schedule-hours">
                <label class="nay-label">كل كم ساعة؟</label>
                <input class="nay-input" type="number" min="1" name="schedule_every_hours" value="<?= mkt_h($form['schedule_every_hours']) ?>" placeholder="مثال: 6">
            </div>
            <div class="mkt-schedule-only mkt-schedule-weekly">
                <label class="nay-label">يوم التشغيل الأسبوعي</label>
                <select class="nay-input" name="schedule_weekday">
                    <?php foreach (mkt_schedule_weekday_types() as $key => $label): ?>
                        <option value="<?= mkt_h($key) ?>" <?= (string)$form['schedule_weekday'] === (string)$key ? 'selected' : '' ?>><?= mkt_h($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="nay-label">السماح بتكرار نفس الحملة</label>
                <label class="nay-checkbox"><input type="checkbox" name="allow_repeat" value="1" <?= !empty($form['allow_repeat']) ? 'checked' : '' ?>> <span>السماح بإعادة المكافأة لاحقًا</span></label>
            </div>
            <div>
                <label class="nay-label">إعادة التنفيذ بعد كم يوم</label>
                <input class="nay-input" type="number" name="repeat_after_days" value="<?= mkt_h($form['repeat_after_days']) ?>">
            </div>
            <div>
                <label class="nay-label">فترة التهدئة بالأيام</label>
                <input class="nay-input" type="number" name="cooldown_days" value="<?= mkt_h($form['cooldown_days']) ?>" placeholder="0 لتعطيلها">
            </div>
            <div>
                <label class="nay-label">نطاق فترة التهدئة</label>
                <select class="nay-input" name="cooldown_scope">
                    <option value="same_campaign" <?= $form['cooldown_scope'] === 'same_campaign' ? 'selected' : '' ?>>لنفس الحملة فقط</option>
                    <option value="same_reward_type" <?= $form['cooldown_scope'] === 'same_reward_type' ? 'selected' : '' ?>>لنفس نوع المكافأة</option>
                    <option value="any_campaign" <?= $form['cooldown_scope'] === 'any_campaign' ? 'selected' : '' ?>>أي حملة تسويقية</option>
                </select>
            </div>
            <div>
                <label class="nay-label">تاريخ البداية</label>
                <input class="nay-input" type="datetime-local" name="starts_at" value="<?= mkt_h(mkt_mysql_to_local_input((string)$form['starts_at'])) ?>">
            </div>
            <div>
                <label class="nay-label">تاريخ النهاية</label>
                <input class="nay-input" type="datetime-local" name="ends_at" value="<?= mkt_h(mkt_mysql_to_local_input((string)$form['ends_at'])) ?>">
            </div>
            <div class="mkt-schedule-only">
                <label class="nay-label">موعد التشغيل القادم</label>
                <div class="mkt-preview-box"><?= mkt_h($form['next_run_at'] ?: 'سيُحتسب تلقائيًا بعد الحفظ') ?></div>
            </div>
        </div>
        <div class="nay-help" style="margin-top:10px">عند اختيار <strong>مجدول</strong> تقدر تشغّل الحملات تلقائيًا عبر ملف <code>cron.php</code> من cPanel Cron Jobs. وعند اختيار <strong>عند حدث</strong> راح تنطلق الحملة تلقائيًا لما يصير الحدث المرتبط داخل النظام.</div>
    </div>

    <div style="grid-column:1/-1;display:flex;gap:10px;justify-content:flex-end">
        <button class="nay-btn primary" type="submit" <?= !$stage2Ready ? 'disabled' : '' ?>><?= mkt_h($form_submit_label) ?></button>
        <a class="nay-btn" href="<?= mkt_h($form_back_href) ?>"><?= mkt_h($form_back_label) ?></a>
    </div>
</form>

<style>
.mkt-preview-box{min-height:58px;padding:12px 14px;border:1px solid #dbe3ef;border-radius:14px;background:#f8fafc;color:#0f172a;line-height:1.8;white-space:pre-wrap}
.mkt-preview-message{min-height:92px}
.mkt-inline-insert{display:flex;gap:10px;align-items:center}
.mkt-inline-insert .nay-input{flex:1}
.mkt-schedule-only,.mkt-schedule-hours,.mkt-schedule-weekly,.mkt-trigger-only{display:none}
@media(max-width:768px){.mkt-inline-insert{flex-direction:column;align-items:stretch}}
</style>

<script>
(function(){
    const form = document.querySelector('form[data-mkt-form="1"]');
    if (!form) return;

    const titleInput = document.getElementById('mkt_notification_title');
    const messageInput = document.getElementById('mkt_notification_message');
    const previewTitle = document.getElementById('mkt_preview_title');
    const previewMessage = document.getElementById('mkt_preview_message');
    const titleSelect = document.getElementById('mkt_title_token_select');
    const messageSelect = document.getElementById('mkt_message_token_select');
    const nameInput = document.getElementById('mkt_name');
    const couponTypeInput = document.getElementById('mkt_coupon_discount_type');
    const couponValueInput = document.getElementById('mkt_coupon_discount_value');
    const couponMinOrderInput = document.getElementById('mkt_coupon_minimum_order_amount');
    const couponValidDaysInput = document.getElementById('mkt_coupon_valid_days');
    const pointsAmountInput = document.getElementById('mkt_points_amount');
    const tierSelect = document.getElementById('mkt_tier_id');
    const minSpentInput = document.getElementById('mkt_min_total_spent');
    const runModeInput = document.getElementById('mkt_run_mode');
    const triggerEventInput = document.getElementById('mkt_trigger_event');
    const scheduleFrequencyInput = document.getElementById('mkt_schedule_frequency');

    function insertToken(input, token){
        if (!input || !token) return;
        const start = input.selectionStart || 0;
        const end = input.selectionEnd || 0;
        const value = input.value || '';
        input.value = value.substring(0, start) + token + value.substring(end);
        const pos = start + token.length;
        input.focus();
        input.setSelectionRange(pos, pos);
        renderPreview();
    }


    function toggleScheduleFields(){
        const runValue = runModeInput ? String(runModeInput.value || '').toLowerCase() : '';
        const isScheduled = ['scheduled', 'schedule', 'auto', 'cron'].indexOf(runValue) !== -1;
        const isTriggered = runValue === 'triggered';
        const freq = scheduleFrequencyInput ? String(scheduleFrequencyInput.value || '').toLowerCase() : 'daily';

        document.querySelectorAll('.mkt-schedule-only').forEach(function(el){
            el.style.display = isScheduled ? '' : 'none';
        });
        document.querySelectorAll('.mkt-trigger-only').forEach(function(el){
            el.style.display = isTriggered ? '' : 'none';
        });
        document.querySelectorAll('.mkt-schedule-hours').forEach(function(el){
            el.style.display = isScheduled && ['every_x_hours', 'hours', 'hourly'].indexOf(freq) !== -1 ? '' : 'none';
        });
        document.querySelectorAll('.mkt-schedule-weekly').forEach(function(el){
            el.style.display = isScheduled && freq === 'weekly' ? '' : 'none';
        });
    }
    window.mktToggleScheduleFields = toggleScheduleFields;

    function renderPreview(){
        const today = new Date();
        const yyyy = today.getFullYear();
        const mm = String(today.getMonth() + 1).padStart(2, '0');
        const dd = String(today.getDate()).padStart(2, '0');
        const codeValue = couponTypeInput && couponTypeInput.value === 'fixed' ? '5000' : '10';
        const typeLabel = couponTypeInput && couponTypeInput.value === 'fixed' ? 'مبلغ ثابت' : 'نسبة مئوية';
        const validDays = Math.max(1, parseInt(couponValidDaysInput && couponValidDaysInput.value ? couponValidDaysInput.value : '7', 10) || 7);
        const expiryDate = new Date(today.getTime());
        expiryDate.setDate(expiryDate.getDate() + validDays);
        const expiry = [expiryDate.getFullYear(), String(expiryDate.getMonth() + 1).padStart(2, '0'), String(expiryDate.getDate()).padStart(2, '0')].join('-');
        const tierText = tierSelect && tierSelect.selectedIndex > 0 ? tierSelect.options[tierSelect.selectedIndex].text : 'Gold';
        const spentText = (minSpentInput && minSpentInput.value ? minSpentInput.value : '250000') + ' د.ع';

        let replacements = {
            '{name}': nameInput && nameInput.value ? nameInput.value : 'عميلنا العزيز',
            '{customer_name}': nameInput && nameInput.value ? nameInput.value : 'عميلنا العزيز',
            '{phone}': '07700000000',
            '{customer_phone}': '07700000000',
            '{campaign}': nameInput && nameInput.value ? nameInput.value : 'حملة تسويقية',
            '{campaign_name}': nameInput && nameInput.value ? nameInput.value : 'حملة تسويقية',
            '{date}': `${yyyy}-${mm}-${dd}`,
            '{today_date}': `${yyyy}-${mm}-${dd}`,
            '{code}': 'MKT-DEMO-01',
            '{coupon_code}': 'MKT-DEMO-01',
            '{value}': couponValueInput && couponValueInput.value ? couponValueInput.value : codeValue,
            '{coupon_value}': couponValueInput && couponValueInput.value ? couponValueInput.value : codeValue,
            '{type}': typeLabel,
            '{coupon_type}': typeLabel,
            '{min}': couponMinOrderInput && couponMinOrderInput.value ? couponMinOrderInput.value + ' د.ع' : '0 د.ع',
            '{coupon_min_order}': couponMinOrderInput && couponMinOrderInput.value ? couponMinOrderInput.value + ' د.ع' : '0 د.ع',
            '{expiry}': expiry,
            '{coupon_expiry_date}': expiry,
            '{points}': pointsAmountInput && pointsAmountInput.value ? pointsAmountInput.value : '200',
            '{points_amount}': pointsAmountInput && pointsAmountInput.value ? pointsAmountInput.value : '200',
            '{balance}': '1200',
            '{points_balance}': '1200',
            '{tier}': tierText,
            '{tier_name}': tierText,
            '{last_order}': '2026-04-01',
            '{last_order_date}': '2026-04-01',
            '{orders}': '3',
            '{total_orders}': '3',
            '{spent}': spentText,
            '{total_spent}': spentText,
        };

        const applyTokens = (text) => {
            let out = text || '';
            Object.keys(replacements).forEach((token) => {
                out = out.split(token).join(replacements[token]);
            });
            return out.trim();
        };

        previewTitle.textContent = applyTokens(titleInput ? titleInput.value : '') || '—';
        previewMessage.textContent = applyTokens(messageInput ? messageInput.value : '') || '—';
    }

    document.getElementById('mkt_insert_title_token')?.addEventListener('click', function(){
        if (!titleSelect || !titleSelect.value) return;
        insertToken(titleInput, titleSelect.value);
        titleSelect.value = '';
    });

    document.getElementById('mkt_insert_message_token')?.addEventListener('click', function(){
        if (!messageSelect || !messageSelect.value) return;
        insertToken(messageInput, messageSelect.value);
        messageSelect.value = '';
    });

    [titleInput, messageInput, nameInput, couponTypeInput, couponValueInput, couponMinOrderInput, couponValidDaysInput, pointsAmountInput, tierSelect, minSpentInput, runModeInput, scheduleFrequencyInput].forEach(function(el){
        if (!el) return;
        el.addEventListener('input', renderPreview);
        el.addEventListener('change', renderPreview);
    });
    if (runModeInput) { runModeInput.addEventListener('change', toggleScheduleFields); runModeInput.addEventListener('input', toggleScheduleFields); }
    if (scheduleFrequencyInput) { scheduleFrequencyInput.addEventListener('change', toggleScheduleFields); scheduleFrequencyInput.addEventListener('input', toggleScheduleFields); }

    toggleScheduleFields();
    setTimeout(toggleScheduleFields, 50);
    renderPreview();
})();
</script>
