<?php
require_once __DIR__ . '/bootstrap.php';
$pageTitle = 'Edit Notification';
include 'partials/head.php';
?>

<div class="min-h-screen pb-20 lg:pb-8">
    <!-- Header -->
    <header class="sticky top-0 bg-white/80 backdrop-blur border-b border-slate-200 px-4 py-3 z-10">
        <div class="max-w-2xl mx-auto flex items-center justify-between">
            <button onclick="goBack()" class="w-8 h-8 rounded-lg hover:bg-slate-100 flex items-center justify-center text-slate-500">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
            <h1 class="text-sm font-semibold" id="page-title">New Notification</h1>
            <button onclick="save()" class="text-sm font-medium text-indigo-500 hover:text-indigo-600">Save</button>
        </div>
    </header>

    <main class="max-w-2xl mx-auto p-4 space-y-4">
        <!-- Title -->
        <div class="bg-white rounded-xl border border-slate-200 p-4">
            <label class="text-xs font-medium text-slate-500 mb-1.5 block">Title</label>
            <input type="text" id="title" placeholder="e.g., Pay Rent" class="w-full h-9 px-3 bg-slate-100 border-0 rounded-lg text-sm focus:bg-white focus:ring-2 focus:ring-indigo-500/20">
        </div>

        <!-- Message -->
        <div class="bg-white rounded-xl border border-slate-200 p-4">
            <div class="flex items-center justify-between mb-1.5">
                <label class="text-xs font-medium text-slate-500">Message</label>
                <span class="text-[10px] text-slate-400"><span id="char-count">0</span>/4096</span>
            </div>
            <textarea id="message" rows="3" placeholder="Your notification message..." class="w-full px-3 py-2 bg-slate-100 border-0 rounded-lg text-sm resize-none focus:bg-white focus:ring-2 focus:ring-indigo-500/20"></textarea>
            <div class="flex items-center justify-between mt-2">
                <div class="flex gap-1.5">
                    <button type="button" onclick="insertFormat('*', '*')" class="h-7 w-7 bg-slate-100 hover:bg-slate-200 rounded text-xs font-bold transition-colors">B</button>
                    <button type="button" onclick="insertFormat('_', '_')" class="h-7 w-7 bg-slate-100 hover:bg-slate-200 rounded text-xs italic transition-colors">I</button>
                    <button type="button" onclick="insertFormat('~', '~')" class="h-7 w-7 bg-slate-100 hover:bg-slate-200 rounded text-xs line-through transition-colors">S</button>
                </div>
                <button type="button" onclick="testMainMessage()" id="test-main-btn" class="h-7 px-3 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded text-xs font-medium transition-colors flex items-center gap-1">
                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
                    Test notification
                </button>
            </div>
        </div>

        <!-- Image Upload -->
        <div class="bg-white rounded-xl border border-slate-200 p-4">
            <label class="text-xs font-medium text-slate-500 mb-1.5 block">Image (optional)</label>
            <div id="image-upload-area">
                <!-- Empty state -->
                <div id="image-empty" class="border-2 border-dashed border-slate-200 rounded-lg p-6 text-center hover:border-slate-300 transition-colors cursor-pointer" onclick="document.getElementById('image-input').click()">
                    <svg class="w-8 h-8 text-slate-300 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                    </svg>
                    <p class="text-xs text-slate-400 mb-1">Click to upload an image</p>
                    <p class="text-[10px] text-slate-300">PNG, JPG up to 5MB</p>
                </div>
                <!-- Preview state -->
                <div id="image-preview" class="hidden">
                    <div class="relative rounded-lg overflow-hidden bg-slate-100">
                        <img id="image-preview-img" src="" alt="Preview" class="w-full max-h-48 object-contain">
                        <button type="button" onclick="removeImage()" class="absolute top-2 right-2 w-7 h-7 bg-black/50 hover:bg-black/70 text-white rounded-full flex items-center justify-center transition-colors">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                        </button>
                    </div>
                    <p id="image-filename" class="text-xs text-slate-400 mt-2 truncate"></p>
                </div>
                <!-- Uploading state -->
                <div id="image-uploading" class="hidden border-2 border-dashed border-indigo-300 rounded-lg p-6 text-center bg-indigo-50">
                    <div class="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin mx-auto mb-2"></div>
                    <p class="text-xs text-indigo-600">Uploading...</p>
                </div>
            </div>
            <input type="file" id="image-input" accept="image/png,image/jpeg,image/jpg,image/gif,image/webp" class="hidden" onchange="handleImageSelect(event)">
        </div>

        <!-- Context/Notes -->
        <div class="bg-white rounded-xl border border-slate-200 p-4">
            <label class="text-xs font-medium text-slate-500 mb-1.5 block">Extra context</label>
            <textarea id="context" rows="2" placeholder="Extra context (not sent to Telegram)..." class="w-full px-3 py-2 bg-slate-100 border-0 rounded-lg text-sm resize-none focus:bg-white focus:ring-2 focus:ring-indigo-500/20"></textarea>
            <p class="text-[10px] text-slate-400 mt-1.5">Extra context for future AI agents and for you; never sent to Telegram.</p>
        </div>

        <!-- Schedule -->
        <div class="bg-white rounded-xl border border-slate-200 p-4">
            <label class="text-xs font-medium text-slate-500 mb-3 block">Schedule</label>

            <!-- Toggle -->
            <div class="flex bg-slate-100 rounded-lg p-1 mb-4">
                <button type="button" id="tab-dates" onclick="setScheduleType('dates')" class="flex-1 h-7 rounded-md text-xs font-medium transition-colors">Specific Dates</button>
                <button type="button" id="tab-recurrence" onclick="setScheduleType('recurrence')" class="flex-1 h-7 rounded-md text-xs font-medium transition-colors">Recurring</button>
            </div>

            <!-- Dates Section -->
            <div id="section-dates" class="space-y-3">
                <div class="flex items-start gap-3 p-3 bg-slate-50 rounded-lg cursor-pointer" onclick="document.getElementById('yearly-repeat').click()">
                    <button type="button" id="yearly-toggle" onclick="event.stopPropagation(); document.getElementById('yearly-repeat').click()"
                        class="w-9 h-5 rounded-full bg-slate-300 relative transition-colors flex-shrink-0 mt-0.5">
                        <span class="absolute left-0.5 top-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform"></span>
                    </button>
                    <input type="checkbox" id="yearly-repeat" onchange="toggleYearlyRepeat()" class="hidden">
                    <div>
                        <span class="text-xs font-medium block">Repeat every year</span>
                        <span class="text-[10px] text-slate-400">These dates will trigger annually</span>
                    </div>
                </div>
                <div id="dates-list" class="space-y-2"></div>
                <button type="button" onclick="addDate()" class="w-full h-10 border-2 border-dashed border-slate-200 rounded-lg text-xs text-slate-400 hover:border-slate-300 hover:text-slate-500 transition-colors">+ Add Date</button>
            </div>

            <!-- Recurrence Section -->
            <div id="section-recurrence" class="hidden space-y-4">
                <div>
                    <label class="text-xs font-medium text-slate-500 mb-1.5 block">Repeat Type</label>
                    <select id="recurrence-type" onchange="updateRecurrenceUI()" class="w-full h-9 px-3 bg-slate-100 border-0 rounded-lg text-sm">
                        <option value="specific_months">Specific Months</option>
                        <option value="monthly_date">Monthly on Date</option>
                        <option value="payday">On Pay Days</option>
                        <option value="monthly_weekday">Monthly on Weekday</option>
                        <option value="weekly">Weekly</option>
                        <option value="daily">Daily</option>
                    </select>
                </div>

                <div id="recurrence-months">
                    <label class="text-xs font-medium text-slate-500 mb-1.5 block">Select Months</label>
                    <div class="grid grid-cols-6 gap-1.5">
                        <button type="button" onclick="toggleMonth(1)" data-month="1" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">Jan</button>
                        <button type="button" onclick="toggleMonth(2)" data-month="2" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">Feb</button>
                        <button type="button" onclick="toggleMonth(3)" data-month="3" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">Mar</button>
                        <button type="button" onclick="toggleMonth(4)" data-month="4" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">Apr</button>
                        <button type="button" onclick="toggleMonth(5)" data-month="5" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">May</button>
                        <button type="button" onclick="toggleMonth(6)" data-month="6" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">Jun</button>
                        <button type="button" onclick="toggleMonth(7)" data-month="7" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">Jul</button>
                        <button type="button" onclick="toggleMonth(8)" data-month="8" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">Aug</button>
                        <button type="button" onclick="toggleMonth(9)" data-month="9" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">Sep</button>
                        <button type="button" onclick="toggleMonth(10)" data-month="10" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">Oct</button>
                        <button type="button" onclick="toggleMonth(11)" data-month="11" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">Nov</button>
                        <button type="button" onclick="toggleMonth(12)" data-month="12" class="month-btn h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">Dec</button>
                    </div>
                </div>

                <div id="recurrence-weekdays" class="hidden">
                    <label class="text-xs font-medium text-slate-500 mb-1.5 block">Select Days</label>
                    <div class="flex gap-1.5">
                        <button type="button" onclick="toggleWeekday(0)" data-weekday="0" class="weekday-btn flex-1 h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">S</button>
                        <button type="button" onclick="toggleWeekday(1)" data-weekday="1" class="weekday-btn flex-1 h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">M</button>
                        <button type="button" onclick="toggleWeekday(2)" data-weekday="2" class="weekday-btn flex-1 h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">T</button>
                        <button type="button" onclick="toggleWeekday(3)" data-weekday="3" class="weekday-btn flex-1 h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">W</button>
                        <button type="button" onclick="toggleWeekday(4)" data-weekday="4" class="weekday-btn flex-1 h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">T</button>
                        <button type="button" onclick="toggleWeekday(5)" data-weekday="5" class="weekday-btn flex-1 h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">F</button>
                        <button type="button" onclick="toggleWeekday(6)" data-weekday="6" class="weekday-btn flex-1 h-8 rounded-lg text-[11px] font-medium bg-slate-100 hover:bg-slate-200 transition-colors">S</button>
                    </div>
                </div>

                <div id="recurrence-monthly-weekday" class="hidden space-y-3">
                    <div>
                        <label class="text-xs font-medium text-slate-500 mb-1.5 block">Select Week & Day</label>
                        <div class="grid grid-cols-2 gap-3">
                            <select id="week-number" onchange="updatePreview()" class="w-full h-9 px-3 bg-slate-100 border-0 rounded-lg text-sm">
                                <option value="1">First</option>
                                <option value="2">Second</option>
                                <option value="3">Third</option>
                                <option value="4">Fourth</option>
                                <option value="last">Last</option>
                            </select>
                            <select id="weekday-select" onchange="updatePreview()" class="w-full h-9 px-3 bg-slate-100 border-0 rounded-lg text-sm">
                                <option value="0">Sunday</option>
                                <option value="1">Monday</option>
                                <option value="2">Tuesday</option>
                                <option value="3">Wednesday</option>
                                <option value="4">Thursday</option>
                                <option value="5">Friday</option>
                                <option value="6">Saturday</option>
                            </select>
                        </div>
                        <p class="text-[10px] text-slate-400 mt-1.5">e.g., "Second Tuesday" of every month</p>
                    </div>
                    <div>
                        <label class="text-xs font-medium text-slate-500 mb-1.5 block">Time</label>
                        <input type="time" id="monthly-weekday-time" value="09:00" onchange="updatePreview()" class="w-full h-9 px-3 bg-slate-100 border-0 rounded-lg text-sm">
                    </div>
                </div>

                <div id="recurrence-payday" class="hidden space-y-3">
                    <div>
                        <label class="text-xs font-medium text-slate-500 mb-1.5 block">Payday</label>
                        <div class="grid grid-cols-2 gap-3">
                            <select id="payday-day" onchange="updatePreview()" class="w-full h-9 px-3 bg-slate-100 border-0 rounded-lg text-sm">
                                <option value="15">15th</option>
                                <option value="30">30th</option>
                            </select>
                            <input type="time" id="payday-time" value="09:00" onchange="updatePreview()" class="w-full h-9 px-3 bg-slate-100 border-0 rounded-lg text-sm">
                        </div>
                        <p class="text-[10px] text-slate-400 mt-1.5">If the date lands on a weekend, it moves to the previous weekday.</p>
                    </div>
                </div>

                <div id="recurrence-day" class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="text-xs font-medium text-slate-500 mb-1.5 block">Day of Month</label>
                        <select id="day-of-month" class="w-full h-9 px-3 bg-slate-100 border-0 rounded-lg text-sm"></select>
                    </div>
                    <div>
                        <label class="text-xs font-medium text-slate-500 mb-1.5 block">Time</label>
                        <input type="time" id="recurrence-time" value="09:00" class="w-full h-9 px-3 bg-slate-100 border-0 rounded-lg text-sm">
                    </div>
                </div>

                <div id="recurrence-interval" class="hidden">
                    <label class="text-xs font-medium text-slate-500 mb-1.5 block">Every X Days</label>
                    <input type="number" id="interval-days" min="1" value="1" class="w-full h-9 px-3 bg-slate-100 border-0 rounded-lg text-sm">
                </div>

                <div class="p-3 bg-slate-50 rounded-lg">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-[10px] text-slate-400">Next 4 Occurrences</span>
                        <button type="button" onclick="updatePreview()" class="text-[10px] text-indigo-500">Refresh</button>
                    </div>
                    <div id="preview-dates" class="space-y-1 text-xs text-slate-600"></div>
                </div>
            </div>
        </div>

        <!-- Follow-ups -->
        <div class="bg-white rounded-xl border border-slate-200 p-4">
            <div class="flex items-center justify-between mb-3">
                <label class="text-xs font-medium text-slate-500">Follow-ups</label>
                <span class="text-[10px] px-1.5 py-0.5 bg-amber-100 text-amber-600 rounded font-medium">if not confirmed</span>
            </div>
            <div id="subsequents-list" class="space-y-2 mb-3"></div>
            <button type="button" onclick="addSubsequent()" class="w-full h-10 border-2 border-dashed border-slate-200 rounded-lg text-xs text-slate-400 hover:border-slate-300 hover:text-slate-500 transition-colors">+ Add Follow-up</button>
        </div>

        <!-- Category -->
        <div class="bg-white rounded-xl border border-slate-200 p-4">
            <label class="text-xs font-medium text-slate-500 mb-1.5 block">Category</label>
            <input type="hidden" id="category" value="">
            <div class="relative" id="category-dropdown">
                <button type="button" onclick="toggleCategoryDropdown()" class="w-full h-9 px-3 bg-white border border-slate-200 rounded-lg text-sm flex items-center justify-between hover:bg-slate-50 transition-colors">
                    <span id="category-display" class="flex items-center gap-2 text-slate-500">No Category</span>
                    <svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                </button>
                <div id="category-options" class="hidden absolute top-full left-0 right-0 mt-1 bg-white rounded-lg shadow-lg border border-slate-200 py-1 z-30 max-h-48 overflow-y-auto">
                    <!-- Populated by JS -->
                </div>
            </div>
        </div>

    </main>

    <!-- Bottom Button -->
    <div class="fixed bottom-0 left-0 right-0 p-4 bg-white border-t border-slate-200 lg:relative lg:max-w-2xl lg:mx-auto lg:border-0 lg:bg-transparent">
        <button onclick="save()" class="w-full h-10 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm font-medium transition-colors">Save Notification</button>
    </div>
</div>

<!-- Date Modal -->
<div id="date-modal" class="hidden fixed inset-0 z-50">
    <div class="absolute inset-0 bg-black/50" onclick="closeDateModal()"></div>
    <div class="absolute bottom-0 left-0 right-0 lg:bottom-auto lg:top-1/2 lg:left-1/2 lg:-translate-x-1/2 lg:-translate-y-1/2 lg:max-w-sm lg:w-full bg-white rounded-t-2xl lg:rounded-2xl p-5">
        <h3 class="text-base font-semibold mb-4">Select Date & Time</h3>
        <div class="space-y-3">
            <input type="date" id="modal-date" class="w-full h-10 px-3 bg-slate-100 border-0 rounded-lg text-sm">
            <input type="time" id="modal-time" value="09:00" class="w-full h-10 px-3 bg-slate-100 border-0 rounded-lg text-sm">
        </div>
        <div class="flex gap-2 mt-5">
            <button onclick="closeDateModal()" class="flex-1 h-9 bg-slate-100 hover:bg-slate-200 rounded-lg text-sm font-medium transition-colors">Cancel</button>
            <button onclick="confirmDate()" class="flex-1 h-9 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm font-medium transition-colors">Add</button>
        </div>
    </div>
</div>

<!-- Subsequent Modal -->
<div id="subsequent-modal" class="hidden fixed inset-0 z-50">
    <div class="absolute inset-0 bg-black/50" onclick="closeSubsequentModal()"></div>
    <div class="absolute bottom-0 left-0 right-0 lg:bottom-auto lg:top-1/2 lg:left-1/2 lg:-translate-x-1/2 lg:-translate-y-1/2 lg:max-w-lg lg:w-full bg-white rounded-t-2xl lg:rounded-2xl p-6">
        <h3 id="sub-modal-title" class="text-lg font-semibold mb-5">Add Follow-up</h3>
        <div class="space-y-5">
            <div>
                <label class="text-xs font-medium text-slate-500 mb-2 block">Send after the main notification</label>
                <div class="grid grid-cols-3 gap-3">
                    <div>
                        <input type="number" id="sub-days" min="0" value="1" class="w-full h-10 px-3 bg-slate-100 border-0 rounded-lg text-sm text-center">
                        <span class="text-xs text-slate-400 block text-center mt-1.5">days</span>
                    </div>
                    <div>
                        <input type="number" id="sub-hours" min="0" value="0" class="w-full h-10 px-3 bg-slate-100 border-0 rounded-lg text-sm text-center">
                        <span class="text-xs text-slate-400 block text-center mt-1.5">hours</span>
                    </div>
                    <div>
                        <input type="number" id="sub-minutes" min="0" value="0" class="w-full h-10 px-3 bg-slate-100 border-0 rounded-lg text-sm text-center">
                        <span class="text-xs text-slate-400 block text-center mt-1.5">minutes</span>
                    </div>
                </div>
            </div>
            <div>
                <div class="flex items-center justify-between mb-2">
                    <label class="text-xs font-medium text-slate-500">Follow-up Message</label>
                    <span class="text-[10px] text-slate-400"><span id="sub-char-count">0</span>/4096</span>
                </div>
                <textarea id="sub-message" rows="5" placeholder="Enter your follow-up message here..." class="w-full px-3 py-3 bg-slate-100 border-0 rounded-lg text-sm resize-none focus:bg-white focus:ring-2 focus:ring-indigo-500/20"></textarea>
                <div class="flex items-center justify-between mt-2">
                    <div class="flex gap-1.5">
                        <button type="button" onclick="insertSubFormat('*', '*')" class="h-7 w-7 bg-slate-100 hover:bg-slate-200 rounded text-xs font-bold transition-colors">B</button>
                        <button type="button" onclick="insertSubFormat('_', '_')" class="h-7 w-7 bg-slate-100 hover:bg-slate-200 rounded text-xs italic transition-colors">I</button>
                        <button type="button" onclick="insertSubFormat('~', '~')" class="h-7 w-7 bg-slate-100 hover:bg-slate-200 rounded text-xs line-through transition-colors">S</button>
                    </div>
                    <button type="button" onclick="testFollowupMessage()" id="test-sub-btn" class="h-7 px-3 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded text-xs font-medium transition-colors flex items-center gap-1">
                        <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
                        Test notification
                    </button>
                </div>
            </div>
            <div>
                <label class="text-xs font-medium text-slate-500 mb-1.5 block">Image (optional)</label>
                <div id="sub-image-upload-area">
                    <div id="sub-image-empty" class="border-2 border-dashed border-slate-200 rounded-lg p-4 text-center hover:border-slate-300 transition-colors cursor-pointer" onclick="document.getElementById('sub-image-input').click()">
                        <svg class="w-7 h-7 text-slate-300 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                        </svg>
                        <p class="text-[11px] text-slate-400 mb-1">Click to upload an image</p>
                        <p class="text-[10px] text-slate-300">PNG, JPG up to 5MB</p>
                    </div>
                    <div id="sub-image-preview" class="hidden">
                        <div class="relative rounded-lg overflow-hidden bg-slate-100">
                            <img id="sub-image-preview-img" src="" alt="Preview" class="w-full max-h-40 object-contain">
                            <button type="button" onclick="removeSubImage()" class="absolute top-2 right-2 w-6 h-6 bg-black/50 hover:bg-black/70 text-white rounded-full flex items-center justify-center transition-colors">
                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                            </button>
                        </div>
                        <p id="sub-image-filename" class="text-xs text-slate-400 mt-2 truncate"></p>
                    </div>
                    <div id="sub-image-uploading" class="hidden border-2 border-dashed border-indigo-300 rounded-lg p-4 text-center bg-indigo-50">
                        <div class="w-7 h-7 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin mx-auto mb-2"></div>
                        <p class="text-xs text-indigo-600">Uploading...</p>
                    </div>
                </div>
                <input type="file" id="sub-image-input" accept="image/png,image/jpeg,image/jpg,image/gif,image/webp" class="hidden" onchange="handleSubImageSelect(event)">
            </div>
        </div>
        <div class="flex gap-3 mt-6">
            <button type="button" onclick="closeSubsequentModal()" class="flex-1 h-10 bg-slate-100 hover:bg-slate-200 rounded-lg text-sm font-medium transition-colors">Cancel</button>
            <button type="button" id="sub-confirm-btn" onclick="confirmSubsequent()" class="flex-1 h-10 bg-indigo-500 hover:bg-indigo-600 text-white rounded-lg text-sm font-medium transition-colors">Add Follow-up</button>
        </div>
    </div>
</div>

<?php include 'partials/scripts.php'; ?>
<script>
    let editId = null;
    let scheduleType = 'dates';
    let dates = [];
    let yearlyRepeat = false;
    let selectedMonths = [];
    let selectedWeekdays = [];
    let subsequents = [];
    let categories = [];
    let imagePath = null; // Stores the uploaded image path
    let subImagePath = null; // Stores the follow-up image path
    let editingSubsequentIndex = null; // null = adding new, number = editing existing

    const titleEl = document.getElementById('title');
    const messageEl = document.getElementById('message');
    const contextEl = document.getElementById('context');
    const categoryEl = document.getElementById('category');
    const appTimezone = window.__APP_CONFIG__?.timezone || 'America/Mexico_City';

    async function init() {
        // Extract ID from URL path: /notifier/notifications/edit/:id/
        const pathMatch = window.location.pathname.match(/\/notifications\/edit\/(\d+)/);
        editId = pathMatch ? pathMatch[1] : null;

        // Load categories from API
        try {
            categories = await Api.getCategories();
            renderCategoryDropdown();
        } catch (error) {
            Toast.error('Error', 'Failed to load categories');
        }

        document.getElementById('day-of-month').innerHTML = [...Array(31)].map((_, i) => `<option value="${i + 1}">${i + 1}</option>`).join('');

        if (editId) {
            await loadNotification(editId);
        } else {
            setScheduleType('dates');
            updatePreview();
        }

        // Close dropdown when clicking outside
        document.addEventListener('click', (e) => {
            if (!e.target.closest('#category-dropdown')) {
                document.getElementById('category-options').classList.add('hidden');
            }
        });
    }

    function renderCategoryDropdown() {
        const options = document.getElementById('category-options');
        options.innerHTML = `
            <button type="button" class="w-full px-3 py-2 text-left text-sm hover:bg-slate-50 flex items-center gap-2" onclick="selectCategory('', 'No Category', '')">
                <span class="w-5 h-5 rounded bg-slate-200 flex items-center justify-center text-slate-400 text-xs">-</span>
                <span>No Category</span>
            </button>
        ` + categories.map(c => `
            <button type="button" class="w-full px-3 py-2 text-left text-sm hover:bg-slate-50 flex items-center gap-2" onclick="selectCategory('${c.id}', '${escapeHtml(c.name)}', '${c.icon || 'bi-tag'}', '${c.color}')">
                <span class="w-5 h-5 rounded flex items-center justify-center text-xs" style="background-color: ${c.color}20; color: ${c.color}">
                    <i class="${c.icon || 'bi-tag'}"></i>
                </span>
                <span>${escapeHtml(c.name)}</span>
            </button>
        `).join('');
    }

    function toggleCategoryDropdown() {
        document.getElementById('category-options').classList.toggle('hidden');
    }

    function normalizeCategoryIcon(icon) {
        if (!icon || !/^bi-[a-z0-9-]+$/i.test(icon)) return 'bi-tag';
        return icon;
    }

    function selectCategory(id, name, icon, color) {
        categoryEl.value = id;
        const display = document.getElementById('category-display');
        const safeIcon = normalizeCategoryIcon(icon);
        if (id) {
            display.innerHTML = `<span class="w-5 h-5 rounded flex items-center justify-center text-xs" style="background-color: ${color}20; color: ${color}"><i class="${safeIcon}"></i></span><span class="text-slate-900">${escapeHtml(name)}</span>`;
        } else {
            display.innerHTML = '<span class="text-slate-500">No Category</span>';
        }
        document.getElementById('category-options').classList.add('hidden');
    }

    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }

    function normalizeUtcString(value) {
        if (!value) return '';
        if (value.includes('T')) return value;
        return value.replace(' ', 'T') + 'Z';
    }

    function formatUtcToTimezone(value, timezone) {
        const iso = normalizeUtcString(value);
        const dt = new Date(iso);
        if (Number.isNaN(dt.getTime())) return value;
        const parts = new Intl.DateTimeFormat('en-US', {
            timeZone: timezone,
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        }).formatToParts(dt);
        const map = {};
        parts.forEach(part => {
            if (part.type !== 'literal') map[part.type] = part.value;
        });
        if (!map.year || !map.month || !map.day || !map.hour || !map.minute) return value;
        return `${map.year}-${map.month}-${map.day} ${map.hour}:${map.minute}`;
    }

    // Local formatOffset function (in case DateUtils isn't loaded yet)
    function formatOffset(days, hours, minutes) {
        const parts = [];
        if (days > 0) parts.push(`${days}d`);
        if (hours > 0) parts.push(`${hours}h`);
        if (minutes > 0) parts.push(`${minutes}m`);
        return '+' + (parts.length ? parts.join(' ') : '0m');
    }

    async function loadNotification(id) {
        try {
            const n = await Api.getNotification(id);
            if (!n) { window.location.href = '/notifier/notifications/'; return; }

            document.getElementById('page-title').textContent = 'Edit Notification';
            titleEl.value = n.title || '';
            messageEl.value = n.message || '';
            contextEl.value = n.context || '';

            // Load image if exists
            if (n.image_path) {
                imagePath = n.image_path;
                showImagePreview(`/notifier/uploads/${n.image_path}`, n.image_path.split('/').pop());
            }

            // Set category with display update
            if (n.category_id) {
                const cat = categories.find(c => c.id === n.category_id);
                if (cat) {
                    selectCategory(cat.id, cat.name, cat.icon || 'bi-tag', cat.color);
                }
            }

            scheduleType = n.schedule_type || 'dates';

            // Convert dates from API format (objects with scheduled_at) to strings
            const notificationTimezone = n.timezone || appTimezone;
            dates = (n.dates || []).map(d => {
                const raw = typeof d === 'object' ? d.scheduled_at : d;
                return formatUtcToTimezone(raw, notificationTimezone);
            });

            yearlyRepeat = n.yearly_repeat == 1 || n.yearly_repeat === true;
            document.getElementById('yearly-repeat').checked = yearlyRepeat;
            updateYearlyToggle();

            subsequents = [...(n.subsequents || [])];

            if (n.recurrence) {
                selectedMonths = [...(n.recurrence.months || [])];
                selectedWeekdays = [...(n.recurrence.weekdays || [])];
                const recurrenceType = n.recurrence.type || 'specific_months';
                const isPayday = recurrenceType === 'monthly_date'
                    && n.recurrence.weekend_adjust === 'previous_weekday'
                    && [15, 30].includes(parseInt(n.recurrence.day_of_month));

                document.getElementById('recurrence-type').value = isPayday ? 'payday' : recurrenceType;
                document.getElementById('interval-days').value = n.recurrence.interval_days || 1;

                if (isPayday) {
                    document.getElementById('payday-day').value = n.recurrence.day_of_month || 15;
                    document.getElementById('payday-time').value = n.recurrence.time_of_day || '09:00';
                } else {
                    document.getElementById('day-of-month').value = n.recurrence.day_of_month || 1;
                    document.getElementById('recurrence-time').value = n.recurrence.time_of_day || '09:00';
                }

                // Monthly weekday settings
                if (n.recurrence.week_number) {
                    document.getElementById('week-number').value = n.recurrence.week_number;
                }
                if (n.recurrence.weekday !== undefined) {
                    document.getElementById('weekday-select').value = n.recurrence.weekday;
                }
                if (n.recurrence.type === 'monthly_weekday' && n.recurrence.time_of_day) {
                    document.getElementById('monthly-weekday-time').value = n.recurrence.time_of_day;
                }
            }

            setScheduleType(scheduleType);
            renderDates();
            renderSubsequents();
            updateMonthButtons();
            updateWeekdayButtons();
            updatePreview();
            updateCharCount();
        } catch (error) {
            Toast.error('Error', 'Failed to load notification');
            window.location.href = '/notifier/notifications/';
        }
    }

    function toggleYearlyRepeat() {
        yearlyRepeat = document.getElementById('yearly-repeat').checked;
        updateYearlyToggle();
    }

    function updateYearlyToggle() {
        const toggle = document.getElementById('yearly-toggle');
        const knob = toggle.querySelector('span');
        if (yearlyRepeat) {
            toggle.classList.remove('bg-slate-300');
            toggle.classList.add('bg-indigo-500');
            knob.style.transform = 'translateX(16px)';
        } else {
            toggle.classList.add('bg-slate-300');
            toggle.classList.remove('bg-indigo-500');
            knob.style.transform = 'translateX(0)';
        }
    }

    // Image upload functions
    async function handleImageSelect(event) {
        const file = event.target.files[0];
        if (!file) return;

        // Validate file type
        const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp'];
        if (!allowedTypes.includes(file.type)) {
            Toast.error('Invalid file', 'Please select a PNG, JPG, GIF, or WebP image');
            event.target.value = '';
            return;
        }

        // Validate file size (5MB)
        if (file.size > 5 * 1024 * 1024) {
            Toast.error('File too large', 'Image must be less than 5MB');
            event.target.value = '';
            return;
        }

        // Show uploading state
        document.getElementById('image-empty').classList.add('hidden');
        document.getElementById('image-preview').classList.add('hidden');
        document.getElementById('image-uploading').classList.remove('hidden');

        try {
            const formData = new FormData();
            formData.append('image', file);

            const response = await fetch('/notifier/api/upload', {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const result = await response.json();

            if (!result.success) {
                throw new Error(result.error || 'Upload failed');
            }

            imagePath = result.path;
            showImagePreview(`/notifier/uploads/${result.path}`, file.name);
            Toast.success('Uploaded', 'Image uploaded successfully');
        } catch (error) {
            Toast.error('Upload failed', error.message);
            showImageEmpty();
        }

        event.target.value = '';
    }

    function showImagePreview(url, filename) {
        document.getElementById('image-empty').classList.add('hidden');
        document.getElementById('image-uploading').classList.add('hidden');
        document.getElementById('image-preview').classList.remove('hidden');
        document.getElementById('image-preview-img').src = url;
        document.getElementById('image-filename').textContent = filename || 'Uploaded image';
    }

    function showImageEmpty() {
        document.getElementById('image-empty').classList.remove('hidden');
        document.getElementById('image-uploading').classList.add('hidden');
        document.getElementById('image-preview').classList.add('hidden');
        imagePath = null;
    }

    function removeImage() {
        showImageEmpty();
        Toast.success('Removed', 'Image removed');
    }

    // Follow-up image upload functions
    async function handleSubImageSelect(event) {
        const file = event.target.files[0];
        if (!file) return;

        const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp'];
        if (!allowedTypes.includes(file.type)) {
            Toast.error('Invalid file', 'Please select a PNG, JPG, GIF, or WebP image');
            event.target.value = '';
            return;
        }

        if (file.size > 5 * 1024 * 1024) {
            Toast.error('File too large', 'Image must be less than 5MB');
            event.target.value = '';
            return;
        }

        document.getElementById('sub-image-empty').classList.add('hidden');
        document.getElementById('sub-image-preview').classList.add('hidden');
        document.getElementById('sub-image-uploading').classList.remove('hidden');

        try {
            const result = await Api.uploadImage(file);
            subImagePath = result.path || result.image_path || null;
            showSubImagePreview(`/notifier/uploads/${subImagePath}`, file.name);
            Toast.success('Uploaded', 'Image uploaded successfully');
        } catch (error) {
            Toast.error('Upload failed', error.message);
            showSubImageEmpty();
        }

        event.target.value = '';
    }

    function showSubImagePreview(url, filename) {
        document.getElementById('sub-image-empty').classList.add('hidden');
        document.getElementById('sub-image-uploading').classList.add('hidden');
        document.getElementById('sub-image-preview').classList.remove('hidden');
        document.getElementById('sub-image-preview-img').src = url;
        document.getElementById('sub-image-filename').textContent = filename || 'Uploaded image';
    }

    function showSubImageEmpty() {
        document.getElementById('sub-image-empty').classList.remove('hidden');
        document.getElementById('sub-image-uploading').classList.add('hidden');
        document.getElementById('sub-image-preview').classList.add('hidden');
        subImagePath = null;
    }

    function resetSubImage() {
        showSubImageEmpty();
        document.getElementById('sub-image-input').value = '';
        document.getElementById('sub-image-filename').textContent = '';
    }

    function removeSubImage() {
        showSubImageEmpty();
        Toast.success('Removed', 'Image removed');
    }

    async function testMainMessage() {
        const message = messageEl.value.trim();
        if (!message) {
            Toast.warning('No message', 'Please enter a message to test');
            return;
        }

        const btn = document.getElementById('test-main-btn');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<span class="animate-pulse">...</span>';
        btn.disabled = true;

        try {
            if (editId) {
                await Api.testNotification(editId);
            } else {
                const payload = { message };
                if (imagePath) payload.image_path = imagePath;
                await Api.request('POST', '/test-message', payload);
            }
            Toast.success('Sent!', 'Test message sent');
        } catch (error) {
            Toast.error('Error', error.message);
        } finally {
            btn.innerHTML = originalText;
            btn.disabled = false;
        }
    }

    async function testFollowupMessage() {
        const message = document.getElementById('sub-message').value.trim();
        if (!message) {
            Toast.warning('No message', 'Please enter a follow-up message to test');
            return;
        }

        const btn = document.getElementById('test-sub-btn');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<span class="animate-pulse">...</span>';
        btn.disabled = true;

        try {
            const payload = { message };
            if (subImagePath) payload.image_path = subImagePath;
            await Api.request('POST', '/test-message', payload);
            Toast.success('Sent!', 'Test message sent');
        } catch (error) {
            Toast.error('Error', error.message);
        } finally {
            btn.innerHTML = originalText;
            btn.disabled = false;
        }
    }

    function setScheduleType(type) {
        scheduleType = type;
        document.getElementById('tab-dates').className = `flex-1 h-7 rounded-md text-xs font-medium transition-colors ${type === 'dates' ? 'bg-white shadow-sm text-slate-900' : 'text-slate-500'}`;
        document.getElementById('tab-recurrence').className = `flex-1 h-7 rounded-md text-xs font-medium transition-colors ${type === 'recurrence' ? 'bg-white shadow-sm text-slate-900' : 'text-slate-500'}`;
        document.getElementById('section-dates').classList.toggle('hidden', type !== 'dates');
        document.getElementById('section-recurrence').classList.toggle('hidden', type !== 'recurrence');
        if (type === 'recurrence') updateRecurrenceUI();
    }

    function renderDates() {
        document.getElementById('dates-list').innerHTML = dates.map((d, i) => `
            <div class="flex items-center gap-2 p-3 bg-slate-50 rounded-lg">
                <svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                <span class="flex-1 text-xs">${formatDateInput(d)}</span>
                <button onclick="removeDate(${i})" class="w-6 h-6 rounded hover:bg-slate-200 flex items-center justify-center text-slate-400">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                </button>
            </div>
        `).join('');
    }

    function formatDateInput(dateStr) {
        const [date, time] = dateStr.split(' ');
        const d = new Date(date + 'T' + time);
        return d.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' }) + ' at ' + time;
    }

    function addDate() {
        document.getElementById('date-modal').classList.remove('hidden');
        document.getElementById('modal-date').value = new Date().toISOString().split('T')[0];
    }

    function closeDateModal() { document.getElementById('date-modal').classList.add('hidden'); }

    function confirmDate() {
        const date = document.getElementById('modal-date').value;
        const time = document.getElementById('modal-time').value;
        if (date && time) { dates.push(`${date} ${time}`); renderDates(); closeDateModal(); }
    }

    function removeDate(i) { dates.splice(i, 1); renderDates(); }

    function updateRecurrenceUI() {
        const type = document.getElementById('recurrence-type').value;
        document.getElementById('recurrence-months').classList.toggle('hidden', type !== 'specific_months');
        document.getElementById('recurrence-weekdays').classList.toggle('hidden', type !== 'weekly');
        document.getElementById('recurrence-monthly-weekday').classList.toggle('hidden', type !== 'monthly_weekday');
        document.getElementById('recurrence-payday').classList.toggle('hidden', type !== 'payday');
        document.getElementById('recurrence-day').classList.toggle('hidden', type === 'weekly' || type === 'daily' || type === 'monthly_weekday' || type === 'payday');
        document.getElementById('recurrence-interval').classList.toggle('hidden', type !== 'daily');
        updatePreview();
    }

    function toggleMonth(m) {
        const i = selectedMonths.indexOf(m);
        if (i === -1) selectedMonths.push(m); else selectedMonths.splice(i, 1);
        selectedMonths.sort((a, b) => a - b);
        updateMonthButtons();
        updatePreview();
    }

    function updateMonthButtons() {
        document.querySelectorAll('.month-btn').forEach(btn => {
            const m = parseInt(btn.dataset.month);
            btn.className = `month-btn h-8 rounded-lg text-[11px] font-medium transition-colors ${selectedMonths.includes(m) ? 'bg-indigo-500 text-white' : 'bg-slate-100 hover:bg-slate-200'}`;
        });
    }

    function toggleWeekday(d) {
        const i = selectedWeekdays.indexOf(d);
        if (i === -1) selectedWeekdays.push(d); else selectedWeekdays.splice(i, 1);
        selectedWeekdays.sort((a, b) => a - b);
        updateWeekdayButtons();
        updatePreview();
    }

    function updateWeekdayButtons() {
        document.querySelectorAll('.weekday-btn').forEach(btn => {
            const d = parseInt(btn.dataset.weekday);
            btn.className = `weekday-btn flex-1 h-8 rounded-lg text-[11px] font-medium transition-colors ${selectedWeekdays.includes(d) ? 'bg-indigo-500 text-white' : 'bg-slate-100 hover:bg-slate-200'}`;
        });
    }

    function getRecurrence() {
        const type = document.getElementById('recurrence-type').value;
        if (type === 'payday') {
            return {
                type: 'monthly_date',
                day_of_month: parseInt(document.getElementById('payday-day').value),
                time_of_day: document.getElementById('payday-time').value,
                weekend_adjust: 'previous_weekday'
            };
        }

        const recurrence = { type };

        if (type === 'monthly_weekday') {
            recurrence.time_of_day = document.getElementById('monthly-weekday-time').value;
            const weekNum = document.getElementById('week-number').value;
            recurrence.week_number = weekNum; // Must be string: "1", "2", "3", "4", or "last"
            recurrence.weekday = parseInt(document.getElementById('weekday-select').value);
        } else {
            recurrence.time_of_day = document.getElementById('recurrence-time').value;
            if (type === 'specific_months') { recurrence.months = [...selectedMonths]; recurrence.day_of_month = parseInt(document.getElementById('day-of-month').value); }
            else if (type === 'monthly_date') { recurrence.day_of_month = parseInt(document.getElementById('day-of-month').value); }
            else if (type === 'weekly') { recurrence.weekdays = [...selectedWeekdays]; }
            else if (type === 'daily') { recurrence.interval_days = parseInt(document.getElementById('interval-days').value) || 1; }
        }
        return recurrence;
    }

    let previewRequestId = 0;

    async function updatePreview() {
        const previewEl = document.getElementById('preview-dates');
        const recurrence = getRecurrence();

        if (recurrence.type === 'specific_months' && selectedMonths.length === 0) {
            previewEl.innerHTML = '<p class="text-slate-400">Select months to see preview</p>';
            return;
        }

        if (recurrence.type === 'weekly' && selectedWeekdays.length === 0) {
            previewEl.innerHTML = '<p class="text-slate-400">Select days to see preview</p>';
            return;
        }

        const requestId = ++previewRequestId;
        previewEl.innerHTML = '<p class="text-slate-400">Loading preview...</p>';

        try {
            const result = await Api.previewSchedule({
                schedule_type: 'recurrence',
                recurrence,
                timezone: appTimezone
            });

            if (requestId !== previewRequestId) return;
            const datesDisplay = result.dates_display || [];
            previewEl.innerHTML = datesDisplay.length === 0
                ? '<p class="text-slate-400">Select options to see preview</p>'
                : datesDisplay.map(d => `<div class="flex items-center gap-1.5"><span class="text-indigo-500">&#8226;</span>${d}</div>`).join('');
        } catch (error) {
            if (requestId !== previewRequestId) return;
            previewEl.innerHTML = '<p class="text-slate-400">Preview unavailable</p>';
        }
    }

    function renderSubsequents() {
        document.getElementById('subsequents-list').innerHTML = subsequents.map((s, i) => {
            const imageBadge = s.image_path ? '<span class="text-[10px] px-2 py-0.5 rounded-full bg-indigo-50 text-indigo-500 font-medium">Image</span>' : '';
            return `
            <div class="p-3 bg-slate-50 rounded-lg">
                <div class="flex items-center justify-between mb-1">
                    <div class="flex items-center gap-2">
                        <span class="text-xs text-indigo-500 font-medium">${formatOffset(s.offset_days, s.offset_hours, s.offset_minutes)}</span>
                        ${imageBadge}
                    </div>
                    <div class="flex items-center gap-1">
                        <button onclick="editSubsequent(${i})" class="w-5 h-5 rounded hover:bg-slate-200 flex items-center justify-center text-slate-400" title="Edit">
                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                        </button>
                        <button onclick="removeSubsequent(${i})" class="w-5 h-5 rounded hover:bg-slate-200 flex items-center justify-center text-slate-400" title="Remove">
                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                        </button>
                    </div>
                </div>
                <p class="text-xs text-slate-600 truncate">${escapeHtml(s.message)}</p>
            </div>
        `;
        }).join('');
    }

    function addSubsequent() {
        editingSubsequentIndex = null;
        document.getElementById('subsequent-modal').classList.remove('hidden');
        document.getElementById('sub-modal-title').textContent = 'Add Follow-up';
        document.getElementById('sub-confirm-btn').textContent = 'Add Follow-up';
        document.getElementById('sub-days').value = 1;
        document.getElementById('sub-hours').value = 0;
        document.getElementById('sub-minutes').value = 0;
        document.getElementById('sub-message').value = '';
        resetSubImage();
        updateSubCharCount();
    }

    function editSubsequent(index) {
        editingSubsequentIndex = index;
        const s = subsequents[index];
        document.getElementById('subsequent-modal').classList.remove('hidden');
        document.getElementById('sub-modal-title').textContent = 'Edit Follow-up';
        document.getElementById('sub-confirm-btn').textContent = 'Update Follow-up';
        document.getElementById('sub-days').value = s.offset_days || 0;
        document.getElementById('sub-hours').value = s.offset_hours || 0;
        document.getElementById('sub-minutes').value = s.offset_minutes || 0;
        document.getElementById('sub-message').value = s.message || '';
        if (s.image_path) {
            subImagePath = s.image_path;
            const fileName = s.image_path.split('/').pop();
            showSubImagePreview(`/notifier/uploads/${s.image_path}`, fileName);
        } else {
            resetSubImage();
        }
        updateSubCharCount();
    }

    function closeSubsequentModal() {
        document.getElementById('subsequent-modal').classList.add('hidden');
        resetSubImage();
        editingSubsequentIndex = null;
    }

    function confirmSubsequent() {
        const days = parseInt(document.getElementById('sub-days').value) || 0;
        const hours = parseInt(document.getElementById('sub-hours').value) || 0;
        const minutes = parseInt(document.getElementById('sub-minutes').value) || 0;
        const message = document.getElementById('sub-message').value.trim();

        if (!message) {
            Toast.warning('Missing message', 'Please enter a follow-up message');
            return;
        }
        if (days === 0 && hours === 0 && minutes === 0) {
            Toast.warning('Invalid offset', 'Please set at least 1 minute offset');
            return;
        }

        const subsequentData = {
            offset_days: days,
            offset_hours: hours,
            offset_minutes: minutes,
            message,
            image_path: subImagePath || null
        };

        if (editingSubsequentIndex !== null) {
            // Editing existing - preserve the original id
            subsequentData.id = subsequents[editingSubsequentIndex].id;
            subsequents[editingSubsequentIndex] = subsequentData;
            Toast.success('Updated', 'Follow-up updated successfully');
        } else {
            // Adding new
            subsequentData.id = Date.now();
            subsequents.push(subsequentData);
            Toast.success('Added', 'Follow-up added successfully');
        }

        renderSubsequents();
        closeSubsequentModal();
    }

    function removeSubsequent(i) { subsequents.splice(i, 1); renderSubsequents(); }

    function insertFormat(before, after) {
        const ta = messageEl;
        const start = ta.selectionStart, end = ta.selectionEnd;
        const selected = ta.value.substring(start, end) || 'text';
        ta.value = ta.value.substring(0, start) + before + selected + after + ta.value.substring(end);
        ta.focus();
        ta.selectionStart = start + before.length;
        ta.selectionEnd = start + before.length + selected.length;
        updateCharCount();
    }

    function insertSubFormat(before, after) {
        const ta = document.getElementById('sub-message');
        const start = ta.selectionStart, end = ta.selectionEnd;
        const selected = ta.value.substring(start, end) || 'text';
        ta.value = ta.value.substring(0, start) + before + selected + after + ta.value.substring(end);
        ta.focus();
        ta.selectionStart = start + before.length;
        ta.selectionEnd = start + before.length + selected.length;
        updateSubCharCount();
    }

    function updateSubCharCount() {
        const count = document.getElementById('sub-message').value.length;
        document.getElementById('sub-char-count').textContent = count;
        document.getElementById('sub-char-count').style.color = count > 4096 ? '#ef4444' : '';
    }

    function updateCharCount() {
        const count = messageEl.value.length;
        document.getElementById('char-count').textContent = count;
        document.getElementById('char-count').style.color = count > 4096 ? '#ef4444' : '';
    }

    messageEl.addEventListener('input', updateCharCount);
    document.getElementById('sub-message').addEventListener('input', updateSubCharCount);

    async function save() {
        const title = titleEl.value.trim();
        const message = messageEl.value.trim();

        if (!title) { Toast.warning('Missing title', 'Please enter a title'); titleEl.focus(); return; }
        if (!message) { Toast.warning('Missing message', 'Please enter a message'); messageEl.focus(); return; }
        if (message.length > 4096) { Toast.warning('Message too long', 'Message exceeds 4096 characters'); return; }
        if (scheduleType === 'dates' && dates.length === 0) { Toast.warning('No dates', 'Please add at least one date'); return; }
        if (scheduleType === 'recurrence') {
            const type = document.getElementById('recurrence-type').value;
            if (type === 'specific_months' && selectedMonths.length === 0) { Toast.warning('No months', 'Please select at least one month'); return; }
            if (type === 'weekly' && selectedWeekdays.length === 0) { Toast.warning('No days', 'Please select at least one day'); return; }
        }

        const notification = {
            title, message,
            context: contextEl.value.trim() || null,
            category_id: categoryEl.value ? parseInt(categoryEl.value) : null,
            image_path: imagePath || null,
            timezone: appTimezone,
            schedule_type: scheduleType,
            dates: scheduleType === 'dates' ? dates : [],
            yearly_repeat: scheduleType === 'dates' ? yearlyRepeat : false,
            recurrence: scheduleType === 'recurrence' ? getRecurrence() : null,
            subsequents
        };

        try {
            if (editId) {
                await Api.updateNotification(editId, notification);
                Toast.success('Updated', 'Notification has been saved');
            } else {
                await Api.createNotification(notification);
                Toast.success('Created', 'Notification has been created');
            }
            window.location.href = '/notifier/notifications/';
        } catch (error) {
            Toast.error('Error', error.message);
        }
    }

    function goBack() { window.location.href = '/notifier/notifications/'; }

    init();
</script>
</body>
</html>
