/* TechCon Booking Pro — Speaker Dashboard JS */
(function () {
  'use strict';
  const D = window.tcbDashboard;
  const SIMPLE_MODE = (D.bookingMode || 'simple') === 'simple';
  const root = document.getElementById('tcb-speaker-dashboard');
  if (!root || !D) return;
  const mode = root.dataset.mode;
  function esc(s){ return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
  function statusLabel(st){ if(SIMPLE_MODE){ return ({pending:'Request Sent',approved:'Booked',reserved:'Unavailable',disabled:'Unavailable',available:'Available',declined:'Rejected',cancelled:'Request Removed'})[st] || st || '—'; } return ({pending:'Pending Review',approved:'Booked',reserved:'Reserved',disabled:'Unavailable',available:'Available',declined:'Declined',cancelled:'Withdrawn'})[st] || st || '—'; }
  function post(action, data) {
    const fd = new FormData(); fd.append('action', action); fd.append('nonce', D.nonce);
    Object.entries(data||{}).forEach(([k,v]) => fd.append(k, v));
    return fetch(D.ajaxUrl, { method:'POST', body: fd }).then(r => r.json());
  }
  function notice(container, msg, type) {
    if (!container) return; const el = document.createElement('div');
    el.className = 'tcb-notice tcb-notice-' + (type||'info'); el.textContent = msg;
    const existing = container.querySelector('.tcb-notice'); if (existing) existing.remove(); container.prepend(el);
  }

  if (mode === 'wall') {
    root.innerHTML = `<div class="tcb-auth-wrap" style="text-align:center;"><div class="tcb-auth-logo"><div class="brand">⚡ ${esc(D.eventLabel || 'TechCon SoCal 2026')}</div><h1>Speaker Portal</h1></div><div class="tcb-auth-wall"><h2>Sign In to Access Your Dashboard</h2><p>Speaker accounts are created by TechCon admin only.</p><div class="tcb-auth-wall-btns"><a href="${esc(root.dataset.login || D.loginUrl)}" class="tcb-btn-outline">Sign In</a></div></div></div>`;
    return;
  }

  if (mode === 'register') {
    root.innerHTML = `<div class="tcb-auth-wrap"><div class="tcb-auth-logo"><div class="brand">⚡ ${esc(D.eventLabel || 'TechCon SoCal 2026')}</div><h1>Speaker Portal</h1></div><div class="tcb-auth-card"><h2>Registration Closed</h2><p>New speakers cannot self-register. Speaker and media partner accounts are created by TechCon admin only.</p><a class="tcb-btn-full" href="${esc(D.loginUrl || '/speaker-login/')}">Back to Login</a></div></div>`;
    return;
  }

  if (mode === 'login') {
    const isPartnerLogin = (root.dataset.role === 'partner') || D.loginRole === 'partner';
    const portalTitle = isPartnerLogin ? 'Media Partner Portal' : 'Speaker / Partner Portal';
    const helpText = isPartnerLogin ? 'Only admin-created media partners can sign in to manage interview requests and slots.' : 'Only admin-created speakers and media partners can sign in.';
    root.innerHTML = `<div class="tcb-auth-wrap"><div class="tcb-auth-logo"><div class="brand">⚡ ${esc(D.eventLabel || 'TechCon SoCal 2026')}</div><h1>${portalTitle}</h1></div><div class="tcb-auth-card"><h2>👋 Welcome Back</h2><div id="login-notice"></div><p style="color:rgba(240,240,255,.55);font-size:13px;">${helpText}</p><div class="tcb-fg"><label>Email or Username</label><input id="l-email" type="text" autocomplete="username" placeholder="partner@company.com"></div><div class="tcb-fg"><label>Password</label><input id="l-pass" type="password" placeholder="••••••••"></div><button id="l-submit" class="tcb-btn-full">Sign In →</button></div></div>`;
    document.getElementById('l-submit').addEventListener('click', function() {
      const btn = this; btn.disabled = true; btn.textContent = 'Signing in…';
      post('tcb_speaker_login', { email: document.getElementById('l-email').value, password: document.getElementById('l-pass').value, role: isPartnerLogin ? 'partner' : 'speaker' }).then(res => {
        if (res.success) window.location.href = res.data.redirect;
        else { notice(document.getElementById('login-notice'), (res.data && res.data.message) || 'Invalid credentials.', 'error'); btn.disabled = false; btn.textContent = 'Sign In →'; }
      }).catch(()=>{ notice(document.getElementById('login-notice'), 'Network error. Please try again.', 'error'); btn.disabled = false; btn.textContent = 'Sign In →'; });
    });
    return;
  }

  if (mode === 'dashboard' && D.loggedIn) {
    const p = D.profile || {};
    const profileUrl = p.profile_url || (D.profileBase + (p.slug || '') + '/');
    root.innerHTML = `<div class="tcb-dash-page"><div class="tcb-dash-header"><div class="tcb-dash-header-left"><div class="greeting">⚡ ${esc(D.eventLabel || 'TechCon SoCal 2026')} — Speaker Dashboard</div><h1>Hello, ${esc(p.name || 'Speaker')} 👋</h1><p style="color:rgba(240,240,255,.55);font-size:13px;margin:6px 0 0;">View your interview schedule and request available media slots.</p></div><div class="tcb-dash-header-right"><a href="${esc(profileUrl)}" class="tcb-btn-sm-ghost" target="_blank">View Profile</a><button class="tcb-btn-sm-ghost" id="tcb-logout-btn">Sign Out</button></div></div><div class="tcb-dash-tabs"><button class="tcb-dash-tab active" data-tab="bookings">📅 My Bookings</button><button class="tcb-dash-tab" data-tab="partners">🎙️ Book Interviews</button><button class="tcb-dash-tab" data-tab="account">🔐 Change Password</button></div><div class="tcb-dash-panel" id="tab-bookings"><div class="tcb-dash-card"><h2>${SIMPLE_MODE ? 'My Interview Requests' : 'My Interview Bookings'}</h2>${renderBookings()}</div><div id="tcb-speaker-chat-panel" class="tcb-dash-card tcb-chat-card" style="display:none;"></div></div><div class="tcb-dash-panel" id="tab-partners" style="display:none;"><div class="tcb-dash-card"><h2>Available Media Partners</h2><p style="color:rgba(240,240,255,.5);font-size:13px;margin-bottom:20px;">Click a partner to visit their booking page and request your interview slot.</p>${renderPartnersGrid()}</div></div><div class="tcb-dash-panel" id="tab-account" style="display:none;"><div class="tcb-dash-card" style="max-width:680px;"><h2>Change Password</h2><p style="color:rgba(240,240,255,.55);font-size:13px;">For security, enter your current password before setting a new one.</p><div id="password-notice"></div><div class="tcb-form-row"><div class="tcb-fg"><label>Current Password</label><input id="pw-current" type="password" autocomplete="current-password"></div></div><div class="tcb-form-row"><div class="tcb-fg"><label>New Password</label><input id="pw-new" type="password" autocomplete="new-password"></div><div class="tcb-fg"><label>Confirm New Password</label><input id="pw-confirm" type="password" autocomplete="new-password"></div></div><button id="pw-save" class="tcb-btn-full" style="width:auto;padding:12px 32px;">Change Password</button></div></div></div>`;
    root.querySelectorAll('.tcb-dash-tab').forEach(btn => btn.addEventListener('click', function(){ root.querySelectorAll('.tcb-dash-tab').forEach(t=>t.classList.remove('active')); root.querySelectorAll('.tcb-dash-panel').forEach(p=>p.style.display='none'); this.classList.add('active'); document.getElementById('tab-'+this.dataset.tab).style.display='block'; }));
    document.getElementById('tcb-logout-btn').addEventListener('click', () => post('tcb_speaker_logout', {}).then(res => { if (res.success) window.location.href = res.data.redirect; }));
    root.querySelectorAll('.tcb-open-chat').forEach(btn => btn.addEventListener('click', function(){ openSpeakerChat(this.dataset.slotId); }));
    root.querySelectorAll('.tcb-withdraw-booking').forEach(btn => btn.addEventListener('click', function(){
      if(!confirm('Withdraw this interview request? The slot will be released.')) return;
      const slotId=this.dataset.slotId;
      this.disabled=true; this.textContent='Withdrawing…';
      post('tcb_cancel_slot', { slot_id: slotId, speaker_id: (D.profile && D.profile.id) || 0 }).then(res=>{
        if(res.success) window.location.reload();
        else { alert((res.data&&res.data.message)||'Unable to withdraw request.'); this.disabled=false; this.textContent='Withdraw'; }
      }).catch(()=>{ alert('Network error. Please try again.'); this.disabled=false; this.textContent='Withdraw'; });
    }));
    document.getElementById('pw-save')?.addEventListener('click', function(){
      const btn=this; btn.disabled=true; btn.textContent='Changing…';
      post('tcb_change_speaker_password', { current_password: document.getElementById('pw-current')?.value || '', new_password: document.getElementById('pw-new')?.value || '', confirm_password: document.getElementById('pw-confirm')?.value || '' }).then(res => {
        notice(document.getElementById('password-notice'), (res.data && res.data.message) || (res.success?'Password changed.':'Error.'), res.success?'success':'error');
        btn.disabled=false; btn.textContent='Change Password';
        if (res.success) { ['pw-current','pw-new','pw-confirm'].forEach(id=>{ const el=document.getElementById(id); if(el) el.value=''; }); }
      }).catch(()=>{ notice(document.getElementById('password-notice'), 'Network error. Please try again.', 'error'); btn.disabled=false; btn.textContent='Change Password'; });
    });
  }

  function renderBookings() {
    const bookings = D.bookings || [];
    if (!bookings.length) return '<div class="tcb-dash-empty">You haven\'t booked any interviews yet. Go to "Book Interviews" to get started.</div>';
    return '<div class="tcb-booking-list">' + bookings.map(b => {
      const canWithdraw = !SIMPLE_MODE && b.status === 'pending';
      const visibleStatus = SIMPLE_MODE ? statusLabel(b.status) : statusLabel(b.status);
      const rebookNote = (!SIMPLE_MODE && b.status === 'declined' && String(b.allow_rebook||'0') === '1') ? '<div class="slot-info">You may choose another available slot for this partner/day.</div>' : ''; 
      return `<div class="tcb-booking-item"><div class="tcb-booking-bar" style="background:${esc(b.partner_color||'#e61a84')}"></div><div class="tcb-booking-main"><div class="partner-name">${b.partner_logo ? `<img src="${esc(b.partner_logo)}" style="height:20px;object-fit:contain;vertical-align:middle;margin-right:6px;">` : ''}${esc(b.partner_name)}</div><div class="slot-info">📅 ${esc(b.event_day)} &nbsp;🕐 ${esc((b.start_time||'').slice(0,5))} – ${esc((b.end_time||'').slice(0,5))}</div>${rebookNote}</div><div class="tcb-booking-actions"><span class="tcb-booking-status ${esc(b.status)}">${esc(visibleStatus)}</span>${(b.status==='approved' && D.chatEnabled) ? `<button type="button" class="tcb-btn-sm-ghost tcb-open-chat" data-slot-id="${esc(b.id)}">Chat</button>` : ''}${canWithdraw ? `<button type="button" class="tcb-btn-sm-ghost tcb-withdraw-booking" data-slot-id="${esc(b.id)}">Withdraw</button>` : ''}</div></div>`;
    }).join('') + '</div>';
  }

  function renderChatMessages(messages){
    if(!messages || !messages.length) return '<div class="tcb-dash-empty">No messages yet. Start the conversation.</div>';
    return messages.map(m=>`<div class="tcb-chat-msg ${m.mine?'mine':'theirs'}"><div class="tcb-chat-meta">${esc(m.sender_name||m.sender_role)} · ${esc((m.created_at||'').slice(0,16))}</div><div class="tcb-chat-bubble">${esc(m.message)}</div></div>`).join('');
  }
  let chatTimer = null;
  function refreshSpeakerChat(slotId){
    post('tcb_get_chat', {slot_id:slotId}).then(res=>{
      const thread=document.getElementById('tcb-speaker-chat-thread');
      if(!thread) return;
      if(res.success){ thread.innerHTML=renderChatMessages(res.data.messages||[]); thread.scrollTop=thread.scrollHeight; }
      else thread.innerHTML='<div class="tcb-dash-empty">'+esc((res.data&&res.data.message)||'Chat unavailable.')+'</div>';
    });
  }
  function openSpeakerChat(slotId){
    const panel=document.getElementById('tcb-speaker-chat-panel');
    if(!panel) return;
    if(chatTimer) clearInterval(chatTimer);
    panel.style.display='block';
    panel.innerHTML=`<div class="tcb-chat-head"><h2>Booking Chat</h2><button type="button" class="tcb-btn-sm-ghost" id="tcb-close-chat">Close</button></div><div id="tcb-speaker-chat-thread" class="tcb-chat-thread">Loading…</div><div class="tcb-chat-compose"><textarea id="tcb-speaker-chat-message" placeholder="Write a message..." rows="3"></textarea><button type="button" class="tcb-btn-full" id="tcb-speaker-chat-send">Send</button></div><p class="tcb-chat-note">Chat becomes available only after your request is approved.</p>`;
    refreshSpeakerChat(slotId);
    chatTimer=setInterval(()=>refreshSpeakerChat(slotId),6000);
    document.getElementById('tcb-close-chat').addEventListener('click',()=>{ panel.style.display='none'; if(chatTimer) clearInterval(chatTimer); });
    document.getElementById('tcb-speaker-chat-send').addEventListener('click',()=>{
      const msg=document.getElementById('tcb-speaker-chat-message').value;
      post('tcb_send_chat',{slot_id:slotId,message:msg}).then(res=>{
        if(res.success){ document.getElementById('tcb-speaker-chat-message').value=''; document.getElementById('tcb-speaker-chat-thread').innerHTML=renderChatMessages(res.data.messages||[]); }
        else notice(panel,(res.data&&res.data.message)||'Unable to send message.','error');
      });
    });
    panel.scrollIntoView({behavior:'smooth',block:'start'});
  }

  function renderPartnersGrid() {
    const partners = (D.partners || []).filter(p => (p.status || 'active') === 'active');
    return '<div class="tcb-partners-dash-grid">' + partners.map(p => {
      return `<a href="${esc((D.bookingBase || '/book/') + encodeURIComponent(p.slug) + '/')}" class="tcb-partner-dash-card" style="--pc:${esc(p.color || '#e61a84')}">${p.logo_url ? `<img src="${esc(p.logo_url)}" alt="${esc(p.name)}">` : `<div style="width:52px;height:52px;border-radius:12px;background:${esc(p.color || '#e61a84')};display:flex;align-items:center;justify-content:center;font-weight:800;color:#fff;font-size:1.2rem;">${esc((p.name||'?')[0])}</div>`}<div class="p-name">${esc(p.name)}</div><div class="p-avail">${p.booking_open=='1' ? 'View available days →' : '🔒 Closed'}</div></a>`;
    }).join('') + '</div>';
  }
}());
