/* TechCon Agenda Pro — Frontend JS renderer
   Fetches agenda data via AJAX and renders pixel-perfect HTML
   matching the techcon socal agenda.html template structure.
   Also handles: brief popups, speaker tooltips, print modes.
*/
(function(){
'use strict';
const C=window.tcaAgenda;
if(!C||!C.eventId)return;
const root=document.getElementById('techcon-agenda-root');
const webRoot=document.getElementById('tc-web-agenda');
const printPortal=document.getElementById('techcon-print-portal');
if(!root||!webRoot)return;

let AGENDA=null;
let SHOW_MY_SESSIONS=false;

function ensurePrintPortalDirectChild(){
  if(!printPortal)return null;
  if(printPortal.parentNode!==document.body){
    document.body.appendChild(printPortal);
  }
  return printPortal;
}

/* ── Helpers ──────────────────────────────────────────── */
function esc(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}
function isCurrentSpeaker(sp){return !!(C.currentSpeakerId && sp && parseInt(sp.id||0,10)===parseInt(C.currentSpeakerId,10));}
function sessionHasCurrentSpeaker(session){return !!(session && (session.speakers||[]).some(isCurrentSpeaker));}
function getVisibleDays(){
  const days=(AGENDA&&AGENDA.days)||[];
  if(!SHOW_MY_SESSIONS||!C.currentSpeakerId)return days;
  return days.map(day=>({...day,sessions:(day.sessions||[]).filter(sessionHasCurrentSpeaker)})).filter(day=>(day.sessions||[]).length);
}
function filterLabel(){return SHOW_MY_SESSIONS?'My Sessions':'Full Agenda';}
function svgLi(){return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="var(--tc-pink)" class="tc-linkedin-icon"><path d="M16 8a6 6 0 016 6v7h-4v-7a2 2 0 00-2-2 2 2 0 00-2 2v7h-4v-7a6 6 0 016-6zM2 9h4v12H2z"/><circle cx="4" cy="4" r="2"/></svg>`;}
function svgPin(){return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>`;}
function svgCal(){return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>`;}
function svgPrintDay(){return`<svg class="tc-print-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><rect x="3.5" y="4.5" width="17" height="16" rx="3"/><path d="M8 2.5v4M16 2.5v4M3.5 9h17M8 13h2.5M13.5 13H16M8 17h2.5M13.5 17H16"/></svg>`;}
function svgPrintRoom(){return`<svg class="tc-print-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><path d="M4 20V6.5A2.5 2.5 0 0 1 6.5 4h11A2.5 2.5 0 0 1 20 6.5V20"/><path d="M8 20v-7.5A1.5 1.5 0 0 1 9.5 11h5a1.5 1.5 0 0 1 1.5 1.5V20M3 20h18"/><path d="M8 7.5h.01M12 7.5h.01M16 7.5h.01" stroke-linecap="round"/></svg>`;}
function accentByIndex(index){return index%2===0?'tc-accent-pink':'tc-accent-purple';}

/* ── Speaker card ─────────────────────────────────────── */
function speakerCard(sp){
  const role=esc([sp.position,sp.company].filter(Boolean).join(' · '));
  const initials=(sp.name||'?').split(' ').map(w=>w[0]).join('').toUpperCase().slice(0,2);
  const avatar=sp.image_url
    ?`<img src="${esc(sp.image_url)}" class="tc-speaker-avatar" alt="${esc(sp.name)}" loading="lazy">`
    :`<div class="tc-speaker-avatar" style="display:flex;align-items:center;justify-content:center;font-weight:900;font-size:.85rem;">${esc(initials)}</div>`;
  const li=sp.linkedin_url?`<a href="${esc(sp.linkedin_url)}" target="_blank" rel="noopener" title="LinkedIn" onclick="event.stopPropagation()">${svgLi()}</a>`:'';
  const nameLink=sp.profile_url
    ?`<a href="${esc(sp.profile_url)}" class="tc-speaker-name" target="_blank" rel="noopener">${esc(sp.name)}</a>`
    :`<span class="tc-speaker-name">${esc(sp.name)}</span>`;
  const tipImg=sp.image_url
    ?`<img src="${esc(sp.image_url)}" class="tc-tooltip-img" alt="${esc(sp.name)}" loading="lazy">`
    :`<div class="tc-tooltip-img" style="display:flex;align-items:center;justify-content:center;font-weight:900;font-size:2rem;">${esc(initials)}</div>`;
  return`<div class="tc-speaker-card">
    ${avatar}
    <div class="tc-speaker-details">
      <div class="tc-speaker-name-wrap">${nameLink}${li}</div>
      <div class="tc-speaker-role">${role}</div>
    </div>
    <div class="tc-tooltip">
      ${tipImg}
      ${sp.profile_url?`<a href="${esc(sp.profile_url)}" class="tc-tooltip-name" target="_blank">${esc(sp.name)}</a>`:`<div class="tc-tooltip-name">${esc(sp.name)}</div>`}
      <div class="tc-tooltip-role">${esc(sp.position||'')}</div>
      <div class="tc-tooltip-company">${esc(sp.company||'')}</div>
    </div>
  </div>`;
}

/* ── Session row ──────────────────────────────────────── */
function sessionRow(s,index){
  const speakers=(s.speakers||[]).map(speakerCard).join('');
  const briefBtn=s.brief?`<div class="tc-brief-wrap">
    <button class="tc-brief-btn" aria-label="Session details">📋 Session Details</button>
    <div class="tc-session-tip">
      <div class="tc-tip-kicker">${esc(s.session_type||'')}</div>
      <div class="tc-tip-title">${esc(s.title)}</div>
      ${s.brief?`<div class="tc-tip-desc">${esc(s.brief)}</div>`:''}
      <div class="tc-tip-meta">
        <div><b>Time</b>${esc(s.time_string||'')}</div>
        <div><b>Room</b>${esc(s.room||'')}</div>
        ${s.track?`<div><b>Track</b>${esc(s.track)}</div>`:''}
        ${s.session_code?`<div><b>Code</b>${esc(s.session_code)}</div>`:''}
      </div>
    </div>
  </div>`:'';
  return`<div class="tc-row ${accentByIndex(index||0)}">
    <div class="tc-cell"><div class="tc-time">${esc(s.time_string||'')}</div></div>
    <div class="tc-cell tc-cell-sep">
      <div class="tc-content-wrap">
        ${s.session_type?`<div class="tc-badge">${esc(s.session_type)}</div>`:''}
        <h3 class="tc-title">${esc(s.title)}</h3>
        ${s.track?`<div class="tc-track">${esc(s.track)}</div>`:''}
        ${speakers?`<div class="tc-speakers-group">${speakers}</div>`:''}
        ${briefBtn}
      </div>
    </div>
    <div class="tc-cell tc-cell-sep">
      ${s.room?`<div class="tc-loc-pill">${svgPin()} ${esc(s.room)}</div>`:''}
    </div>
  </div>`;
}

/* ── Day block ────────────────────────────────────────── */
function dayBlock(day){
  const rows=(day.sessions||[]).map((session,index)=>sessionRow(session,index)).join('');
  const dateFormatted=day.day_label||day.day_date||'';
  return`<div class="tc-day-block">
    <div class="tc-day-header">
      <div class="tc-day-date">${svgCal()} ${esc(dateFormatted)}</div>
      <h2>${esc(day.day_title||'')}</h2>
    </div>
    <div class="tc-grid-glass">
      <div class="tc-labels">
        <div class="tc-label-txt">Speakers</div>
        <div class="tc-label-txt">Session</div>
        <div class="tc-label-txt">Location</div>
      </div>
      ${rows}
    </div>
  </div>`;
}

/* ── Hero ─────────────────────────────────────────────── */
function heroHtml(ev){
  return`<div class="tc-hero">
    <div class="tc-hero-pill">
      <div class="tc-hero-pill-section">
        <span class="tc-hero-pill-icon">${svgCal()}</span>
        <span>${esc(ev.date_range||'')}</span>
      </div>
      <div class="tc-hero-pill-divider"></div>
      <div class="tc-hero-pill-section">
        <span class="tc-hero-pill-icon">${svgPin()}</span>
        <span>${esc(ev.venue||'')}${ev.address?', '+esc(ev.address):''}</span>
      </div>
    </div>
    <h1 class="tc-hero-title">${esc(ev.name||'')}</h1>
    ${ev.subtitle?`<h2 class="tc-hero-subtitle">${esc(ev.subtitle)}</h2>`:''}
    <div class="tc-btn-wrap">
      ${ev.cta_url?`<a href="${esc(ev.cta_url)}" class="tc-btn tc-btn-plasma">${esc(ev.cta_text||'Register Now')}</a>`:''}
    </div>
  </div>
  <div class="tc-print-toolbar">
    ${C.currentSpeakerId?`<button class="tc-print-btn tc-my-session-filter ${SHOW_MY_SESSIONS?'active':''}" id="tc-toggle-my-sessions" title="Show only agenda sessions where your speaker profile is assigned."><span>${SHOW_MY_SESSIONS?'Show Full Agenda':'My Sessions'}</span></button>`:''}
    <button class="tc-print-btn" id="tc-print-day" title="Print the ${C.currentSpeakerId?'current filtered ':''}agenda grouped by day.">${svgPrintDay()} <span>Print by Day</span></button>
    <button class="tc-print-btn" id="tc-print-room" title="Print the ${C.currentSpeakerId?'current filtered ':''}agenda grouped by room.">${svgPrintRoom()} <span>Print by Room</span></button>
  </div>`;
}

/* ── Main render ──────────────────────────────────────── */
function render(data){
  AGENDA=data;
  const ev=data.event;
  const days=getVisibleDays();
  const empty=SHOW_MY_SESSIONS && !days.length ? '<div class="tc-empty-filter-card"><h3>No assigned sessions found</h3><p>Your logged-in speaker profile is not assigned to any agenda sessions yet.</p></div>' : '';
  webRoot.innerHTML=heroHtml(ev)+empty+days.map(dayBlock).join('');
  attachEvents();
}

/* ── Events ───────────────────────────────────────────── */
function attachEvents(){
  // Brief toggle.
  root.querySelectorAll('.tc-brief-btn').forEach(btn=>{
    btn.addEventListener('click',function(e){
      e.stopPropagation();
      const row=this.closest('.tc-row');
      if(!row)return;
      const wasActive=row.classList.contains('brief-active');
      root.querySelectorAll('.tc-row.brief-active').forEach(r=>r.classList.remove('brief-active'));
      if(!wasActive)row.classList.add('brief-active');
    });
  });
  // Speaker tooltip on mobile (tap).
  if(window.innerWidth<=768){
    root.querySelectorAll('.tc-speaker-card').forEach(card=>{
      card.addEventListener('click',function(e){
        e.stopPropagation();
        const was=this.classList.contains('speaker-tip-active');
        root.querySelectorAll('.tc-speaker-card.speaker-tip-active').forEach(c=>c.classList.remove('speaker-tip-active'));
        if(!was)this.classList.add('speaker-tip-active');
      });
    });
  }
  // Close on outside click.
  document.addEventListener('click',()=>{
    root.querySelectorAll('.tc-row.brief-active').forEach(r=>r.classList.remove('brief-active'));
    root.querySelectorAll('.tc-speaker-card.speaker-tip-active').forEach(c=>c.classList.remove('speaker-tip-active'));
  });
  // Speaker filter + print buttons.
  document.getElementById('tc-toggle-my-sessions')?.addEventListener('click',()=>{SHOW_MY_SESSIONS=!SHOW_MY_SESSIONS; render(AGENDA);});
  document.getElementById('tc-print-day')?.addEventListener('click',()=>buildPrint('day'));
  document.getElementById('tc-print-room')?.addEventListener('click',()=>buildPrint('room'));
}

/* ── Print engine ─────────────────────────────────────── */
function populatePrint(mode){
  if(!AGENDA)return;
  const portal=ensurePrintPortalDirectChild();
  if(!portal)return;
  const ev=AGENDA.event||{};
  const days=getVisibleDays();
  portal.className=mode==='room'?'room-mode':'';

  let html=`<div class="p-header"><h1>${esc(ev.name||'Agenda')} ${SHOW_MY_SESSIONS?'— My Sessions':''}</h1><p>${esc(ev.date_range||'')} · ${esc(ev.venue||'')} · ${esc(ev.address||'')}</p></div>`;

  if(mode==='day'){
    days.forEach(day=>{
      const sessions=day.sessions||[];
      if(!sessions.length)return;
      html+=`<div class="p-day-title"><span>${esc(day.day_label||day.day_date||'')}</span><span>${esc(day.day_title||'')}</span></div>`;
      html+=`<table class="p-table"><thead><tr><th class="p-time">Time</th><th>Session</th><th class="p-loc">Location</th></tr></thead><tbody>`;
      sessions.forEach(s=>{
        const speakers=(s.speakers||[]).map(sp=>`<li>${esc(sp.name)}${sp.position?` — ${esc(sp.position)}`:''}${sp.company?`, ${esc(sp.company)}`:''}</li>`).join('');
        html+=`<tr><td class="p-time">${esc(s.time_string||'')}</td>
          <td>${s.session_type?`<span class="p-type">${esc(s.session_type)}</span> `:''}
          <span class="p-title">${esc(s.title)}</span>
          ${s.track?`<div class="p-track">${esc(s.track)}</div>`:''}
          ${s.brief?`<div class="p-desc">${esc(s.brief)}</div>`:''}
          ${speakers?`<ul class="p-speakers">${speakers}</ul>`:''}</td>
          <td class="p-loc">${esc(s.room||'')}</td></tr>`;
      });
      html+=`</tbody></table>`;
    });
  } else {
    const byRoom={};
    days.forEach(day=>{
      (day.sessions||[]).forEach(s=>{
        const r=s.room||'(No Room)';
        if(!byRoom[r])byRoom[r]=[];
        byRoom[r].push({...s,_day_label:day.day_label||day.day_date||''});
      });
    });
    Object.keys(byRoom).sort().forEach(room=>{
      const sessions=byRoom[room];
      html+=`<div class="p-room-block"><div class="p-room-heading">${esc(room)}</div>`;
      html+=`<table class="p-table"><thead><tr><th class="p-time">Time</th><th class="p-loc">Day</th><th>Session</th></tr></thead><tbody>`;
      sessions.forEach(s=>{
        const speakers=(s.speakers||[]).map(sp=>`<li>${esc(sp.name)}${sp.position?` — ${esc(sp.position)}`:''}${sp.company?`, ${esc(sp.company)}`:''}</li>`).join('');
        html+=`<tr><td class="p-time">${esc(s.time_string||'')}</td>
          <td class="p-loc" style="font-size:7.5pt;">${esc(s._day_label)}</td>
          <td>${s.session_type?`<span class="p-type">${esc(s.session_type)}</span> `:''}
          <span class="p-title">${esc(s.title)}</span>
          ${s.track?`<div class="p-track">${esc(s.track)}</div>`:''}
          ${s.brief?`<div class="p-desc">${esc(s.brief)}</div>`:''}
          ${speakers?`<ul class="p-speakers">${speakers}</ul>`:''}</td></tr>`;
      });
      html+=`</tbody></table></div>`;
    });
  }
  portal.innerHTML=html;
}

function buildPrint(mode){
  populatePrint(mode||'day');
  setTimeout(()=>window.print(),100);
}

window.addEventListener('beforeprint',()=>{
  const portal=ensurePrintPortalDirectChild();
  if(AGENDA && portal && !portal.innerHTML.trim())populatePrint('day');
});

/* ── Fetch ────────────────────────────────────────────── */
const fd=new FormData();
fd.append('action','tca_get_agenda');
fd.append('event_id',C.eventId);
fetch(C.ajaxUrl,{method:'POST',body:fd})
  .then(r=>r.json())
  .then(res=>{
    if(res.success)render(res.data);
    else webRoot.innerHTML='<p style="color:#e61a84;text-align:center;">'+esc(res.data?.message||'Failed to load agenda.')+'</p>';
  })
  .catch(()=>{webRoot.innerHTML='<p style="color:#e61a84;text-align:center;">Network error loading agenda.</p>';});

}());
