/* TechCon Agenda Pro — Admin UI JS */
(function($) {
    'use strict';
    const C = window.tcaAdmin;
    if (!C) return;

    const $app = $('#tca-app');
    const page = $app.data('page'); // tca-speakers, tca-events, tca-sessions

    // SVGs
    const icons = {
        edit: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>',
        trash: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>',
        key: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"></path></svg>',
        link: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>',
        user: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>'
    };

    // Global state
    let state = {
        data: [],
        currentEventId: C.events.length > 0 ? C.events[0].id : 0,
        sessionSearch: ''
    };

    /* ── Core AJAX Helper ──────────────────────────────────── */
    function req(action, data = {}) {
        data.action = action;
        data.nonce = C.nonce;
        return $.post(C.ajaxUrl, data).then(r => {
            if (!r.success) throw new Error(r.data?.message || C.i18n.error);
            return r.data;
        });
    }

    function esc(s) {
        return String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }

    /* ── Render Headers ────────────────────────────────────── */
    function renderHeader(title, buttonsHtml = '') {
        return `
            <div class="tca-header">
                <h1>
                    <svg viewBox="0 0 24 24" fill="none" stroke="var(--tca-pink)" stroke-width="2"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>
                    ${title}
                </h1>
                <div class="tca-flex">${buttonsHtml}</div>
            </div>
            <div id="tca-content"></div>
        `;
    }

    /* ── Modals ────────────────────────────────────────────── */
    function openModal(title, bodyHtml, onSave) {
        $('.tca-modal-overlay').remove();
        const html = `
            <div class="tca-modal-overlay active">
                <div class="tca-modal">
                    <div class="tca-modal-header">
                        <h2>${title}</h2>
                        <button class="tca-modal-close">&times;</button>
                    </div>
                    <div class="tca-modal-body">
                        <form id="tca-modal-form">${bodyHtml}</form>
                    </div>
                    <div class="tca-modal-footer">
                        <button class="tca-btn tca-modal-close">Cancel</button>
                        <button class="tca-btn tca-btn-primary" id="tca-modal-save">Save</button>
                    </div>
                </div>
            </div>
        `;
        $('body').append(html);
        $('.tca-modal-close').on('click', () => $('.tca-modal-overlay').remove());
        $('#tca-modal-save').on('click', () => {
            const fd = new FormData(document.getElementById('tca-modal-form'));
            const data = Object.fromEntries(fd.entries());
            onSave(data, $('#tca-modal-save'));
        });
    }

    /* ── Speakers Page ─────────────────────────────────────── */
    function loadSpeakers() {
        $app.html(renderHeader('Speakers Pool', `
            <button class="tca-btn" id="btn-import-sp">Import CSV</button>
            <button class="tca-btn tca-btn-primary" id="btn-add-sp">+ Add Speaker</button>
        `));
        $('#tca-content').html('<div class="tca-loader"></div>');

        req('tca_get_speakers').then(res => {
            state.data = res;
            let rows = res.map(sp => `
                <tr>
                    <td>
                        <div class="tca-flex">
                            ${sp.image_url ? `<img src="${sp.image_url}" class="tca-avatar-sm">` : `<div class="tca-avatar-sm"></div>`}
                            <div>
                                <div style="font-weight:600;color:#fff">${sp.name}</div>
                                <div style="font-size:12px;color:var(--tca-text-muted)">${sp.email}</div>
                            </div>
                        </div>
                    </td>
                    <td>${sp.company || '—'}<br><small style="color:var(--tca-text-muted)">${sp.position || ''}</small></td>
                    <td>
                        ${sp.credentials_sent == 1 
                            ? `<span class="tca-badge tca-badge-live">Sent</span>` 
                            : `<button class="tca-btn btn-send-cred" data-id="${sp.id}" style="padding:4px 8px;font-size:11px">Send Credentials</button>`}
                    </td>
                    <td>
                        <div class="tca-actions">
                            ${sp.profile_url ? `<a href="${sp.profile_url}" target="_blank" class="tca-icon-btn" title="View Profile" style="color:var(--tca-text-muted)">${icons.link}</a>` : ''}
                            <button class="tca-icon-btn btn-pw" data-id="${sp.id}" title="Manage Password">${icons.key}</button>
                            <button class="tca-icon-btn btn-edit-sp" data-id="${sp.id}" title="Edit">${icons.edit}</button>
                            <button class="tca-icon-btn btn-del-sp" data-id="${sp.id}" title="Delete">${icons.trash}</button>
                        </div>
                    </td>
                </tr>
            `).join('');

            $('#tca-content').html(`
                <div class="tca-card tca-table-wrap">
                    <table class="tca-table">
                        <thead><tr><th>Speaker</th><th>Company / Role</th><th>Credentials</th><th>Actions</th></tr></thead>
                        <tbody>${rows || '<tr><td colspan="4" style="text-align:center">No speakers yet.</td></tr>'}</tbody>
                    </table>
                </div>
            `);
            attachSpeakerEvents();
        }).catch(err => alert(err));
    }

    function attachSpeakerEvents() {
        $('#btn-add-sp').on('click', () => editSpeakerModal());
        $('.btn-edit-sp').on('click', function() {
            const id = $(this).data('id');
            const sp = state.data.find(s => s.id == id);
            if (sp) editSpeakerModal(sp);
        });
        $('.btn-del-sp').on('click', function() {
            if (!confirm(C.i18n.confirmDelete)) return;
            req('tca_delete_speaker', { id: $(this).data('id') }).then(() => loadSpeakers());
        });
        $('.btn-send-cred').on('click', function() {
            const $btn = $(this);
            $btn.text('Sending...').prop('disabled', true);
            req('tca_send_credentials', { id: $btn.data('id') })
                .then(res => { alert(res.message); loadSpeakers(); })
                .catch(err => { alert(err); $btn.text('Send Credentials').prop('disabled', false); });
        });
        $('.btn-pw').on('click', function() {
            const id = $(this).data('id');
            req('tca_get_speaker_password', { id }).then(res => {
                const isBlank = res.password === '—';
                const pwHtml = isBlank 
                    ? `<p style="color:var(--tca-text-muted)">No password generated yet. Click "Generate & Send" below.</p>`
                    : `<div style="display:flex;gap:8px;margin-bottom:15px;">
                         <input type="text" id="pw-view-input" class="tca-input" value="${res.password}" readonly style="flex:1;font-family:monospace;">
                         <button type="button" class="tca-btn" onclick="navigator.clipboard.writeText(document.getElementById('pw-view-input').value); alert('Copied!')">Copy</button>
                       </div>`;

                const h = `
                    <div style="margin-bottom: 20px;">
                        <h3>Current Password</h3>
                        ${pwHtml}
                    </div>
                    <div style="padding:15px;background:rgba(255,255,255,0.05);border-radius:8px;margin-bottom:15px;">
                        <h4 style="margin:0 0 10px 0;">Set Custom Password</h4>
                        <div style="display:flex;gap:8px;">
                            <input type="text" id="custom-pw-input" class="tca-input" placeholder="Type new password" style="flex:1;">
                            <button type="button" class="tca-btn" id="btn-save-custom-pw">Set Password</button>
                        </div>
                    </div>
                    <div>
                        <button type="button" class="tca-btn tca-btn-primary" id="btn-resend-pw" style="width:100%;justify-content:center;">
                            Generate New Random Password & Send Email
                        </button>
                    </div>
                `;
                openModal('Manage Speaker Password', h, () => $('.tca-modal-overlay').remove());
                $('#tca-modal-save').hide(); // Hide the default save button

                $('#btn-save-custom-pw').on('click', () => {
                    const newPw = $('#custom-pw-input').val();
                    if(!newPw) return alert('Enter a password first');
                    $('#btn-save-custom-pw').text('Saving...');
                    req('tca_set_speaker_password', { id, password: newPw })
                        .then(r => { alert(r.message); $('.tca-modal-overlay').remove(); })
                        .catch(e => { alert(e); $('#btn-save-custom-pw').text('Set Password'); });
                });

                $('#btn-resend-pw').on('click', () => {
                    $('#btn-resend-pw').text('Sending...').prop('disabled', true);
                    req('tca_send_credentials', { id })
                        .then(r => { alert(r.message); $('.tca-modal-overlay').remove(); })
                        .catch(e => { alert(e); $('#btn-resend-pw').text('Generate New Random Password & Send Email').prop('disabled', false); });
                });
            });
        });
        $('#btn-import-sp').on('click', () => {
            const h = `
                <p>Upload a CSV file. <a href="${C.ajaxUrl}?action=tca_export_speakers_template" class="tca-text-pink">Download Template</a></p>
                <input type="file" name="csv" class="tca-input" accept=".csv" required>
            `;
            openModal('Import Speakers', h, (data, $btn) => {
                $btn.text('Importing...');
                const fd = new FormData(document.getElementById('tca-modal-form'));
                fd.append('action', 'tca_import_speakers');
                fd.append('nonce', C.nonce);
                $.ajax({ url: C.ajaxUrl, type: 'POST', data: fd, processData: false, contentType: false })
                 .done(r => { $('.tca-modal-overlay').remove(); loadSpeakers(); alert(`Imported: ${r.data.inserted}, Updated: ${r.data.updated}`); })
                 .fail(() => alert('Import failed.'));
            });
        });
    }

    function editSpeakerModal(sp = {}) {
        const h = `
            <input type="hidden" name="id" value="${sp.id || 0}">
            <div class="tca-form-grid">
                <div class="tca-form-group"><label>Name *</label><input type="text" name="name" class="tca-input" value="${sp.name || ''}" required></div>
                <div class="tca-form-group"><label>Email *</label><input type="email" name="email" class="tca-input" value="${sp.email || ''}" required></div>
                <div class="tca-form-group"><label>Company</label><input type="text" name="company" class="tca-input" value="${sp.company || ''}"></div>
                <div class="tca-form-group"><label>Position</label><input type="text" name="position" class="tca-input" value="${sp.position || ''}"></div>
                <div class="tca-form-group"><label>Image URL</label><input type="text" name="image_url" class="tca-input" value="${sp.image_url || ''}"></div>
                <div class="tca-form-group"><label>LinkedIn URL</label><input type="text" name="linkedin_url" class="tca-input" value="${sp.linkedin_url || ''}"></div>
                <div class="tca-form-group"><label>Public Profile Tag</label><input type="text" name="profile_tag" class="tca-input" value="${sp.profile_tag || 'TechCon SoCal 2026 Speaker'}" placeholder="TechCon SoCal 2026 Speaker"><p style="font-size:12px;color:var(--tca-text-muted);margin-top:6px;">Shown as the main tag on the public speaker profile.</p></div>
                <div class="tca-form-group" style="grid-column:1/-1"><label>Custom Profile URL</label><input type="url" name="profile_url" class="tca-input" value="${sp.profile_url || ''}" placeholder="Leave empty to auto-generate /speaker/speaker-name/"><p style="font-size:12px;color:var(--tca-text-muted);margin-top:6px;">If this field is empty, the plugin automatically uses the speaker’s internal public profile link. You can paste a custom TechCon/team profile URL here anytime.</p></div>
            </div>
            <div class="tca-form-group"><label>Bio</label><textarea name="bio" class="tca-input">${sp.bio || ''}</textarea></div>
        `;
        openModal(sp.id ? 'Edit Speaker' : 'Add Speaker', h, (data, $btn) => {
            $btn.text('Saving...');
            req('tca_save_speaker', data).then(() => { $('.tca-modal-overlay').remove(); loadSpeakers(); }).catch(err => { alert(err); $btn.text('Save'); });
        });
    }

    /* ── Events Page ───────────────────────────────────────── */
    function loadEvents() {
        $app.html(renderHeader('Events', `<button class="tca-btn tca-btn-primary" id="btn-add-ev">+ Create Event</button>`));
        $('#tca-content').html('<div class="tca-loader"></div>');

        req('tca_get_events').then(res => {
            state.data = res;
            let rows = res.map(ev => `
                <tr>
                    <td>
                        <div style="font-weight:700;color:#fff">${ev.name}</div>
                        <div style="font-size:12px;color:var(--tca-text-muted)">${ev.date_range}</div>
                        <div style="font-size:11px;margin-top:6px;font-family:monospace;color:var(--tca-pink)">[techcon_agenda id="${ev.id}"]</div>
                    </td>
                    <td>${ev.venue}<br><small style="color:var(--tca-text-muted)">${ev.address}</small></td>
                    <td><span class="tca-badge ${ev.status === 'live' ? 'tca-badge-live' : 'tca-badge-draft'}">${ev.status.toUpperCase()}</span></td>
                    <td>
                        <div class="tca-actions">
                            <button class="tca-icon-btn btn-edit-ev" data-id="${ev.id}" title="Edit">${icons.edit}</button>
                            <button class="tca-icon-btn btn-del-ev" data-id="${ev.id}" title="Delete">${icons.trash}</button>
                        </div>
                    </td>
                </tr>
            `).join('');

            $('#tca-content').html(`
                <div class="tca-card tca-table-wrap">
                    <table class="tca-table">
                        <thead><tr><th>Event / Shortcode</th><th>Location</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody>${rows || '<tr><td colspan="4" style="text-align:center">No events yet.</td></tr>'}</tbody>
                    </table>
                </div>
            `);
            attachEventEvents();
        }).catch(err => alert(err));
    }

    function attachEventEvents() {
        $('#btn-add-ev').on('click', () => editEventModal());
        $('.btn-edit-ev').on('click', function() {
            const id = $(this).data('id');
            const ev = state.data.find(e => e.id == id);
            if (ev) editEventModal(ev);
        });
        $('.btn-del-ev').on('click', function() {
            if (!confirm(C.i18n.confirmDelete)) return;
            req('tca_delete_event', { id: $(this).data('id') }).then(() => loadEvents());
        });
    }

    function editEventModal(ev = {}) {
        const h = `
            <input type="hidden" name="id" value="${ev.id || 0}">
            <div class="tca-form-grid">
                <div class="tca-form-group"><label>Event Name *</label><input type="text" name="name" class="tca-input" value="${ev.name || ''}" required></div>
                <div class="tca-form-group"><label>Subtitle</label><input type="text" name="subtitle" class="tca-input" value="${ev.subtitle || ''}"></div>
                <div class="tca-form-group"><label>Date Range (Text)</label><input type="text" name="date_range" class="tca-input" value="${ev.date_range || ''}" placeholder="e.g. May 21-23, 2026"></div>
                <div class="tca-form-group"><label>Status</label>
                    <select name="status" class="tca-input">
                        <option value="draft" ${ev.status==='draft'?'selected':''}>Draft</option>
                        <option value="live" ${ev.status==='live'?'selected':''}>Live</option>
                    </select>
                </div>
                <div class="tca-form-group"><label>Venue Name</label><input type="text" name="venue" class="tca-input" value="${ev.venue || ''}"></div>
                <div class="tca-form-group"><label>City/Address</label><input type="text" name="address" class="tca-input" value="${ev.address || ''}"></div>
                
                <div class="tca-form-group"><label>Primary Color (Pink)</label><input type="color" name="color_primary" class="tca-input" value="${ev.color_primary || '#e61a84'}" style="height:40px;padding:2px"></div>
                <div class="tca-form-group"><label>Secondary Color (Purple)</label><input type="color" name="color_secondary" class="tca-input" value="${ev.color_secondary || '#4e24c0'}" style="height:40px;padding:2px"></div>
                <div class="tca-form-group"><label>Background Color</label><input type="color" name="color_bg" class="tca-input" value="${ev.color_bg || '#0b0b1c'}" style="height:40px;padding:2px"></div>
            </div>
        `;
        openModal(ev.id ? 'Edit Event' : 'Create Event', h, (data, $btn) => {
            $btn.text('Saving...');
            req('tca_save_event', data).then(() => { 
                $('.tca-modal-overlay').remove(); 
                // Refresh global events list for dropdowns if needed, then reload
                window.location.reload(); 
            }).catch(err => { alert(err); $btn.text('Save'); });
        });
    }

    /* ── Sessions Page (Basic placeholder, full implementation needs more React/Vue-like state) ─ */
    function loadSessions() {
        if (!C.events.length) {
            $app.html(renderHeader('Sessions') + '<div class="tca-card">Please create an Event first.</div>');
            return;
        }
        
        let evOptions = C.events.map(e => `<option value="${e.id}" ${e.id == state.currentEventId ? 'selected' : ''}>${e.name}</option>`).join('');
        
        $app.html(renderHeader('Sessions', `
            <input type="search" id="sess-keyword-search" class="tca-input" value="${state.sessionSearch || ''}" placeholder="Search sessions by title, code, track, room, speaker..." style="width:360px;max-width:100%;margin-right:10px">
            <select id="sess-event-filter" class="tca-input" style="width:200px;margin-right:10px">${evOptions}</select>
            <button class="tca-btn" id="btn-import-sess">Import CSV</button>
            <button class="tca-btn tca-btn-primary" id="btn-add-sess">+ Add Session</button>
        `));

        $('#sess-event-filter').on('change', function() {
            state.currentEventId = $(this).val();
            renderSessionsTable();
        });

        let sessionSearchTimer = null;
        $('#sess-keyword-search').on('input', function() {
            state.sessionSearch = $(this).val();
            clearTimeout(sessionSearchTimer);
            sessionSearchTimer = setTimeout(renderSessionsTable, 180);
        });

        renderSessionsTable();
    }

    function renderSessionsTable() {
        $('#tca-content').html('<div class="tca-loader"></div>');
        req('tca_get_sessions', { event_id: state.currentEventId }).then(res => {
            const keyword = String(state.sessionSearch || '').trim().toLowerCase();
            const matchesKeyword = (s) => {
                if (!keyword) return true;
                const speakersText = (s.speakers || []).map(sp => [sp.name, sp.company, sp.position, sp.email].filter(Boolean).join(' ')).join(' ');
                const searchable = [
                    s.external_id, s.json_id, s.date_short, s.date, s.time_string, s.room,
                    s.session_code, s.code, s.session_type, s.type, s.title, s.track,
                    s.description, s.brief, s.day_label, speakersText
                ].filter(Boolean).join(' ').toLowerCase();
                return searchable.includes(keyword);
            };
            const filtered = res.filter(matchesKeyword);

            let rows = filtered.map(s => `
                <tr>
                    <td>
                        <div style="font-weight:700;color:#fff">${s.title}</div>
                        <div style="font-size:12px;color:var(--tca-text-muted)">
                          ${s.day_label || ''} · ${s.date_short || s.date || ''} · ${s.time_string || ''}
                        </div>
                        <div style="font-size:11px;color:var(--tca-pink);font-family:monospace;margin-top:3px;">
                          ${s.external_id || s.json_id || 'No JSON ID'} ${s.session_code ? ' · Code: ' + s.session_code : ''}
                        </div>
                    </td>
                    <td><span class="tca-badge" style="background:rgba(255,255,255,0.1)">${s.session_type || 'Session'}</span></td>
                    <td>${s.room || '—'}</td>
                    <td>
                        <span style="font-size:12px;color:var(--tca-text-muted);">Agenda item</span>
                    </td>
                    <td>
                        <div class="tca-actions">
                            <button class="tca-icon-btn btn-edit-sess" data-id="${s.id}" title="Edit">${icons.edit}</button>
                            <button class="tca-icon-btn btn-del-sess" data-id="${s.id}" title="Delete">${icons.trash}</button>
                        </div>
                    </td>
                </tr>
            `).join('');

            $('#tca-content').html(`
                <div class="tca-card" style="margin-bottom:14px;display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap">
                    <div style="font-weight:700;color:#fff">${filtered.length} Session${filtered.length === 1 ? '' : 's'} Found</div>
                    <div style="font-size:12px;color:var(--tca-text-muted)">${keyword ? 'Filtered from ' + res.length + ' total sessions' : 'Search by title, code, track, room, type, time, description, or speaker name'}</div>
                </div>
                <div class="tca-card tca-table-wrap">
                    <table class="tca-table">
                        <thead><tr><th>Session</th><th>Type</th><th>Room</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody>${rows || '<tr><td colspan="5" style="text-align:center">No sessions found for this search.</td></tr>'}</tbody>
                    </table>
                </div>
            `);

            $('#btn-add-sess').off('click').on('click', () => editSessionModal());
            $('.btn-edit-sess').on('click', function() {
                const id = $(this).data('id');
                const sess = res.find(x => x.id == id);
                if (sess) editSessionModal(sess);
            });
            $('.btn-del-sess').on('click', function() {
                if (!confirm(C.i18n.confirmDelete)) return;
                req('tca_delete_session', { id: $(this).data('id') }).then(() => renderSessionsTable());
            });


            $('#btn-import-sess').off('click').on('click', () => {
                const h = `
                    <p>Import sessions for selected event. <a href="${C.ajaxUrl}?action=tca_export_sessions_template" class="tca-text-pink">Download Template</a></p>
                    <input type="file" name="csv" class="tca-input" accept=".csv" required>
                    <input type="hidden" name="event_id" value="${state.currentEventId}">
                `;
                openModal('Import Sessions', h, (data, $btn) => {
                    $btn.text('Importing...');
                    const fd = new FormData(document.getElementById('tca-modal-form'));
                    fd.append('action', 'tca_import_sessions');
                    fd.append('nonce', C.nonce);
                    $.ajax({ url: C.ajaxUrl, type: 'POST', data: fd, processData: false, contentType: false })
                     .done(r => { $('.tca-modal-overlay').remove(); renderSessionsTable(); alert(`Imported: ${r.data.inserted}`); })
                     .fail(() => alert('Import failed.'));
                });
            });

        }).catch(err => alert(err));
    }


    function editSessionModal(sess = {}) {
        Promise.all([
            req('tca_get_days', { event_id: state.currentEventId }),
            req('tca_get_speakers', { session_selector: 1 })
        ]).then(([days, speakers]) => {
            const selectedSpeakers = (sess.speakers || []).map(sp => String(sp.id));
            const dayOptions = days.map(d => `<option value="${d.id}" ${String(sess.day_id || '') === String(d.id) ? 'selected' : ''}>${d.day_label || d.day_date}</option>`).join('');
            const speakerOptions = speakers.map(sp => {
                const speakerLabel = [sp.name, sp.position, sp.company].filter(Boolean).join(' · ');
                return `<option value="${sp.id}" ${selectedSpeakers.includes(String(sp.id)) ? 'selected' : ''} data-search="${speakerLabel.toLowerCase()}">${speakerLabel}</option>`;
            }).join('');
            const h = `
                <input type="hidden" name="id" value="${sess.id || 0}">
                <input type="hidden" name="event_id" value="${state.currentEventId}">
                <div class="tca-form-grid">
                    <div class="tca-form-group"><label>Agenda JSON ID</label><input type="text" name="external_id" class="tca-input" value="${sess.external_id || sess.json_id || ''}" placeholder="01-05P"></div>
                    <div class="tca-form-group"><label>Short Date</label><input type="text" name="date_short" class="tca-input" value="${sess.date_short || sess.date || ''}" placeholder="05/22"></div>
                    <div class="tca-form-group"><label>Day</label><select name="day_id" class="tca-input" required>${dayOptions}</select></div>
                    <div class="tca-form-group"><label>Time</label><input type="text" name="time_string" class="tca-input" value="${sess.time_string || ''}" placeholder="11:20 AM - 12:00 PM"></div>
                    <div class="tca-form-group"><label>Room</label><input type="text" name="room" class="tca-input" value="${sess.room || ''}" placeholder="Templo Mayor"></div>
                    <div class="tca-form-group"><label>Code</label><input type="text" name="session_code" class="tca-input" value="${sess.session_code || sess.code || ''}" placeholder="1.4C"></div>
                    <div class="tca-form-group"><label>Type</label><input type="text" name="session_type" class="tca-input" value="${sess.session_type || sess.type || ''}" placeholder="Panel"></div>
                    <div class="tca-form-group"><label>Track</label><input type="text" name="track" class="tca-input" value="${sess.track || ''}" placeholder="Investments"></div>
                </div>
                <div class="tca-form-group"><label>Title</label><input type="text" name="title" class="tca-input" value="${sess.title || ''}" required></div>
                <div class="tca-form-group"><label>Description</label><textarea name="description" class="tca-input" rows="5">${sess.description || ''}</textarea></div>
                <div class="tca-form-group"><label>Brief</label><textarea name="brief" class="tca-input" rows="3">${sess.brief || ''}</textarea></div>
                <div class="tca-form-group"><label>Sort Order</label><input type="number" name="sort_order" class="tca-input" value="${sess.sort_order || 0}"></div>
                <div class="tca-form-group">
                    <label>Speakers for this session</label>
                    <div class="tca-speaker-select-wrap">
                        <input type="search" id="tca-speaker-select-search" class="tca-input" placeholder="Search speakers by name, role, or company..." autocomplete="off">
                        <select id="tca-session-speakers-select" name="speaker_ids[]" class="tca-input tca-multi-select" multiple size="9">
                            ${speakerOptions}
                        </select>
                        ${speakerOptions ? '<div id="tca-selected-speakers" class="tca-selected-speakers"></div>' : '<p style="color:var(--tca-text-muted)">No speakers available yet. Import speakers first, then select them here.</p>'}
                    </div>
                    <p style="font-size:12px;color:var(--tca-text-muted);margin-top:6px;">Search and select multiple speakers. For CSV import, use comma-separated speaker names in one quoted field, for example: "Jack Lucas, Arabian Prince".</p>
                </div>
            `;
            openModal(sess.id ? 'Edit Agenda Session' : 'Add Agenda Session', h, (data, $btn) => {
                $btn.text('Saving...');
                const fd = new FormData(document.getElementById('tca-modal-form'));
                const payload = Object.fromEntries(fd.entries());
                payload.speaker_ids = fd.getAll('speaker_ids[]');
                req('tca_save_session', payload).then(() => {
                    $('.tca-modal-overlay').remove();
                    renderSessionsTable();
                }).catch(err => { alert(err); $btn.text('Save'); });
            });
            initSessionSpeakerSelector();
        }).catch(err => alert(err));
    }


    function initSessionSpeakerSelector() {
        const $select = $('#tca-session-speakers-select');
        const $search = $('#tca-speaker-select-search');
        const $selected = $('#tca-selected-speakers');
        if (!$select.length) return;

        function refreshSelected() {
            const chosen = $select.find('option:selected').map(function() {
                return `<span class="tca-selected-chip" data-id="${this.value}">${$(this).text()} <button type="button" class="tca-chip-remove" aria-label="Remove speaker">×</button></span>`;
            }).get().join('');
            $selected.html(chosen || '<span style="color:var(--tca-text-muted);font-size:12px;">No speakers selected yet.</span>');
        }

        $search.on('input', function() {
            const q = $(this).val().toLowerCase().trim();
            $select.find('option').each(function() {
                const haystack = ($(this).data('search') || $(this).text()).toString().toLowerCase();
                $(this).toggle(!q || haystack.includes(q));
            });
        });

        $select.on('change', refreshSelected);
        $selected.on('click', '.tca-chip-remove', function() {
            const id = $(this).closest('.tca-selected-chip').data('id');
            $select.find(`option[value="${id}"]`).prop('selected', false);
            $select.trigger('change');
        });
        refreshSelected();
    }

    /* ── Settings ──────────────────────────────────────────── */
    function loadSettings() {
        $app.html(renderHeader('Settings', '<button class="tca-btn tca-btn-primary" id="btn-save-settings">Save Settings</button>'));
        $('#tca-content').html('<div class="tca-loader"></div>');

        req('tca_get_settings').then(res => {
            const h = `
                <div class="tca-card" style="max-width: 600px;">
                    <h3>Public Display Options</h3>
                    <div class="tca-form-group">
                        <label style="display:flex;align-items:center;gap:10px;cursor:pointer;">
                            <input type="checkbox" id="set-enable-profiles" ${res.enable_profiles === 'yes' ? 'checked' : ''}>
                            <span>Enable Individual Speaker Profile Pages</span>
                        </label>
                        <p style="font-size:12px;color:var(--tca-text-muted);margin-top:6px;">If enabled, clicking a speaker on the agenda will take visitors to their dedicated profile page.</p>
                    </div>
                    <div class="tca-form-group">
                        <label style="display:flex;align-items:center;gap:10px;cursor:pointer;">
                            <input type="checkbox" id="set-enable-agenda-pages" ${res.enable_agenda_pages === 'yes' ? 'checked' : ''}>
                            <span>Enable Public Agenda Page</span>
                        </label>
                        <p style="font-size:12px;color:var(--tca-text-muted);margin-top:6px;">Controls the public /agenda route and agenda shortcode output.</p>
                    </div>
                    <hr style="border:0;border-top:1px solid rgba(255,255,255,.08);margin:20px 0;">
                    <h3>Speaker Credential Email Text</h3>
                    <div class="tca-form-group">
                        <label>Editable Message Text</label>
                        <textarea class="tca-input" id="set-speaker-credential-body-text" rows="10" placeholder="Write only the email message text. The branded layout, credentials box, CTA button, reset link, and footer stay the same.">${esc(res.speaker_credentials_body_text || '')}</textarea>
                        <p style="font-size:12px;color:var(--tca-text-muted);margin-top:6px;line-height:1.5;">Only this message text changes. The email design, login credentials, CTA button, password reset note, and footer remain fixed. Supported tokens: {site_name}, {name}, {email}, {password}, {login_url}, {dashboard_url}, {reset_url}</p>
                    </div>
                    <h4 style="margin:18px 0 10px;">Header, CTA & Footer Text</h4>
                    <div class="tca-form-group">
                        <label>Header Subtitle</label>
                        <input type="text" class="tca-input" id="set-speaker-credential-header-text" value="${esc(res.speaker_credential_header_text || 'Speaker Portal — Your Access Credentials')}">
                    </div>
                    <div class="tca-form-group">
                        <label>Button Text</label>
                        <input type="text" class="tca-input" id="set-speaker-credential-button-text" value="${esc(res.speaker_credential_button_text || 'Sign In to Speaker Portal →')}">
                    </div>
                    <div class="tca-form-group">
                        <label>Password Reset Note</label>
                        <textarea class="tca-input" id="set-speaker-credential-password-note" rows="3">${esc(res.speaker_credential_password_note || 'For security, you can {reset_link} after logging in. Your new password remains accessible to TechCon administrators.')}</textarea>
                        <p style="font-size:12px;color:var(--tca-text-muted);margin-top:6px;line-height:1.5;">Use {reset_link} where the clickable “change your password” link should appear.</p>
                    </div>
                    <div class="tca-form-group">
                        <label>Footer Company 1 Text</label>
                        <input type="text" class="tca-input" id="set-footer-techcon-text" value="${esc(res.credential_footer_techcon_text || 'TechCon Global')}">
                    </div>
                    <div class="tca-form-group">
                        <label>Footer Company 1 URL</label>
                        <input type="url" class="tca-input" id="set-footer-techcon-url" value="${esc(res.credential_footer_techcon_url || 'https://techconglobal.com/')}">
                    </div>
                    <div class="tca-form-group">
                        <label>Footer Connector Text</label>
                        <input type="text" class="tca-input" id="set-footer-powered-by-text" value="${esc(res.credential_footer_powered_by_text || 'Powered by')}">
                    </div>
                    <div class="tca-form-group">
                        <label>Footer Company 2 Text</label>
                        <input type="text" class="tca-input" id="set-footer-brilzen-text" value="${esc(res.credential_footer_brilzen_text || 'BRILZEN (SMC-PRIVATE) LIMITED')}">
                    </div>
                    <div class="tca-form-group">
                        <label>Footer Company 2 URL</label>
                        <input type="url" class="tca-input" id="set-footer-brilzen-url" value="${esc(res.credential_footer_brilzen_url || 'https://brilzen.com/')}">
                    </div>
                    <hr style="border:0;border-top:1px solid rgba(255,255,255,.08);margin:20px 0;">
                    <h3>Export & Data Maintenance</h3>
                    <div style="display:flex;gap:10px;flex-wrap:wrap;margin:12px 0 16px;">
                        <a class="tca-btn tca-btn-ghost" href="${res.export_speakers_url}" target="_blank">Export Speakers CSV</a>
                        <a class="tca-btn tca-btn-ghost" href="${res.export_sessions_url}" target="_blank">Export Sessions CSV</a>
                        <button class="tca-btn tca-btn-danger" id="btn-clear-speakers-data">Clear All Speaker Data</button>
                    </div>
                    <p style="font-size:12px;color:var(--tca-text-muted);line-height:1.5;"><strong>Clear All Speaker Data</strong> removes all speakers and speaker assignments from events/sessions. Events, days, and sessions remain untouched.</p>
                </div>
            `;
            $('#tca-content').html(h);

            $('#btn-clear-speakers-data').on('click', function() {
                if(!confirm('This will permanently clear all speakers and speaker assignments. Continue?')) return;
                if(!confirm('Final confirmation: this cannot be undone. Clear all speaker data?')) return;
                req('tca_clear_speakers_data', {}).then(res => { alert((res && res.message) || 'Speaker data cleared.'); }).catch(err => alert(err));
            });

            $('#btn-save-settings').on('click', function() {
                const $btn = $(this);
                $btn.text('Saving...');
                req('tca_save_settings', {
                    enable_profiles: $('#set-enable-profiles').is(':checked') ? 'yes' : 'no',
                    enable_agenda_pages: $('#set-enable-agenda-pages').is(':checked') ? 'yes' : 'no',
                    speaker_credentials_body_text: $('#set-speaker-credential-body-text').val() || '',
                    speaker_credential_header_text: $('#set-speaker-credential-header-text').val() || '',
                    speaker_credential_button_text: $('#set-speaker-credential-button-text').val() || '',
                    speaker_credential_password_note: $('#set-speaker-credential-password-note').val() || '',
                    credential_footer_techcon_text: $('#set-footer-techcon-text').val() || '',
                    credential_footer_techcon_url: $('#set-footer-techcon-url').val() || '',
                    credential_footer_powered_by_text: $('#set-footer-powered-by-text').val() || '',
                    credential_footer_brilzen_text: $('#set-footer-brilzen-text').val() || '',
                    credential_footer_brilzen_url: $('#set-footer-brilzen-url').val() || ''
                }).then(() => {
                    $btn.text('Save Settings');
                    alert('Settings saved!');
                });
            });
        }).catch(err => alert(err));
    }

    /* ── Router ────────────────────────────────────────────── */
    if (page === 'tca-speakers') loadSpeakers();
    else if (page === 'tca-events') loadEvents();
    else if (page === 'tca-sessions') loadSessions();
    else if (page === 'tca-settings') loadSettings();
    else $app.html(renderHeader('Under Construction', '') + '<div class="tca-card">This tab will be fully functional when the TechCon Booking Pro plugin rebuild is complete.</div>');

})(jQuery);
