<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/crm_shared.php';

if (session_status() !== PHP_SESSION_ACTIVE) session_start();

$cfg = $config ?? eaq_load_config();
$baseUrl = $cfg['base_url'] ?? eaq_base_url();
$lang = $cfg['lang'] ?? 'pt-BR';

// Export CRM snapshot (mock) as JSON (admin not required).
if (!empty($_GET['export']) && $_GET['export'] === 'crm') {
  $crm = eaq_load_crm_snapshot();
  header('Content-Type: application/json; charset=utf-8');
  header('Content-Disposition: attachment; filename="crm_snapshot.json"');
  echo json_encode($crm, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  exit;
}

// Load CRM snapshot (mock/local).
$crm = eaq_load_crm_snapshot();

// Handle admin actions: toggle follow-up completion + save manager notes.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($cfg['enable_admin_actions'] ?? true)) {
  $action = (string)($_POST['action'] ?? '');

  if ($action === 'toggle_followup') {
    if (!eaq_is_installed()) eaq_redirect($baseUrl . '/install/');
    eaq_require_admin($cfg);

    $followupId = (string)($_POST['followup_id'] ?? '');
    $toggled = false;
    foreach (($crm['followups'] ?? []) as &$fu) {
      if (($fu['Id'] ?? '') === $followupId) {
        $fu['IsCompleted'] = !($fu['IsCompleted'] ?? false);
        $toggled = true;
        break;
      }
    }
    unset($fu);
    if ($toggled) {
      eaq_write_json('mock_crm.json', $crm);
      $notice = 'Follow-up atualizado.';
    } else {
      $error = 'Follow-up não encontrado.';
    }
  }

  if ($action === 'save_manager_notes') {
    if (!eaq_is_installed()) eaq_redirect($baseUrl . '/install/');
    eaq_require_admin($cfg);

    $text = trim((string)($_POST['manager_note_text'] ?? ''));
    if ($text !== '') {
      $notes = eaq_load_manager_notes();
      if (!is_array($notes)) $notes = [];
      $notes[] = [
        'id' => uniqid('note_', true),
        'text' => $text,
        'createdAt' => gmdate('c'),
      ];
      eaq_save_manager_notes($notes);
      $notice = 'Nota salva.';
    } else {
      $error = 'Nota vazia.';
    }
  }

  if ($action === 'create_opportunity') {
    if (!eaq_is_installed()) eaq_redirect($baseUrl . '/install/');
    eaq_require_admin($cfg);

    $title = trim((string)($_POST['opp_title'] ?? ''));
    $leadId = trim((string)($_POST['opp_lead_id'] ?? ''));
    $value = trim((string)($_POST['opp_value'] ?? ''));
    $stage = trim((string)($_POST['opp_stage'] ?? 'NewLead'));

    if ($title === '' || $leadId === '') {
      $error = 'Informe título e lead.';
    } else {
      $valueNum = is_numeric($value) ? (float)$value : 0.0;

      // Use only stages supported by the pipeline mapping.
      $allowedStages = ['NewLead', 'Contacted', 'ProposalSent', 'FollowUp', 'ReadyToClose', 'QuestSessionDone', 'Won', 'Lost'];
      if (!in_array($stage, $allowedStages, true)) $stage = 'NewLead';

      $newOppId = 'opp-' . uniqid('', true);
      $crm['opportunities'][] = [
        'Id' => $newOppId,
        'LeadId' => $leadId,
        'Title' => $title,
        'Stage' => $stage,
        'Value' => $valueNum,
        'ProposalRecordId' => null,
        'SessionRecordId' => null,
        'CommercialPriority' => 'Low',
        'SuggestedNextAction' => 'Qualificar e avançar etapa',
        'CreatedAt' => gmdate('c'),
        'UpdatedAt' => gmdate('c'),
      ];

      // Seed an open follow-up to make the dashboard actionable.
      $crm['followups'][] = [
        'Id' => 'fu-' . uniqid('', true),
        'OpportunityId' => $newOppId,
        'SessionRecordId' => null,
        'Title' => 'Próximo passo (follow-up inicial)',
        'DueDate' => gmdate('c', time() + 2 * 86400),
        'Priority' => 'Medium',
        'IsCompleted' => false,
        'CreatedAt' => gmdate('c'),
      ];

      eaq_write_json('mock_crm.json', $crm);

      $redirSection = (string)($_GET['section'] ?? 'executive');
      $redirQ = trim((string)($_GET['q'] ?? ''));
      $redir = $baseUrl . '/app/?section=' . rawurlencode($redirSection);
      if ($redirQ !== '') $redir .= '&q=' . rawurlencode($redirQ);
      eaq_redirect($redir);
    }
  }
}

$now = new DateTimeImmutable('now', new DateTimeZone('UTC'));

$leads = $crm['leads'] ?? [];
$opps = $crm['opportunities'] ?? [];
$sessions = $crm['sessions'] ?? [];
$followups = $crm['followups'] ?? [];

$leadById = [];
foreach ($leads as $l) {
  $id = (string)($l['Id'] ?? '');
  if ($id !== '') $leadById[$id] = $l;
}

$oppById = [];
foreach ($opps as $o) {
  $id = (string)($o['Id'] ?? '');
  if ($id !== '') $oppById[$id] = $o;
}

// Search filter for pipeline/actions (server-side).
$q = trim((string)($_GET['q'] ?? ''));
if ($q === '') $q = '';

$matchesQuery = function (string $haystack, string $needle): bool {
  if ($needle === '') return true;
  return stripos($haystack, $needle) !== false;
};

// Helper: pick the first open follow-up (earliest due) for an opportunity.
$firstOpenFollowupForOpp = function (array $crmLocal, string $opportunityId) use ($now): ?array {
  $best = null; // ['fu' => array, 'due' => DateTimeImmutable]
  foreach ($crmLocal['followups'] ?? [] as $fu) {
    if (!empty($fu['IsCompleted'])) continue;
    if (($fu['OpportunityId'] ?? '') !== $opportunityId) continue;

    $due = eaq_parse_utc_iso((string)($fu['DueDate'] ?? ''));
    if ($due === null) continue;
    if ($best === null || $due < $best['due']) {
      $best = ['fu' => $fu, 'due' => $due];
    }
  }
  return $best['fu'] ?? null;
};

// Counts for KPI cards.
$counts = [
  'leads_total' => count($leads),
  'opps_total' => count($opps),
  'sessions_total' => count($sessions),
  'followups_open' => 0,
  'followups_done' => 0,
];
foreach ($followups as $fu) {
  if (!empty($fu['IsCompleted'])) $counts['followups_done']++;
  else $counts['followups_open']++;
}

// Manager notes (drawer).
$managerNotes = eaq_load_manager_notes();
if (!is_array($managerNotes)) $managerNotes = [];
$latestNote = $managerNotes ? $managerNotes[count($managerNotes) - 1] : null;
$latestNoteText = is_array($latestNote) ? (string)($latestNote['text'] ?? '') : '';

// KPI: pipeline active value + progress.
$pipelineActiveValue = 0.0;
$pipelineTotalValue = 0.0;
$pipelineWonValue = 0.0;
foreach ($opps as $o) {
  $value = is_numeric($o['Value'] ?? null) ? (float)$o['Value'] : 0.0;
  $pipelineTotalValue += $value;
  if (eaq_stage_is_closed($o['Stage'] ?? null)) {
    if (($o['Stage'] ?? '') === 'Won') $pipelineWonValue += $value;
  } else {
    $pipelineActiveValue += $value;
  }
}
$pipelineProgress = $pipelineTotalValue > 0 ? (int)round(($pipelineWonValue / $pipelineTotalValue) * 100) : 0;

// KPI: Sessões Quest + conversion estimate.
$questSessionsCount = 0;
$questConvertedCount = 0;
foreach ($sessions as $s) {
  if (!empty($s['SessionId'])) {
    $questSessionsCount++;
    $final = (string)($s['FinalDecisionState'] ?? '');
    if ($final !== '' && $final !== 'Unknown') $questConvertedCount++;
  }
}
$questConversion = $questSessionsCount > 0 ? (int)round(($questConvertedCount / $questSessionsCount) * 100) : 0;

// KPI: readiness average across sessions.
$readinessSum = 0;
$readinessN = 0;
foreach ($sessions as $s) {
  $readinessSum += eaq_compute_readiness_percent_from_session($s);
  $readinessN++;
}
$readinessAvg = $readinessN > 0 ? (int)round($readinessSum / $readinessN) : 0;

// KPI: follow-ups pending/urgent.
$urgentFollowups = [];
foreach ($followups as $fu) {
  if (!empty($fu['IsCompleted'])) continue;
  $prio = (string)($fu['Priority'] ?? '');
  $due = eaq_parse_utc_iso((string)($fu['DueDate'] ?? ''));
  if ($due !== null && $due < $now) $urgentFollowups[] = $fu;
  else if (in_array($prio, ['Urgent', 'High'], true)) $urgentFollowups[] = $fu;
}
$urgentFollowupsCount = count($urgentFollowups);

// Build pipeline board columns.
$columns = [
  'Leads Qualificados' => ['key' => 'qualified', 'accent' => 'var(--accent-primary)'],
  'Proposta Enviada' => ['key' => 'proposal_sent', 'accent' => 'var(--accent-vr)'],
  'Negociação' => ['key' => 'negotiation', 'accent' => 'var(--success)'],
  'Sessão Quest' => ['key' => 'quest_session', 'accent' => 'var(--accent-vr)'],
  'Fechamento' => ['key' => 'closing', 'accent' => 'var(--success)'],
];

$colOpps = [];
foreach ($columns as $colName => $_meta) $colOpps[$colName] = [];

foreach ($opps as $o) {
  $leadId = (string)($o['LeadId'] ?? '');
  $lead = $leadById[$leadId] ?? null;
  $company = is_array($lead) ? (string)($lead['Company'] ?? '') : '';
  $clientText = trim(($company !== '' ? $company : (string)($lead['Name'] ?? '')));
  $oppText = (string)($o['Title'] ?? '');
  $stage = (string)($o['Stage'] ?? '');

  if (!$matchesQuery($clientText . ' ' . $oppText . ' ' . $stage, $q)) continue;

  // Column mapping based on mock stage.
  $targetCol = null;
  if ($stage === 'NewLead' || $stage === 'Contacted') $targetCol = 'Leads Qualificados';
  else if ($stage === 'ProposalSent') $targetCol = 'Proposta Enviada';
  else if ($stage === 'FollowUp' || $stage === 'ReadyToClose') $targetCol = 'Negociação';
  else if ($stage === 'QuestSessionDone') $targetCol = 'Sessão Quest';
  else if ($stage === 'Won') $targetCol = 'Fechamento';

  if ($targetCol === null) continue;

  $follow = $firstOpenFollowupForOpp($crm, (string)($o['Id'] ?? ''));
  $dueDt = null;
  $dueLabel = '—';
  $isOverdue = false;
  $isUrgent = false;
  if (is_array($follow)) {
    $dueDt = eaq_parse_utc_iso((string)($follow['DueDate'] ?? ''));
    if ($dueDt !== null) {
      $dueLabel = eaq_relative_due_label($dueDt, $now);
      $isOverdue = $dueDt < $now;
    }
    $followPriority = (string)($follow['Priority'] ?? '');
    $isUrgent = $isOverdue || in_array($followPriority, ['Urgent', 'High'], true);
  }

  $commercialPriority = (string)($o['CommercialPriority'] ?? '');
  $tagType = null;
  if ($isUrgent) $tagType = 'urgent';
  else if ($stage === 'QuestSessionDone' || in_array($commercialPriority, ['High', 'Critical'], true)) $tagType = 'quest';

  $colOpps[$targetCol][] = [
    'opp' => $o,
    'lead' => $lead,
    'company' => $clientText,
    'dueLabel' => $dueLabel,
    'tagType' => $tagType,
    'isUrgent' => $isUrgent,
    'value' => is_numeric($o['Value'] ?? null) ? (float)$o['Value'] : 0.0,
  ];
}

// Recommended actions: open follow-ups ordered by due date.
$openFollowups = [];
foreach ($followups as $fu) {
  if (!empty($fu['IsCompleted'])) continue;
  $oppId = (string)($fu['OpportunityId'] ?? '');
  $opp = $oppById[$oppId] ?? null;
  $leadId = $opp ? (string)($opp['LeadId'] ?? '') : '';
  $lead = $leadById[$leadId] ?? null;

  $company = is_array($lead) ? (string)($lead['Company'] ?? '') : '';
  $oppTitle = is_array($opp) ? (string)($opp['Title'] ?? '') : '';
  $fuTitle = (string)($fu['Title'] ?? '');

  if (!$matchesQuery($fuTitle . ' ' . $company . ' ' . $oppTitle, $q)) continue;

  $dueDt = eaq_parse_utc_iso((string)($fu['DueDate'] ?? ''));
  $openFollowups[] = ['fu' => $fu, 'opp' => $opp, 'due' => $dueDt];
}

usort($openFollowups, function ($a, $b) {
  $da = $a['due'] instanceof DateTimeImmutable ? $a['due']->getTimestamp() : PHP_INT_MAX;
  $db = $b['due'] instanceof DateTimeImmutable ? $b['due']->getTimestamp() : PHP_INT_MAX;
  return $da <=> $db;
});

$recommended = array_slice($openFollowups, 0, 4);

// Events Ativos: sessions ordered by readiness.
$sessionsWithReadiness = [];
foreach ($sessions as $s) {
  $sessionsWithReadiness[] = ['s' => $s, 'r' => eaq_compute_readiness_percent_from_session($s)];
}
usort($sessionsWithReadiness, fn($a, $b) => $b['r'] <=> $a['r']);
$eventsAtivos = array_slice($sessionsWithReadiness, 0, 3);

// Next session quest: earliest open follow-up that is tied to a session.
$nextSessionFollowup = null;
$nextSessionFollowupDue = null;
foreach ($openFollowups as $item) {
  $fu = $item['fu'];
  if (empty($fu['SessionRecordId'])) continue;
  $due = $item['due'];
  if ($due === null) continue;
  if ($nextSessionFollowupDue === null || $due < $nextSessionFollowupDue) {
    $nextSessionFollowup = $fu;
    $nextSessionFollowupDue = $due;
  }
}
if ($nextSessionFollowup === null && count($openFollowups) > 0) {
  $nextSessionFollowup = $openFollowups[0]['fu'];
  $nextSessionFollowupDue = $openFollowups[0]['due'];
}

$nextOpp = null;
$nextLead = null;
$nextOppValue = 0.0;
if (is_array($nextSessionFollowup)) {
  $nextOppId = (string)($nextSessionFollowup['OpportunityId'] ?? '');
  $nextOpp = $oppById[$nextOppId] ?? null;
  $nextLeadId = $nextOpp ? (string)($nextOpp['LeadId'] ?? '') : '';
  $nextLead = $leadById[$nextLeadId] ?? null;
  $nextOppValue = $nextOpp && is_numeric($nextOpp['Value'] ?? null) ? (float)$nextOpp['Value'] : 0.0;
}

// Watchlist risks: top 2 urgent/overdue open follow-ups.
$watchlistCandidates = [];
foreach ($openFollowups as $item) {
  $fu = $item['fu'];
  $due = $item['due'];
  $prio = (string)($fu['Priority'] ?? '');
  $overdue = $due instanceof DateTimeImmutable ? $due < $now : false;
  $isRisk = $overdue || in_array($prio, ['Urgent', 'High'], true);
  if (!$isRisk) continue;
  $watchlistCandidates[] = $item;
}

usort($watchlistCandidates, function ($a, $b) {
  $da = $a['due'] instanceof DateTimeImmutable ? $a['due']->getTimestamp() : PHP_INT_MAX;
  $db = $b['due'] instanceof DateTimeImmutable ? $b['due']->getTimestamp() : PHP_INT_MAX;
  return $da <=> $db;
});
$watchlist = array_slice($watchlistCandidates, 0, 2);

$watchRiskCount = count($watchlistCandidates);

// Simple views for tabs (client-side).
$activeNav = (string)($_GET['section'] ?? 'executive');
if ($activeNav === '') $activeNav = 'executive';

$sectionTitles = [
  'executive' => 'Visão Executiva',
  'indicadores' => 'Indicadores',
  'snapshots' => 'Snapshots',
  'pipeline' => 'Pipeline',
  'opps' => 'Oportunidades',
  'leads' => 'Leads',
  'quest-sessions' => 'Sessões Quest',
  'handoff' => 'Handoff',
  'checklist' => 'Checklist',
  'execucao' => 'Execução',
  'watchlist' => 'Watchlist',
  'decisoes' => 'Decisões',
];
$pageTitle = $sectionTitles[$activeNav] ?? 'Visão Executiva';

$pipelineListView = '';
$pipelineAnalysisView = '';

$createOppMode = (!empty($_GET['create_opp']) && $_GET['create_opp'] === '1');

?>
<!doctype html>
<html lang="<?php echo htmlspecialchars($lang, ENT_QUOTES); ?>">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?php echo htmlspecialchars($cfg['app_name'] ?? 'CRM Eventos', ENT_QUOTES); ?></title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }

    :root {
      --bg-primary: #F8FAFC;
      --bg-secondary: #FFFFFF;
      --bg-tertiary: #F1F5F9;
      --text-primary: #0F172A;
      --text-secondary: #475569;
      --text-tertiary: #94A3B8;
      --border-light: #E2E8F0;
      --accent-primary: #2563EB;
      --accent-vr: #7C3AED;
      --success: #10B981;
      --warning: #F59E0B;
      --danger: #EF4444;
      --shadow-card: 0 1px 3px rgba(0,0,0,0.04);
      --shadow-elevated: 0 4px 12px rgba(0,0,0,0.08);
    }

    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Inter', sans-serif;
      background: var(--bg-primary);
      color: var(--text-primary);
      overflow-x: hidden;
    }

    .topbar {
      height: 64px;
      background: var(--bg-secondary);
      border-bottom: 1px solid var(--border-light);
      display: flex;
      align-items: center;
      padding: 0 24px;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 100;
      box-shadow: var(--shadow-card);
      gap: 16px;
    }

    .logo { font-weight: 700; font-size: 20px; color: var(--accent-primary); margin-right: 8px; white-space: nowrap; }

    .breadcrumb {
      color: var(--text-secondary);
      font-size: 14px;
      flex: 1;
      min-width: 220px;
    }

    .search-box {
      width: 400px;
      padding: 8px 16px;
      border: 1px solid var(--border-light);
      border-radius: 6px;
      background: var(--bg-primary);
      color: var(--text-tertiary);
      font-size: 14px;
    }

    .topbar-actions {
      display: flex;
      gap: 16px;
      align-items: center;
      margin-left: 24px;
    }

    .notification-icon {
      width: 20px;
      height: 20px;
      position: relative;
      cursor: pointer;
    }

    .badge {
      position: absolute;
      top: -4px;
      right: -4px;
      background: var(--danger);
      color: white;
      font-size: 10px;
      padding: 2px 4px;
      border-radius: 10px;
      font-weight: 600;
    }

    .avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: var(--accent-primary);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 600;
      font-size: 12px;
      cursor: pointer;
    }

    .layout {
      display: flex;
      margin-top: 64px;
      height: calc(100vh - 64px);
    }

    .sidebar {
      width: 240px;
      background: var(--bg-secondary);
      border-right: 1px solid var(--border-light);
      padding: 16px 0;
      overflow-y: auto;
    }

    .nav-group { margin-bottom: 24px; padding: 0 12px; }
    .nav-title {
      font-size: 11px;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      color: var(--text-tertiary);
      font-weight: 600;
      padding: 0 12px;
      margin-bottom: 8px;
    }

    .nav-item {
      display: flex;
      align-items: center;
      padding: 10px 12px;
      margin: 2px 0;
      border-radius: 6px;
      cursor: pointer;
      font-size: 14px;
      color: var(--text-secondary);
      transition: all 0.2s;
      user-select: none;
    }

    .nav-item:hover { background: var(--bg-primary); color: var(--text-primary); }

    .nav-item.active {
      background: #DBEAFE;
      color: var(--accent-primary);
      border-left: 3px solid var(--accent-primary);
      margin-left: -3px;
      padding-left: 15px;
    }

    .nav-icon { width: 16px; margin-right: 12px; text-align: center; }

    .main {
      flex: 1;
      padding: 24px;
      overflow-y: auto;
      background: var(--bg-primary);
    }

    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      gap: 12px;
    }

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: var(--text-primary);
      letter-spacing: -0.5px;
    }

    .page-badge {
      background: var(--bg-tertiary);
      padding: 4px 12px;
      border-radius: 20px;
      font-size: 12px;
      color: var(--text-secondary);
      margin-left: 12px;
      font-weight: 500;
    }

    .btn {
      padding: 8px 16px;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      border: none;
      transition: all 0.2s;
      text-decoration: none;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      white-space: nowrap;
    }

    .btn-secondary {
      background: transparent;
      border: 1px solid var(--border-light);
      color: var(--text-secondary);
      margin-right: 8px;
    }

    .btn-secondary:hover { background: var(--bg-tertiary); }

    .btn-primary { background: var(--accent-primary); color: white; }
    .btn-primary:hover { background: var(--accent-primary); filter: brightness(0.9); }

    .notice, .error {
      margin-bottom: 16px;
      border-radius: 10px;
      padding: 12px 14px;
      font-size: 13px;
      font-weight: 600;
    }
    .notice { background: #ECFDF5; border: 1px solid #BBF7D0; color: #065F46; }
    .error { background: #FEF2F2; border: 1px solid #FECACA; color: #991B1B; }

    .kpi-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 16px;
      margin-bottom: 24px;
    }

    .kpi-card {
      background: var(--bg-secondary);
      border: 1px solid var(--border-light);
      border-radius: 8px;
      padding: 20px;
      box-shadow: var(--shadow-card);
      min-height: 118px;
    }

    .kpi-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
    }

    .kpi-label {
      font-size: 12px;
      color: var(--text-secondary);
      font-weight: 500;
    }

    .kpi-value {
      font-size: 28px;
      font-weight: 700;
      color: var(--text-primary);
      margin-bottom: 4px;
    }

    .kpi-trend {
      font-size: 12px;
      color: var(--success);
      font-weight: 500;
    }
    .kpi-trend.down { color: var(--danger); }

    .kpi-sub {
      font-size: 13px;
      color: var(--text-tertiary);
      margin-top: 8px;
    }

    .progress-bar {
      height: 4px;
      background: var(--bg-tertiary);
      border-radius: 2px;
      margin-top: 8px;
      overflow: hidden;
    }

    .progress-fill {
      height: 100%;
      background: var(--accent-primary);
      border-radius: 2px;
      width: 0%;
    }

    .pipeline-container {
      background: var(--bg-tertiary);
      border-radius: 12px;
      padding: 16px;
      margin-bottom: 24px;
    }

    .pipeline-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      gap: 12px;
      flex-wrap: wrap;
    }

    .pipeline-title { font-size: 14px; font-weight: 600; color: var(--text-primary); }

    .pipeline-tabs { display: flex; gap: 4px; }
    .tab {
      padding: 6px 12px;
      border-radius: 6px;
      font-size: 12px;
      cursor: pointer;
      color: var(--text-secondary);
      user-select: none;
      background: transparent;
    }
    .tab.active { background: var(--bg-secondary); color: var(--text-primary); font-weight: 500; }

    .board { display: flex; gap: 16px; overflow-x: auto; padding-bottom: 8px; }

    .column {
      min-width: 260px;
      background: var(--bg-secondary);
      border-radius: 8px;
      padding: 12px;
    }

    .column-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      font-size: 12px;
      font-weight: 600;
      color: var(--text-secondary);
      gap: 12px;
    }

    .count-badge {
      background: var(--bg-tertiary);
      padding: 2px 8px;
      border-radius: 10px;
      font-size: 11px;
      font-weight: 600;
      color: var(--text-secondary);
      flex: none;
    }

    .opportunity-card {
      background: var(--bg-secondary);
      border: 1px solid var(--border-light);
      border-left: 3px solid var(--accent-primary);
      border-radius: 6px;
      padding: 12px;
      margin-bottom: 8px;
      cursor: pointer;
      transition: all 0.2s;
    }

    .opportunity-card:hover { box-shadow: var(--shadow-elevated); transform: translateY(-2px); }

    .opp-header { display: flex; justify-content: space-between; margin-bottom: 4px; gap: 8px; }
    .opp-client { font-size: 13px; font-weight: 600; color: var(--text-primary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .opp-value { font-size: 13px; color: var(--text-secondary); font-weight: 500; flex: none; }
    .opp-event { font-size: 12px; color: var(--text-tertiary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-bottom: 8px; }

    .opp-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 8px;
    }

    .opp-tags { display: flex; gap: 4px; flex-wrap: wrap; }

    .tag {
      font-size: 10px;
      padding: 2px 6px;
      border-radius: 4px;
      font-weight: 700;
      letter-spacing: 0.1px;
    }

    .tag-quest { background: #EDE9FE; color: var(--accent-vr); }
    .tag-urgent { background: #FEE2E2; color: var(--danger); }

    .opp-date { font-size: 11px; color: var(--text-tertiary); font-weight: 600; }

    .bottom-grid {
      display: grid;
      grid-template-columns: 1.2fr 0.8fr;
      gap: 24px;
      align-items: start;
    }

    .panel {
      background: var(--bg-secondary);
      border: 1px solid var(--border-light);
      border-radius: 8px;
      box-shadow: var(--shadow-card);
    }

    .panel-header { display: flex; border-bottom: 1px solid var(--border-light); }

    .panel-tab {
      flex: 1;
      padding: 12px;
      text-align: center;
      font-size: 12px;
      font-weight: 600;
      color: var(--text-secondary);
      cursor: pointer;
      border-bottom: 2px solid transparent;
      user-select: none;
    }

    .panel-tab.active { color: var(--accent-primary); border-bottom-color: var(--accent-primary); background: var(--bg-primary); }

    .action-list { padding: 8px 0; }

    .action-item {
      display: flex;
      align-items: center;
      padding: 12px 16px;
      border-bottom: 1px solid var(--border-light);
      transition: background 0.2s;
      gap: 12px;
    }

    .action-item:hover { background: var(--bg-primary); }

    .action-icon {
      width: 32px;
      height: 32px;
      border-radius: 6px;
      background: #DBEAFE;
      color: var(--accent-primary);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 4px;
      font-size: 14px;
      flex: none;
    }

    .action-content { flex: 1; min-width: 0; }
    .action-title { font-size: 14px; font-weight: 600; color: var(--text-primary); margin-bottom: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .action-meta { font-size: 12px; color: var(--text-tertiary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

    .action-tag {
      font-size: 11px;
      padding: 2px 8px;
      border-radius: 10px;
      font-weight: 700;
      margin-right: 2px;
      flex: none;
    }

    .tag-today { background: #D1FAE5; color: var(--success); }
    .tag-late { background: #FEE2E2; color: var(--danger); }

    .action-btn {
      padding: 4px 12px;
      border: 1px solid var(--border-light);
      background: white;
      border-radius: 4px;
      font-size: 12px;
      cursor: pointer;
      flex: none;
      font-weight: 700;
      color: var(--text-secondary);
      transition: all 0.2s;
    }

    .right-stack { display: flex; flex-direction: column; gap: 16px; }

    .small-card {
      background: var(--bg-secondary);
      border: 1px solid var(--border-light);
      border-radius: 8px;
      padding: 16px;
      box-shadow: var(--shadow-card);
    }

    .card-title {
      font-size: 13px;
      font-weight: 700;
      color: var(--text-primary);
      margin-bottom: 12px;
    }

    .event-mini {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid var(--border-light);
      gap: 12px;
    }

    .event-mini:last-child { border-bottom: none; }
    .event-name { font-size: 13px; color: var(--text-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .event-progress { font-size: 11px; color: var(--success); font-weight: 800; flex: none; }

    .highlight-box {
      background: linear-gradient(135deg, #EDE9FE 0%, #DBEAFE 100%);
      border-radius: 8px;
      padding: 16px;
      text-align: center;
      border: 1px solid rgba(37, 99, 235, 0.12);
    }

    .highlight-title {
      font-size: 11px;
      color: var(--accent-vr);
      font-weight: 800;
      text-transform: uppercase;
      margin-bottom: 8px;
    }

    .highlight-value {
      font-size: 18px;
      font-weight: 900;
      color: var(--text-primary);
      margin-bottom: 4px;
    }

    .drawer {
      width: 320px;
      background: var(--bg-secondary);
      border-left: 1px solid var(--border-light);
      padding: 24px;
      overflow-y: auto;
    }

    .drawer-title { font-size: 14px; font-weight: 800; color: var(--text-secondary); margin-bottom: 16px; }

    .calendar-mini {
      background: var(--bg-primary);
      border-radius: 8px;
      padding: 12px;
      margin-bottom: 16px;
      border: 1px solid var(--border-light);
    }

    .cal-header { text-align: center; font-weight: 800; margin-bottom: 8px; font-size: 13px; color: var(--text-secondary); }

    .cal-grid {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 4px;
      text-align: center;
      font-size: 11px;
    }

    .cal-day { padding: 4px; color: var(--text-tertiary); border-radius: 4px; font-weight: 700; }
    .cal-day.highlight { background: var(--accent-primary); color: white; }

    .next-session {
      background: var(--bg-primary);
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 16px;
      border: 1px solid var(--border-light);
    }

    .session-label { font-size: 11px; color: var(--accent-vr); font-weight: 900; margin-bottom: 4px; }
    .session-title { font-size: 16px; font-weight: 900; margin-bottom: 4px; color: var(--text-primary); }
    .session-time { font-size: 13px; color: var(--text-secondary); margin-bottom: 12px; font-weight: 700; }

    .btn-block {
      width: 100%;
      padding: 8px;
      background: var(--accent-vr);
      color: white;
      border: none;
      border-radius: 6px;
      font-size: 13px;
      cursor: pointer;
      font-weight: 900;
    }

    textarea {
      width: 100%;
      padding: 12px;
      border: 1px solid var(--border-light);
      border-radius: 6px;
      font-family: inherit;
      font-size: 13px;
      resize: vertical;
      min-height: 110px;
    }

    input[type="text"], input[type="number"], select {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid var(--border-light);
      border-radius: 6px;
      background: var(--bg-primary);
      color: var(--text-primary);
      font-size: 14px;
      font-weight: 700;
    }

    @media (max-width: 1200px) {
      .kpi-grid { grid-template-columns: repeat(2, 1fr); }
      .bottom-grid { grid-template-columns: 1fr; }
      .layout { flex-direction: column; height: auto; }
      .sidebar, .drawer { width: 100%; }
      .drawer { border-left: none; border-top: 1px solid var(--border-light); }
      .topbar { position: sticky; top: 0; }
      .search-box { width: 240px; }
    }
  </style>
</head>
<body>
  <div class="topbar">
    <div class="logo">◆ CRM Eventos</div>
    <div class="breadcrumb"><?php echo htmlspecialchars((string)$pageTitle, ENT_QUOTES); ?> / Q1 2026</div>

    <form method="get" action="" style="margin:0; flex:none;">
      <input
        type="text"
        class="search-box"
        name="q"
        value="<?php echo htmlspecialchars($q, ENT_QUOTES); ?>"
        placeholder="Buscar oportunidades, eventos ou clientes..."
      >
      <input type="hidden" name="section" value="<?php echo htmlspecialchars($activeNav, ENT_QUOTES); ?>">
    </form>

    <div class="topbar-actions">
      <div class="notification-icon">
        🔔
        <?php if ($counts['followups_open'] > 0): ?>
          <span class="badge"><?php echo (int)min(99, $counts['followups_open']); ?></span>
        <?php endif; ?>
      </div>
      <div class="avatar">JD</div>
      <div style="color: var(--text-tertiary); cursor: pointer;">⚙️</div>
    </div>
  </div>

  <div class="layout">
    <aside class="sidebar">
      <div class="nav-group">
        <div class="nav-title">Executivo</div>
        <a class="nav-item <?php echo $activeNav === 'executive' ? 'active' : ''; ?>" href="?section=executive">
          <span class="nav-icon">▣</span> Visão Executiva
        </a>
        <a class="nav-item <?php echo $activeNav === 'indicadores' ? 'active' : ''; ?>" href="?section=indicadores">
          <span class="nav-icon">◈</span> Indicadores
        </a>
        <a class="nav-item <?php echo $activeNav === 'snapshots' ? 'active' : ''; ?>" href="?section=snapshots">
          <span class="nav-icon">◉</span> Snapshots
        </a>
      </div>

      <div class="nav-group">
        <div class="nav-title">CRM Comercial</div>
        <a class="nav-item <?php echo $activeNav === 'pipeline' ? 'active' : ''; ?>" href="?section=pipeline">
          <span class="nav-icon">◧</span> Pipeline
        </a>
        <a class="nav-item <?php echo $activeNav === 'opps' ? 'active' : ''; ?>" href="?section=opps">
          <span class="nav-icon">◐</span> Oportunidades
        </a>
        <a class="nav-item <?php echo $activeNav === 'leads' ? 'active' : ''; ?>" href="?section=leads">
          <span class="nav-icon">○</span> Leads
        </a>
        <a class="nav-item <?php echo $activeNav === 'quest-sessions' ? 'active' : ''; ?>" href="?section=quest-sessions">
          <span class="nav-icon">◑</span> Sessões Quest
        </a>
      </div>

      <div class="nav-group">
        <div class="nav-title">Operações</div>
        <a class="nav-item <?php echo $activeNav === 'handoff' ? 'active' : ''; ?>" href="?section=handoff">
          <span class="nav-icon">▶</span> Handoff
        </a>
        <a class="nav-item <?php echo $activeNav === 'checklist' ? 'active' : ''; ?>" href="?section=checklist">
          <span class="nav-icon">✓</span> Checklist
        </a>
        <a class="nav-item <?php echo $activeNav === 'execucao' ? 'active' : ''; ?>" href="?section=execucao">
          <span class="nav-icon">⚡</span> Execução
        </a>
      </div>

      <div class="nav-group">
        <div class="nav-title">Governança</div>
        <a class="nav-item <?php echo $activeNav === 'watchlist' ? 'active' : ''; ?>" href="?section=watchlist">
          <span class="nav-icon">◆</span> Watchlist
        </a>
        <a class="nav-item <?php echo $activeNav === 'decisoes' ? 'active' : ''; ?>" href="?section=decisoes">
          <span class="nav-icon">▮</span> Decisões
        </a>
      </div>
    </aside>

    <main class="main">
      <?php if (!empty($notice)): ?>
        <div class="notice"><?php echo htmlspecialchars($notice, ENT_QUOTES); ?></div>
      <?php endif; ?>
      <?php if (!empty($error)): ?>
        <div class="error"><?php echo htmlspecialchars($error, ENT_QUOTES); ?></div>
      <?php endif; ?>

      <div class="page-header">
        <div style="display: flex; align-items: center; gap: 8px;">
          <h1 class="page-title"><?php echo htmlspecialchars($pageTitle, ENT_QUOTES); ?></h1>
          <span class="page-badge">Q1 2026</span>
        </div>

        <div style="display:flex; align-items:center; gap: 8px; flex-wrap: wrap;">
          <a class="btn btn-secondary" href="<?php echo htmlspecialchars($baseUrl . '/app/?export=crm', ENT_QUOTES); ?>">
            Exportar
          </a>
          <a
            class="btn btn-primary"
            href="<?php echo htmlspecialchars($baseUrl . '/app/?section=' . rawurlencode($activeNav) . ($q !== '' ? '&q=' . rawurlencode($q) : '') . '&create_opp=1', ENT_QUOTES); ?>"
          >
            + Nova Oportunidade
          </a>
        </div>
      </div>

      <?php if ($createOppMode): ?>
        <div class="panel" style="margin-bottom: 24px;">
          <div class="panel-header">
            <div class="panel-tab active" style="border-bottom-color: transparent;">Criar Oportunidade (Mock)</div>
          </div>
          <div style="padding: 16px;">
            <?php if (!empty($error)): ?>
              <div class="error" style="margin: 0 0 12px 0;"><?php echo htmlspecialchars($error, ENT_QUOTES); ?></div>
            <?php endif; ?>

            <form method="post" action="">
              <input type="hidden" name="action" value="create_opportunity">

              <div style="display:flex; gap: 12px; flex-wrap: wrap;">
                <div style="flex: 1; min-width: 260px;">
                  <div style="font-size: 12px; color: var(--text-secondary); font-weight: 900; margin-bottom: 8px;">Título</div>
                  <input type="text" name="opp_title" placeholder="Ex: Evento Corporativo 200 pax" required>
                </div>

                <div style="flex: 1; min-width: 180px;">
                  <div style="font-size: 12px; color: var(--text-secondary); font-weight: 900; margin-bottom: 8px;">Valor (R$)</div>
                  <input type="number" name="opp_value" placeholder="Ex: 50000" step="0.01" required>
                </div>
              </div>

              <div style="display:flex; gap: 12px; margin-top: 12px; flex-wrap: wrap;">
                <div style="flex: 1; min-width: 260px;">
                  <div style="font-size: 12px; color: var(--text-secondary); font-weight: 900; margin-bottom: 8px;">Lead (empresa)</div>
                  <select name="opp_lead_id" required>
                    <?php foreach ($leads as $l): ?>
                      <?php
                        $id = (string)($l['Id'] ?? '');
                        if ($id === '') continue;
                        $company = (string)($l['Company'] ?? '');
                        $name = (string)($l['Name'] ?? '');
                      ?>
                      <option value="<?php echo htmlspecialchars($id, ENT_QUOTES); ?>">
                        <?php echo htmlspecialchars(trim($company . ' - ' . $name), ENT_QUOTES); ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </div>

                <div style="flex: 1; min-width: 220px;">
                  <div style="font-size: 12px; color: var(--text-secondary); font-weight: 900; margin-bottom: 8px;">Stage inicial</div>
                  <select name="opp_stage" required>
                    <option value="NewLead">NewLead</option>
                    <option value="Contacted">Contacted</option>
                    <option value="ProposalSent">ProposalSent</option>
                    <option value="FollowUp">FollowUp</option>
                    <option value="ReadyToClose">ReadyToClose</option>
                  </select>
                </div>
              </div>

              <div style="display:flex; gap: 10px; margin-top: 16px; flex-wrap: wrap;">
                <button class="btn btn-primary" type="submit">Criar oportunidade</button>
                <a
                  class="btn btn-secondary"
                  href="<?php echo htmlspecialchars($baseUrl . '/app/?section=' . rawurlencode((string)$activeNav) . ($q !== '' ? '&q=' . rawurlencode((string)$q) : ''), ENT_QUOTES); ?>"
                >
                  Cancelar
                </a>
              </div>
            </form>
          </div>
        </div>
      <?php endif; ?>

      <?php if ($activeNav !== 'executive' && !$createOppMode): ?>
        <div class="notice" style="margin-bottom: 16px;">
          A seção <strong><?php echo htmlspecialchars((string)$pageTitle, ENT_QUOTES); ?></strong> ainda não está implementada neste mock.
          Mostrando a Visão Executiva.
        </div>
      <?php endif; ?>

      <div class="kpi-grid">
        <div class="kpi-card">
          <div class="kpi-header">
            <span class="kpi-label">Pipeline Ativo</span>
            <span class="kpi-icon" style="color: var(--accent-primary);">◈</span>
          </div>
          <div class="kpi-value"><?php echo htmlspecialchars(eaq_format_money_brl($pipelineActiveValue), ENT_QUOTES); ?></div>
          <div class="kpi-trend">▲ <?php echo (int)max(0, min(99, $pipelineProgress)); ?>% vs progresso</div>
          <div class="progress-bar">
            <div class="progress-fill" style="width: <?php echo (int)max(0, min(100, $pipelineProgress)); ?>%;"></div>
          </div>
        </div>

        <div class="kpi-card">
          <div class="kpi-header">
            <span class="kpi-label">Sessões Quest</span>
            <span class="kpi-icon" style="color: var(--accent-vr);">◉</span>
          </div>
          <div class="kpi-value"><?php echo (int)$questSessionsCount; ?></div>
          <div class="kpi-trend"><?php echo (int)$questConversion; ?>% conversão</div>
          <?php
            // Next 7 days open follow-ups count.
            $convSoon = 0;
            foreach ($followups as $fu) {
              if (!empty($fu['IsCompleted'])) continue;
              $due = eaq_parse_utc_iso((string)($fu['DueDate'] ?? ''));
              if ($due === null) continue;
              $days = (int)$due->diff($now)->format('%r%a');
              if ($days >= 0 && $days <= 7) $convSoon++;
            }
          ?>
          <div class="kpi-sub"><?php echo (int)$convSoon; ?> agendadas (7d)</div>
        </div>

        <div class="kpi-card">
          <div class="kpi-header">
            <span class="kpi-label">Eventos em Operação</span>
            <span class="kpi-icon" style="color: var(--success);">▶</span>
          </div>
          <div class="kpi-value"><?php echo (int)count($sessions); ?></div>
          <div class="kpi-trend">Readiness médio <?php echo (int)$readinessAvg; ?>%</div>
          <div class="progress-bar">
            <div class="progress-fill" style="width: <?php echo (int)max(0, min(100, $readinessAvg)); ?>%; background: var(--success);"></div>
          </div>
        </div>

        <div class="kpi-card">
          <div class="kpi-header">
            <span class="kpi-label">Ações Pendentes</span>
            <span class="kpi-icon" style="color: var(--warning);">⚠</span>
          </div>
          <div class="kpi-value"><?php echo (int)$counts['followups_open']; ?></div>
          <div class="kpi-trend <?php echo $urgentFollowupsCount > 0 ? 'down' : ''; ?>">
            <?php echo $urgentFollowupsCount > 0 ? '▼ ' . (int)$urgentFollowupsCount : '▲ 0 urgentes'; ?> urgentes
          </div>
          <div class="kpi-sub">
            <?php
              $late = 0;
              foreach ($followups as $fu) {
                if (!empty($fu['IsCompleted'])) continue;
                $due = eaq_parse_utc_iso((string)($fu['DueDate'] ?? ''));
                if ($due !== null && $due < $now) $late++;
              }
            ?>
            <?php echo (int)$late; ?> atrasadas
          </div>
        </div>
      </div>

      <div class="pipeline-container">
        <div class="pipeline-header">
          <div class="pipeline-title">Pipeline Comercial</div>
          <div class="pipeline-tabs" id="pipelineTabs">
            <div class="tab active" data-view="board">Board</div>
            <div class="tab" data-view="list">Lista</div>
            <div class="tab" data-view="analysis">Análise</div>
          </div>
        </div>

        <div id="view-board">
          <div class="board">
            <?php foreach ($columns as $colName => $meta): ?>
              <?php $items = $colOpps[$colName] ?? []; ?>
              <div class="column">
                <div class="column-header">
                  <span><?php echo htmlspecialchars($colName, ENT_QUOTES); ?></span>
                  <span class="count-badge"><?php echo (int)count($items); ?></span>
                </div>

                <?php if (count($items) === 0): ?>
                  <div style="font-size:12px; color: var(--text-tertiary); padding: 10px 6px;">
                    Sem itens
                  </div>
                <?php endif; ?>

                <?php foreach ($items as $it): ?>
                  <?php
                    $o = $it['opp'];
                    $value = (float)$it['value'];
                    $tagType = $it['tagType'];
                    $isUrgent = !empty($it['isUrgent']);

                    $borderColor = $meta['accent'];
                    if ($isUrgent) $borderColor = 'var(--warning)';
                  ?>
                  <div class="opportunity-card" style="border-left-color: <?php echo htmlspecialchars($borderColor, ENT_QUOTES); ?>;">
                    <div class="opp-header">
                      <span class="opp-client"><?php echo htmlspecialchars((string)$it['company'], ENT_QUOTES); ?></span>
                      <span class="opp-value"><?php echo htmlspecialchars(eaq_format_money_brl($value), ENT_QUOTES); ?></span>
                    </div>
                    <div class="opp-event"><?php echo htmlspecialchars((string)($o['Title'] ?? ''), ENT_QUOTES); ?></div>

                    <div class="opp-footer">
                      <div class="opp-tags">
                        <?php if ($tagType === 'quest'): ?>
                          <span class="tag tag-quest">Quest</span>
                        <?php elseif ($tagType === 'urgent'): ?>
                          <span class="tag tag-urgent">Urgente</span>
                        <?php endif; ?>
                      </div>
                      <span class="opp-date"><?php echo htmlspecialchars((string)$it['dueLabel'], ENT_QUOTES); ?></span>
                    </div>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php endforeach; ?>
          </div>
        </div>

        <div id="view-list" style="display:none;">
          <div class="panel" style="box-shadow:none;">
            <div class="panel-header">
              <div class="panel-tab active" style="border-bottom-color: transparent;">Oportunidades (Lista)</div>
            </div>
            <div style="padding: 12px 16px;">
              <table style="width:100%; border-collapse: collapse;">
                <thead>
                  <tr style="text-align:left; font-size:12px; color: var(--text-secondary);">
                    <th style="padding: 8px 6px;">Empresa</th>
                    <th style="padding: 8px 6px;">Título</th>
                    <th style="padding: 8px 6px;">Stage</th>
                    <th style="padding: 8px 6px;">Valor</th>
                    <th style="padding: 8px 6px;">Próximo follow-up</th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                    // Use current q filter already applied per pipeline column; here list all opps matching query.
                    $listed = [];
                    foreach ($opps as $o) {
                      $stage = (string)($o['Stage'] ?? '');
                      $leadId = (string)($o['LeadId'] ?? '');
                      $lead = $leadById[$leadId] ?? null;
                      $company = is_array($lead) ? (string)($lead['Company'] ?? '') : '';
                      $title = (string)($o['Title'] ?? '');
                      if (!$matchesQuery($company . ' ' . $title . ' ' . $stage, $q)) continue;
                      $follow = $firstOpenFollowupForOpp($crm, (string)($o['Id'] ?? ''));
                      $dueDt = null;
                      $dueLabel = '—';
                      if (is_array($follow)) {
                        $dueDt = eaq_parse_utc_iso((string)($follow['DueDate'] ?? ''));
                        if ($dueDt) $dueLabel = eaq_relative_due_label($dueDt, $now);
                      }
                      $listed[] = ['o'=>$o,'company'=>$company,'dueLabel'=>$dueLabel];
                    }
                  ?>
                  <?php foreach ($listed as $row): ?>
                    <?php $o = $row['o']; ?>
                    <tr style="border-top:1px solid var(--border-light);">
                      <td style="padding: 10px 6px; font-weight:700; color: var(--text-secondary);">
                        <?php echo htmlspecialchars((string)$row['company'], ENT_QUOTES); ?>
                      </td>
                      <td style="padding: 10px 6px; color: var(--text-tertiary);">
                        <?php echo htmlspecialchars((string)($o['Title'] ?? ''), ENT_QUOTES); ?>
                      </td>
                      <td style="padding: 10px 6px; color: var(--text-tertiary);">
                        <?php echo htmlspecialchars((string)($o['Stage'] ?? ''), ENT_QUOTES); ?>
                      </td>
                      <td style="padding: 10px 6px; color: var(--text-secondary); font-weight:700;">
                        <?php
                          $v = is_numeric($o['Value'] ?? null) ? (float)$o['Value'] : 0.0;
                          echo htmlspecialchars(eaq_format_money_brl($v), ENT_QUOTES);
                        ?>
                      </td>
                      <td style="padding: 10px 6px; color: var(--text-secondary); font-weight:800;">
                        <?php echo htmlspecialchars((string)$row['dueLabel'], ENT_QUOTES); ?>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                  <?php if (count($listed) === 0): ?>
                    <tr>
                      <td colspan="5" style="padding: 14px 6px; color: var(--text-tertiary); font-weight:700;">
                        Nenhuma oportunidade encontrada para o filtro atual.
                      </td>
                    </tr>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <div id="view-analysis" style="display:none;">
          <div class="panel" style="box-shadow:none;">
            <div class="panel-header">
              <div class="panel-tab active" style="border-bottom-color: transparent;">Análise (Mock)</div>
            </div>
            <div style="padding: 14px 16px; color: var(--text-secondary); font-size: 13px; font-weight: 700;">
              <div style="margin-bottom:8px;">
                Este modo usa apenas o snapshot local (mock). Para “análise” avançada, ligue as regras/cálculos reais do seu Web CRM.
              </div>
              <div style="display:flex; gap: 14px; flex-wrap: wrap;">
                <span class="tag tag-quest">Conversão Sessões: <?php echo (int)$questConversion; ?>%</span>
                <span class="tag tag-urgent">Urgências: <?php echo (int)$urgentFollowupsCount; ?></span>
                <span class="tag" style="background: var(--bg-tertiary); color: var(--text-tertiary);">Readiness médio: <?php echo (int)$readinessAvg; ?>%</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="bottom-grid">
        <div class="panel">
          <div class="panel-header">
            <div class="panel-tab active" data-panel="actions">Ações Recomendadas</div>
            <div class="panel-tab" data-panel="alerts">Alertas</div>
            <div class="panel-tab" data-panel="calendar">Calendário</div>
          </div>

          <div class="action-list" id="panel-actions">
            <?php if (count($recommended) === 0): ?>
              <div style="padding: 14px 16px; color: var(--text-tertiary); font-weight: 700; font-size: 13px;">
                Sem follow-ups abertos para o filtro atual.
              </div>
            <?php endif; ?>

            <?php foreach ($recommended as $item): ?>
              <?php
                $fu = $item['fu'];
                $opp = $item['opp'];
                $due = $item['due'];
                $prio = (string)($fu['Priority'] ?? '');
                $title = (string)($fu['Title'] ?? '');
                $oppTitle = is_array($opp) ? (string)($opp['Title'] ?? '') : '';
                $leadId = is_array($opp) ? (string)($opp['LeadId'] ?? '') : '';
                $lead = $leadById[$leadId] ?? null;
                $company = is_array($lead) ? (string)($lead['Company'] ?? '') : '';
                $dueLabel = '—';
                $isLate = false;
                if ($due instanceof DateTimeImmutable) {
                  $dueLabel = eaq_relative_due_label($due, $now);
                  $isLate = $due < $now;
                }
                $urgent = $isLate || in_array($prio, ['Urgent', 'High'], true);
                $isToday = ($dueLabel !== '—' && strpos($dueLabel, 'Hoje') === 0);
                $iconBg = $urgent ? '#FEE2E2' : ($isToday ? '#D1FAE5' : '#DBEAFE');
                $iconColor = $urgent ? 'var(--danger)' : ($isToday ? 'var(--success)' : 'var(--accent-primary)');
                $buttonStyle = '';
                $buttonText = 'Registrar';
                if ($urgent) {
                  $buttonStyle = 'border-color: var(--danger); color: var(--danger);';
                  $buttonText = 'Urgente';
                } elseif ($isToday) {
                  $buttonText = 'Registrar';
                }
                $tagClass = '';
                $tagText = '';
                if ($isLate) {
                  $tagClass = 'tag-late';
                  $tagText = 'Atrasado';
                } elseif ($isToday) {
                  $tagClass = 'tag-today';
                  $tagText = $dueLabel;
                } else {
                  $tagClass = '';
                  $tagText = $dueLabel;
                }
              ?>
              <form method="post" action="" style="margin:0; display: contents;">
                <input type="hidden" name="action" value="toggle_followup">
                <input type="hidden" name="followup_id" value="<?php echo htmlspecialchars((string)($fu['Id'] ?? ''), ENT_QUOTES); ?>">
                <div class="action-item">
                  <div class="action-icon" style="background: <?php echo htmlspecialchars($iconBg, ENT_QUOTES); ?>; color: <?php echo htmlspecialchars($iconColor, ENT_QUOTES); ?>">
                    <?php echo $urgent ? '⚠' : '📞'; ?>
                  </div>
                  <div class="action-content">
                    <div class="action-title"><?php echo htmlspecialchars($title, ENT_QUOTES); ?></div>
                    <div class="action-meta"><?php echo htmlspecialchars(($oppTitle !== '' ? $oppTitle : $company), ENT_QUOTES); ?></div>
                  </div>
                  <?php if ($tagText !== ''): ?>
                    <span class="action-tag <?php echo htmlspecialchars($tagClass, ENT_QUOTES); ?>">
                      <?php echo htmlspecialchars($tagText, ENT_QUOTES); ?>
                    </span>
                  <?php endif; ?>
                  <?php
                    $oppValue = is_array($opp) && is_numeric($opp['Value'] ?? null) ? (float)$opp['Value'] : 0.0;
                  ?>
                  <span style="font-size:13px; color: var(--text-secondary); font-weight:900; flex:none;">
                    <?php echo htmlspecialchars(eaq_format_money_brl($oppValue), ENT_QUOTES); ?>
                  </span>
                  <button class="action-btn" style="<?php echo htmlspecialchars($buttonStyle, ENT_QUOTES); ?>" type="submit">
                    <?php echo htmlspecialchars($buttonText, ENT_QUOTES); ?>
                  </button>
                </div>
              </form>
            <?php endforeach; ?>
          </div>

          <div class="action-list" id="panel-alerts" style="display:none;">
            <div style="padding: 14px 16px; color: var(--text-secondary); font-weight: 700; font-size: 13px;">
              Alertas (mock): <?php echo (int)$watchRiskCount; ?> riscos na watchlist.
            </div>
          </div>

          <div class="action-list" id="panel-calendar" style="display:none;">
            <div style="padding: 14px 16px; color: var(--text-secondary); font-weight: 700; font-size: 13px;">
              Calendário: use a aba “Detalhes do Dia” no drawer.
            </div>
          </div>
        </div>

        <div class="right-stack">
          <div class="small-card">
            <div class="card-title">Eventos Ativos</div>
            <?php if (count($eventsAtivos) === 0): ?>
              <div style="font-size: 13px; color: var(--text-tertiary); font-weight: 800; padding: 6px 0;">Sem sessões</div>
            <?php endif; ?>
            <?php foreach ($eventsAtivos as $item): ?>
              <?php
                $s = $item['s'];
                $r = (int)$item['r'];
                $oppId = (string)($s['OpportunityId'] ?? '');
                $opp = $oppById[$oppId] ?? null;
                $company = '';
                if (is_array($opp)) {
                  $leadId = (string)($opp['LeadId'] ?? '');
                  $lead = $leadById[$leadId] ?? null;
                  $company = is_array($lead) ? (string)($lead['Company'] ?? '') : '';
                }
                $color = $r < 60 ? 'var(--warning)' : 'var(--success)';
                $label = is_string($company) && $company !== '' ? $company : 'Sessão Quest';
              ?>
              <div class="event-mini">
                <span class="event-name"><?php echo htmlspecialchars($label, ENT_QUOTES); ?></span>
                <span class="event-progress" style="color: <?php echo htmlspecialchars($color, ENT_QUOTES); ?>;"><?php echo (int)$r; ?>%</span>
              </div>
            <?php endforeach; ?>
          </div>

          <div class="highlight-box">
            <div class="highlight-title">Próxima Sessão Quest</div>
            <div class="highlight-value">
              <?php
                $hlLabel = '—';
                if ($nextSessionFollowupDue instanceof DateTimeImmutable) $hlLabel = eaq_relative_due_label($nextSessionFollowupDue, $now);
                echo htmlspecialchars($hlLabel, ENT_QUOTES);
              ?>
            </div>
            <div style="font-size: 13px; color: var(--text-secondary); margin-bottom: 12px; font-weight: 800;">
              <?php
                $display = '';
                if (is_array($nextOpp)) $display = (string)($nextOpp['Title'] ?? '');
                if ($display === '' && is_array($nextLead)) $display = (string)($nextLead['Company'] ?? '');
                echo htmlspecialchars($display, ENT_QUOTES);
              ?>
            </div>
            <?php if (is_array($nextSessionFollowup)): ?>
              <form method="post" action="" style="margin:0;">
                <input type="hidden" name="action" value="toggle_followup">
                <input type="hidden" name="followup_id" value="<?php echo htmlspecialchars((string)($nextSessionFollowup['Id'] ?? ''), ENT_QUOTES); ?>">
                <button class="btn-primary" type="submit" style="padding: 6px 16px; font-size: 12px;">
                  Preparar Sala
                </button>
              </form>
            <?php else: ?>
              <button class="btn-primary" type="button" disabled style="padding: 6px 16px; font-size: 12px;">Preparar Sala</button>
            <?php endif; ?>
          </div>

          <div class="small-card">
            <div class="card-title">
              Watchlist <span style="color: var(--warning); font-size: 11px;">(<?php echo (int)$watchRiskCount; ?> riscos)</span>
            </div>

            <?php if (count($watchlist) === 0): ?>
              <div style="font-size: 13px; color: var(--text-tertiary); font-weight: 800; padding: 6px 0;">Sem riscos relevantes</div>
            <?php endif; ?>

            <?php foreach ($watchlist as $item): ?>
              <?php
                $fu = $item['fu'];
                $due = $item['due'];
                $opp = $item['opp'];
                $oppTitle = is_array($opp) ? (string)($opp['Title'] ?? '') : '';
                $dueLabel = $due instanceof DateTimeImmutable ? eaq_relative_due_label($due, $now) : '—';
              ?>
              <div class="watchlist-item" style="display:flex; align-items:center; padding: 10px 8px; background: #FFFBEB; border-left: 3px solid var(--warning); border-radius: 4px; margin-bottom: 8px;">
                <span style="color: var(--warning); font-weight: 900;">⚠</span>
                <span class="watchlist-text" style="font-size:12px; color: var(--text-secondary); margin-left: 8px; font-weight: 800;">
                  <?php echo htmlspecialchars(($oppTitle !== '' ? $oppTitle : (string)($fu['Title'] ?? '')), ENT_QUOTES); ?>
                  <?php echo $due instanceof DateTimeImmutable ? ' (' . htmlspecialchars($dueLabel, ENT_QUOTES) . ')' : ''; ?>
                </span>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
      </div>
    </main>

    <aside class="drawer">
      <div class="drawer-title">Detalhes do Dia</div>

      <div class="calendar-mini">
        <div class="cal-header">Março 2026</div>
        <div class="cal-grid">
          <?php
            // Keep the calendar visual simple (static preview).
            $days = [null, null, null, null, null, null, null, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
            // Highlight day 11 to match provided HTML.
            $flat = [6,7,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
          ?>
          <?php
            // Render 21 cells to mimic the original grid.
            for ($i = 1; $i <= 21; $i++):
          ?>
            <div class="cal-day<?php echo $i === 11 ? ' highlight' : ''; ?>"><?php echo (int)$i; ?></div>
          <?php endfor; ?>
        </div>
      </div>

      <div class="next-session">
        <div class="session-label">Próxima Sessão</div>
        <div class="session-title">
          <?php
            $nextTitle = '';
            if (is_array($nextOpp)) $nextTitle = (string)($nextOpp['Title'] ?? '');
            if ($nextTitle === '' && is_array($nextLead)) $nextTitle = (string)($nextLead['Company'] ?? '');
            echo htmlspecialchars($nextTitle !== '' ? $nextTitle : '—', ENT_QUOTES);
          ?>
        </div>
        <div class="session-time">
          <?php
            $dueLabel = ($nextSessionFollowupDue instanceof DateTimeImmutable) ? eaq_relative_due_label($nextSessionFollowupDue, $now) : '—';
            echo htmlspecialchars($dueLabel, ENT_QUOTES);
          ?>
        </div>
        <div style="font-size: 12px; color: var(--text-tertiary); margin-bottom: 12px; font-weight: 800;">
          <?php
            $leadCompany = is_array($nextLead) ? (string)($nextLead['Company'] ?? '') : '';
            $leadCompany = $leadCompany !== '' ? $leadCompany : '—';
            echo htmlspecialchars($leadCompany, ENT_QUOTES);
          ?> | Preparativos em andamento
        </div>

        <form method="post" action="" style="margin:0;">
          <?php if (is_array($nextSessionFollowup)): ?>
            <input type="hidden" name="action" value="toggle_followup">
            <input type="hidden" name="followup_id" value="<?php echo htmlspecialchars((string)($nextSessionFollowup['Id'] ?? ''), ENT_QUOTES); ?>">
            <button class="btn-block" type="submit">Ver Preparativos</button>
          <?php else: ?>
            <button class="btn-block" type="button" disabled>Ver Preparativos</button>
          <?php endif; ?>
        </form>
      </div>

      <div style="margin-bottom: 12px; font-size: 13px; font-weight: 900; color: var(--text-secondary);">Notas Gerenciais</div>
      <form method="post" action="" style="margin:0;">
        <textarea name="manager_note_text" placeholder="Adicione observações rápidas..."><?php echo htmlspecialchars($latestNoteText, ENT_QUOTES); ?></textarea>
        <button class="btn btn-secondary" style="margin-top: 8px; width: 100%; font-weight: 800;" type="submit" name="action" value="save_manager_notes">
          Salvar Nota
        </button>
      </form>

      <div style="margin-top: 24px; padding-top: 24px; border-top: 1px solid var(--border-light);">
        <div style="font-size: 13px; font-weight: 900; color: var(--text-secondary); margin-bottom: 12px;">Stats Rápidos</div>

        <?php
          $todayKey = eaq_day_key_utc($now);
          $newLeadsToday = 0;
          foreach ($leads as $l) {
            $created = eaq_parse_utc_iso((string)($l['CreatedAt'] ?? ''));
            if ($created && eaq_day_key_utc($created) === $todayKey) $newLeadsToday++;
          }
          $proposalsSentToday = 0;
          foreach (($crm['proposals'] ?? []) as $p) {
            $sentAt = eaq_parse_utc_iso((string)($p['SentAt'] ?? ''));
            if ($sentAt && eaq_day_key_utc($sentAt) === $todayKey) $proposalsSentToday++;
          }
          $convTax = 0;
          if ($questSessionsCount > 0) $convTax = (int)round(($questConvertedCount / $questSessionsCount) * 100);
        ?>

        <div style="display: flex; justify-content: space-between; margin-bottom: 8px; font-size: 12px;">
          <span style="color: var(--text-tertiary); font-weight: 800;">Novos Leads (hoje)</span>
          <span style="font-weight: 1000;"><?php echo (int)$newLeadsToday; ?></span>
        </div>
        <div style="display: flex; justify-content: space-between; margin-bottom: 8px; font-size: 12px;">
          <span style="color: var(--text-tertiary); font-weight: 800;">Propostas enviadas</span>
          <span style="font-weight: 1000;"><?php echo (int)$proposalsSentToday; ?></span>
        </div>
        <div style="display: flex; justify-content: space-between; font-size: 12px;">
          <span style="color: var(--text-tertiary); font-weight: 800;">Taxa de conversão</span>
          <span style="font-weight: 1000; color: var(--success);"><?php echo (int)$convTax; ?>%</span>
        </div>
      </div>
    </aside>
  </div>

  <script>
    (function () {
      // Pipeline tabs
      var tabs = document.querySelectorAll('#pipelineTabs .tab');
      var views = {
        board: document.getElementById('view-board'),
        list: document.getElementById('view-list'),
        analysis: document.getElementById('view-analysis'),
      };

      function setPipelineView(view) {
        Object.keys(views).forEach(function (k) {
          if (!views[k]) return;
          views[k].style.display = (k === view) ? '' : 'none';
        });
        tabs.forEach(function (t) {
          t.classList.toggle('active', (t.getAttribute('data-view') === view));
        });
      }

      tabs.forEach(function (t) {
        t.addEventListener('click', function () {
          setPipelineView(t.getAttribute('data-view'));
        });
      });

      // Bottom panel tabs
      var panelTabs = document.querySelectorAll('.panel-tab[data-panel]');
      var panels = {
        actions: document.getElementById('panel-actions'),
        alerts: document.getElementById('panel-alerts'),
        calendar: document.getElementById('panel-calendar'),
      };

      function setPanel(panelKey) {
        Object.keys(panels).forEach(function (k) {
          if (!panels[k]) return;
          panels[k].style.display = (k === panelKey) ? '' : 'none';
        });
        panelTabs.forEach(function (x) {
          x.classList.toggle('active', x.getAttribute('data-panel') === panelKey);
        });
      }

      panelTabs.forEach(function (x) {
        x.addEventListener('click', function () {
          setPanel(x.getAttribute('data-panel'));
        });
      });
    })();
  </script>
</body>
</html>

