<template>
    <Head :title="'Report: ' + automation.title + ' - CRMfic'" />

    <AppLayout>
        <!-- Header & Breadcrumbs -->
        <div class="ar-header">
            <Link href="/automation" class="ar-back">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="16" height="16">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18"/>
                </svg>
                Automation Funnels
            </Link>

            <div class="ar-title-row">
                <div class="ar-title-left">
                    <h1 class="ar-title">{{ automation.title }}</h1>
                    <div class="ar-meta">
                        <span :class="['ar-badge', statusClass(automation.status)]">
                            {{ automation.status.charAt(0).toUpperCase() + automation.status.slice(1) }}
                        </span>
                        <span class="ar-meta-sep">·</span>
                        <span class="ar-meta-id">ID: #{{ automation.id }}</span>
                        <span class="ar-meta-sep">·</span>
                        <span class="ar-meta-date" v-if="automation.created_at">Created {{ formatDateTime(automation.created_at) }}</span>
                    </div>
                </div>
                <div class="ar-title-actions">
                    <Link :href="`/automation/${automation.id}/edit`" class="btn btn-primary btn-sm">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="14" height="14" style="margin-right: 4px;">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931z"/>
                        </svg>
                        Edit Funnel
                    </Link>
                </div>
            </div>
        </div>

        <!-- Global Date Range Filter Control Bar -->
        <div class="ar-controls-bar">
            <div class="controls-title-wrap">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="16" height="16" class="text-slate-400">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5m-9-6h.008v.008H12v-.008zM12 15h.008v.008H12V15zm0 2.25h.008v.008H12v-.008zM9.75 15h.008v.008H9.75V15zm0 2.25h.008v.008H9.75v-.008zM7.5 15h.008v.008H7.5V15zm0 2.25h.008v.008H7.5v-.008zm6.75-4.5h.008v.008h-.008v-.008zm0 2.25h.008v.008h-.008V15zm0 2.25h.008v.008h-.008v-.008zm2.25-4.5h.008v.008H16.5v-.008zm0 2.25h.008v.008H16.5V15z" />
                </svg>
                <span class="controls-title">Filter by Date Range:</span>
            </div>
            <div class="ar-date-filters">
                <div class="date-input-wrap">
                    <CwDateTimePicker 
                        v-model="startDate" 
                        mode="date" 
                        :disablePast="false" 
                        @update:modelValue="onDateChange" 
                        placeholder="Start Date" 
                    />
                </div>
                <span class="date-sep">to</span>
                <div class="date-input-wrap">
                    <CwDateTimePicker 
                        v-model="endDate" 
                        mode="date" 
                        :disablePast="false" 
                        @update:modelValue="onDateChange" 
                        placeholder="End Date" 
                        align="right"
                    />
                </div>
                <button v-if="startDate || endDate" class="btn btn-ghost btn-sm clear-dates-btn" @click="clearDates" title="Clear filters">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="14" height="14">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                </button>
            </div>
        </div>

        <!-- High-Impact KPI Overview Cards -->
        <div class="ar-kpi-grid">
            <div class="ar-kpi-card">
                <div class="ar-kpi-icon is-blue">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="20" height="20">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.109A9.342 9.342 0 0012.458 10.22c.005-.134.01-.268.012-.403 0-3.3-2.69-5.966-5.97-5.966S.531 6.516.531 9.817c.002.135.007.269.012.403a9.34 9.34 0 007.502 9.017M12.458 10.22A9.309 9.309 0 0015 15.68M12.458 10.22a9.309 9.309 0 01-2.458-5.64m0 0a4.125 4.125 0 00-7.533 2.493M12.458 10.22a9.337 9.337 0 014.121-.952c2.148 0 4.122.72 5.7 1.93" />
                    </svg>
                </div>
                <div class="ar-kpi-info">
                    <div class="ar-kpi-val">{{ (automation.enrolled_count ?? 0).toLocaleString() }}</div>
                    <div class="ar-kpi-label">Total Enrolled</div>
                    <div class="ar-kpi-sub">Contacts entered this funnel</div>
                </div>
            </div>

            <div class="ar-kpi-card">
                <div class="ar-kpi-icon is-yellow">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="20" height="20">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
                    </svg>
                </div>
                <div class="ar-kpi-info">
                    <div class="ar-kpi-val">{{ activeContactsCount.toLocaleString() }}</div>
                    <div class="ar-kpi-label">Active / In Progress</div>
                    <div class="ar-kpi-sub">Currently running through steps</div>
                </div>
            </div>

            <div class="ar-kpi-card">
                <div class="ar-kpi-icon is-green">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="20" height="20">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                </div>
                <div class="ar-kpi-info">
                    <div class="ar-kpi-val">{{ (automation.completed_count ?? 0).toLocaleString() }}</div>
                    <div class="ar-kpi-label">Funnel Completed</div>
                    <div class="ar-kpi-sub">Reached completion step</div>
                </div>
            </div>

            <div class="ar-kpi-card">
                <div class="ar-kpi-icon is-red">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="20" height="20">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" />
                    </svg>
                </div>
                <div class="ar-kpi-info">
                    <div class="ar-kpi-val">{{ (automation.error_count ?? 0).toLocaleString() }}</div>
                    <div class="ar-kpi-label">Errors Encountered</div>
                    <div class="ar-kpi-sub">Failed step execution</div>
                </div>
            </div>
        </div>

        <!-- Tabs Navigation -->
        <div class="ar-tabs-wrap">
            <div class="ar-tabs">
                <button
                    v-for="tab in tabs"
                    :key="tab.id"
                    class="ar-tab"
                    :class="{ 'is-active': activeTab === tab.id }"
                    @click="activeTab = tab.id"
                >
                    {{ tab.label }}
                </button>
            </div>
        </div>

        <!-- TAB CONTENT: OVERVIEW & EMAIL METRICS -->
        <div v-if="activeTab === 'overview'" class="ar-tab-pane">
            <!-- Funnel Conversion Flow Chart Card -->
            <div class="ar-card ar-chart-card">
                <div class="ar-card-header flex justify-between items-center" style="display:flex; justify-content:space-between; align-items:center;">
                    <span style="font-weight:700; font-size:15px; color:#1e293b;">Funnel Steps Conversion Flow</span>
                    <span style="font-size:12px; color:#64748b; font-weight:500;">Total contacts passing through each step</span>
                </div>
                <div class="ar-card-body" style="height: 340px; position: relative; padding: 24px;">
                    <canvas ref="funnelChartCanvas"></canvas>
                </div>
            </div>

            <div class="ar-row-grid">
                <!-- Funnel Structure Info -->
                <div class="ar-card">
                    <div class="ar-card-header">Funnel Design Summary</div>
                    <div class="ar-card-body" style="padding: 24px 24px 8px 24px;">
                        <div class="ar-summary-row">
                            <span class="label">Trigger Source</span>
                            <span class="value">{{ triggerLabel(triggerNode?.sub || 'Unknown') }}</span>
                        </div>
                        <div class="ar-summary-row">
                            <span class="label">Total Steps Count</span>
                            <span class="value">{{ totalSteps }} steps</span>
                        </div>
                        <div class="ar-summary-row">
                            <span class="label">Email Sequences</span>
                            <span class="value">{{ emailNodesCount }} send nodes</span>
                        </div>
                        <div class="ar-summary-row" v-if="triggerNode?.config?.logical_operator">
                            <span class="label">Trigger Logic</span>
                            <span class="value">{{ triggerNode.config.logical_operator }}</span>
                        </div>
                    </div>
                </div>

                <!-- Email Performance (If contains Email nodes) -->
                <div class="ar-card">
                    <div class="ar-card-header">Email Delivery & Engagement</div>
                    <div class="ar-card-body">
                        <div class="ar-email-metrics" style="display: flex; gap: 16px; align-items: center; justify-content: space-between; flex-wrap: wrap;">
                            <!-- Delivered Count -->
                            <div class="metric-item-delivered" style="flex: 1; display: flex; flex-direction: column; align-items: center; text-align: center; background: #f8fafc; border: 1px solid #f1f5f9; border-radius: 12px; padding: 20px; min-width: 120px; height: 130px; justify-content: center;">
                                <div style="width: 40px; height: 40px; border-radius: 50%; background: #e0f2fe; color: #0284c7; display: flex; align-items: center; justify-content: center; margin-bottom: 8px;">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="20" height="20">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5" />
                                    </svg>
                                </div>
                                <div class="metric-num" style="font-size: 24px; font-weight: 700; color: #0f172a; line-height: 1.2;">{{ (automation.emails_sent ?? 0).toLocaleString() }}</div>
                                <div class="metric-lbl" style="font-size: 11px; font-weight: 600; color: #64748b; text-transform: uppercase; margin-top: 4px;">Delivered</div>
                            </div>
                            
                            <!-- Circular Stats -->
                            <div class="metric-circles-grid" style="flex: 2.2; display: flex; gap: 16px; justify-content: space-between; align-items: center; min-width: 250px;">
                                <!-- Open Rate Circle -->
                                <div style="display: flex; flex-direction: column; align-items: center; flex: 1;">
                                    <div class="visual-metric-wrapper" style="position: relative; width: 72px; height: 72px; display: flex; align-items: center; justify-content: center; margin-bottom: 6px;">
                                        <svg width="72" height="72" style="transform: rotate(-90deg);">
                                            <circle stroke="#f1f5f9" stroke-width="5" fill="transparent" r="28" cx="36" cy="36" />
                                            <circle stroke="#3b82f6" stroke-width="5" fill="transparent" r="28" cx="36" cy="36"
                                                    :stroke-dasharray="2 * Math.PI * 28"
                                                    :stroke-dashoffset="2 * Math.PI * 28 * (1 - Math.min(100, Math.max(0, parseFloat(openRate))) / 100)"
                                                    stroke-linecap="round"
                                                    style="transition: stroke-dashoffset 0.5s ease-in-out;" />
                                        </svg>
                                        <div style="position: absolute; font-size: 13px; font-weight: 700; color: #0f172a;">
                                            {{ openRate }}%
                                        </div>
                                    </div>
                                    <div class="metric-lbl" style="font-size: 11px; font-weight: 600; color: #475569; text-align: center;">Open Rate</div>
                                    <span class="metric-sub" style="font-size: 10px; color: #94a3b8; margin-top: 2px; text-align: center;">{{ (automation.unique_opens ?? 0).toLocaleString() }} unique</span>
                                </div>

                                <!-- Click Rate Circle -->
                                <div style="display: flex; flex-direction: column; align-items: center; flex: 1;">
                                    <div class="visual-metric-wrapper" style="position: relative; width: 72px; height: 72px; display: flex; align-items: center; justify-content: center; margin-bottom: 6px;">
                                        <svg width="72" height="72" style="transform: rotate(-90deg);">
                                            <circle stroke="#f1f5f9" stroke-width="5" fill="transparent" r="28" cx="36" cy="36" />
                                            <circle stroke="#10b981" stroke-width="5" fill="transparent" r="28" cx="36" cy="36"
                                                    :stroke-dasharray="2 * Math.PI * 28"
                                                    :stroke-dashoffset="2 * Math.PI * 28 * (1 - Math.min(100, Math.max(0, parseFloat(clickRate))) / 100)"
                                                    stroke-linecap="round"
                                                    style="transition: stroke-dashoffset 0.5s ease-in-out;" />
                                        </svg>
                                        <div style="position: absolute; font-size: 13px; font-weight: 700; color: #0f172a;">
                                            {{ clickRate }}%
                                        </div>
                                    </div>
                                    <div class="metric-lbl" style="font-size: 11px; font-weight: 600; color: #475569; text-align: center;">Click Rate</div>
                                    <span class="metric-sub" style="font-size: 10px; color: #94a3b8; margin-top: 2px; text-align: center;">{{ (automation.unique_clicks ?? 0).toLocaleString() }} unique</span>
                                </div>

                                <!-- Bounce Rate Circle -->
                                <div style="display: flex; flex-direction: column; align-items: center; flex: 1;">
                                    <div class="visual-metric-wrapper" style="position: relative; width: 72px; height: 72px; display: flex; align-items: center; justify-content: center; margin-bottom: 6px;">
                                        <svg width="72" height="72" style="transform: rotate(-90deg);">
                                            <circle stroke="#f1f5f9" stroke-width="5" fill="transparent" r="28" cx="36" cy="36" />
                                            <circle stroke="#ef4444" stroke-width="5" fill="transparent" r="28" cx="36" cy="36"
                                                    :stroke-dasharray="2 * Math.PI * 28"
                                                    :stroke-dashoffset="2 * Math.PI * 28 * (1 - Math.min(100, Math.max(0, parseFloat(bounceRate))) / 100)"
                                                    stroke-linecap="round"
                                                    style="transition: stroke-dashoffset 0.5s ease-in-out;" />
                                        </svg>
                                        <div style="position: absolute; font-size: 13px; font-weight: 700; color: #0f172a;">
                                            {{ bounceRate }}%
                                        </div>
                                    </div>
                                    <div class="metric-lbl" style="font-size: 11px; font-weight: 600; color: #475569; text-align: center;">Bounce Rate</div>
                                    <span class="metric-sub" style="font-size: 10px; color: #ef4444; margin-top: 2px; text-align: center;">{{ (automation.emails_bounced ?? 0).toLocaleString() }} bounced</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- TAB CONTENT: FUNNEL STEPS BREAKDOWN -->
        <div v-else-if="activeTab === 'steps'" class="ar-tab-pane">
            <div class="ar-card">
                <div class="ar-card-header">Funnel Steps Flow Performance</div>
                <div class="ar-table-scroll">
                    <table class="ar-table">
                        <thead>
                            <tr>
                                <th>Step Name</th>
                                <th>Type</th>
                                <th style="text-align: center;">Completed / Succeeded</th>
                                <th style="text-align: center;">Processing / Delayed</th>
                                <th style="text-align: center;">Errors / Failed</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="node in orderedNodes" :key="node.id">
                                <td>
                                    <div class="ar-node-name-cell">
                                        <div class="ar-node-bullet" :style="{ backgroundColor: getNodeColor(node.type) }"></div>
                                        <div>
                                            <div class="node-title">{{ node.title }}</div>
                                            <div class="node-sub" v-if="node.sub">{{ node.sub }}</div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="ar-node-type-badge">{{ node.type.toUpperCase().replace('_', ' ') }}</span>
                                </td>
                                <td style="text-align: center;" class="text-green font-semibold">
                                    {{ (nodeStats[node.id]?.success ?? 0).toLocaleString() }}
                                </td>
                                <td style="text-align: center;" class="text-yellow font-semibold">
                                    {{ (nodeStats[node.id]?.processing ?? 0).toLocaleString() }}
                                </td>
                                <td style="text-align: center;" class="text-red font-semibold">
                                    {{ (nodeStats[node.id]?.error ?? 0).toLocaleString() }}
                                </td>
                            </tr>
                            <tr v-if="orderedNodes.length === 0">
                                <td colspan="5" class="ar-empty-state">No steps defined in this automation funnel.</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- TAB CONTENT: ENROLLED CONTACTS -->
        <div v-else-if="activeTab === 'contacts'" class="ar-tab-pane">
            <div class="ar-card">
                <div class="ar-card-header flex justify-between items-center flex-wrap gap-4" style="display:flex; justify-content:space-between; align-items:center;">
                    <span>Enrolled Contacts Directory</span>
                    <!-- Contact Search input -->
                    <div class="ar-search-box">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" width="14" height="14">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"/>
                        </svg>
                        <input type="text" v-model="contactSearch" @input="onContactSearch" placeholder="Search contacts...">
                    </div>
                </div>

                <!-- Status tabs -->
                <div class="ar-contact-filters" style="display:flex; border-bottom:1px solid #f1f5f9; padding: 12px 24px; gap: 8px; background: #f8fafc; flex-wrap: wrap;">
                    <button 
                        v-for="statusOpt in [
                            { value: '', label: 'All Contacts', color: '#475569', bg: '#f1f5f9' },
                            { value: 'active', label: 'Active', color: '#d97706', bg: '#fffbeb' },
                            { value: 'completed', label: 'Completed', color: '#10b981', bg: '#ecfdf5' },
                            { value: 'failed', label: 'Failed', color: '#ef4444', bg: '#fef2f2' }
                        ]"
                        :key="statusOpt.value"
                        class="contact-status-tab"
                        @click="filterContactsByStatus(statusOpt.value)"
                        style="border: 1px solid transparent; padding: 6px 14px; font-size:12px; font-weight:600; border-radius: 6px; cursor:pointer; transition: all 0.15s ease-in-out;"
                        :style="(filters.contact_status || '') === statusOpt.value 
                            ? { color: statusOpt.color, background: statusOpt.bg, borderColor: statusOpt.color, boxWidth: '1px', boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }
                            : { color: '#64748b', background: '#fff', borderColor: '#e2e8f0' }"
                    >
                        {{ statusOpt.label }}
                    </button>
                </div>

                <div class="ar-table-scroll">
                    <table class="ar-table">
                        <thead>
                            <tr>
                                <th>Contact</th>
                                <th>Email</th>
                                <th>Enrolled Date</th>
                                <th>Current Funnel Status</th>
                                <th style="text-align: right;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="contact in contacts.data" :key="contact.id">
                                <td>
                                    <div class="font-semibold text-slate-800">{{ contact.name || 'Unnamed Contact' }}</div>
                                </td>
                                <td>{{ contact.email }}</td>
                                <td>{{ formatDateTime(contact.enrolled_at) }}</td>
                                <td>
                                    <span :class="['ar-status-pill', `is-${contact.status}`]">
                                        {{ contact.status === 'completed' ? 'END' : contact.status.toUpperCase() }}
                                    </span>
                                </td>
                                <td style="text-align: right;">
                                    <button class="btn btn-outline btn-xs" @click="viewContactJourney(contact)">
                                        View Journey
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="12" height="12" style="margin-left: 4px;">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
                                        </svg>
                                    </button>
                                </td>
                            </tr>
                            <tr v-if="contacts.data.length === 0">
                                <td colspan="5" class="ar-empty-state">No contacts found in this funnel.</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="ar-card-footer" v-if="contacts.links && contacts.links.length > 3">
                    <Pagination :paginator="contacts" page-name="contacts_page" preserve-state />
                </div>
            </div>
        </div>

        <!-- TAB CONTENT: GENERAL ACTIVITY LOGS -->
        <div v-else-if="activeTab === 'logs'" class="ar-tab-pane">
            <div class="ar-card">
                <div class="ar-card-header flex justify-between items-center flex-wrap gap-4">
                    <span>Funnel Activity Stream Log</span>
                    <CwSelect 
                        v-model="logFilter" 
                        :options="[
                            {value: '', label: 'All Events'},
                            {value: 'enrolled', label: 'Enrollments'},
                            {value: 'node_processing', label: 'In-Progress Steps'},
                            {value: 'node_success', label: 'Successful Actions'},
                            {value: 'node_error', label: 'Errors / Failures'},
                            {value: 'completed', label: 'Completions'}
                        ]" 
                        @change="onLogFilterChange" 
                        style="width: 190px;" 
                    />
                </div>
                <div class="ar-table-scroll">
                    <table class="ar-table">
                        <thead>
                            <tr>
                                <th>Time</th>
                                <th>Contact</th>
                                <th>Event Type</th>
                                <th>Step Name</th>
                                <th>Detail / Result</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="event in events.data" :key="event.id">
                                <td style="white-space: nowrap;">{{ formatDateTime(event.created_at) }}</td>
                                <td>
                                    <div v-if="event.contact">
                                        <div class="font-medium">{{ event.contact.name }}</div>
                                        <div class="text-xs text-slate-400">{{ event.contact.email }}</div>
                                    </div>
                                    <span v-else class="text-slate-400">-</span>
                                </td>
                                <td>
                                    <span :class="['ar-log-badge', `is-${event.event_type}`]">
                                        {{ event.event_type === 'completed' ? 'END' : event.event_type.replace('node_', '').toUpperCase() }}
                                    </span>
                                </td>
                                <td>
                                    <span class="font-medium" v-if="event.node_id && getNodeTitle(event.node_id)">
                                        {{ getNodeTitle(event.node_id) }}
                                    </span>
                                    <span v-else-if="event.event_type === 'completed'" class="font-semibold text-slate-700">End</span>
                                    <span v-else class="text-slate-400">Funnel Main</span>
                                </td>
                                <td>
                                    <div class="ar-log-reason" :title="event.reason">{{ event.reason || 'No description available.' }}</div>
                                </td>
                            </tr>
                            <tr v-if="events.data.length === 0">
                                <td colspan="5" class="ar-empty-state">No logs recorded matching current filter.</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="ar-card-footer" v-if="events.links && events.links.length > 3">
                    <Pagination :paginator="events" page-name="events_page" preserve-state />
                </div>
            </div>
        </div>

        <!-- DYNAMIC CLICK JOURNEY DRAWER (INDIVIDUAL CONTACT ANALYTICS) -->
        <Teleport to="body">
            <div class="ar-drawer-backdrop" v-if="isDrawerOpen" @click="closeDrawer"></div>
            <Transition name="slide-drawer">
                <div class="ar-drawer" v-if="isDrawerOpen">
                    <div class="ar-drawer-header">
                        <div>
                            <div class="text-xs font-semibold text-teal-600 uppercase tracking-wider">Contact Journey Analytics</div>
                            <h3 class="ar-drawer-title">{{ selectedContact?.name || 'Contact Journey' }}</h3>
                            <div class="text-xs text-slate-400">{{ selectedContact?.email }}</div>
                        </div>
                        <button class="ar-drawer-close" @click="closeDrawer" aria-label="Close drawer">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="20" height="20">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>

                    <div class="ar-drawer-body">
                        <!-- Loading spinner -->
                        <div v-if="loadingJourney" class="ar-drawer-loading">
                            <div class="ar-spinner"></div>
                            <span>Retrieving contact path...</span>
                        </div>

                        <!-- Timeline journey list -->
                        <div v-else class="ar-journey-timeline">
                            <div v-for="(step, idx) in contactJourney" :key="step.id" class="ar-journey-item">
                                <!-- Timeline Line -->
                                <div class="ar-journey-line" v-if="idx < contactJourney.length - 1"></div>

                                <!-- Icon node -->
                                <div class="ar-journey-bullet" :style="{ backgroundColor: getNodeColor(step.node_type) }">
                                    <span class="bullet-inner"></span>
                                </div>

                                <!-- Step content details -->
                                <div class="ar-journey-content">
                                    <div class="flex justify-between items-start gap-4">
                                        <h4 class="step-title font-semibold text-slate-800">{{ step.node_title }}</h4>
                                        <span class="step-time">{{ formatTimeAgo(step.created_at) }}</span>
                                    </div>
                                    <div class="flex items-center gap-2 mt-1">
                                        <span :class="['ar-step-status-pill', `is-${step.event_type}`]">
                                            {{ step.event_type === 'completed' ? 'END' : step.event_type.replace('node_', '').toUpperCase() }}
                                        </span>
                                        <span class="text-xs text-slate-400">{{ step.node_type.toUpperCase().replace('_', ' ') }}</span>
                                    </div>
                                    <p class="step-desc text-slate-600 mt-2" v-if="step.reason">{{ step.reason }}</p>
                                    <span class="step-date-full">{{ formatDateTime(step.created_at) }}</span>
                                </div>
                            </div>

                            <div v-if="contactJourney.length === 0" class="text-center py-12 text-slate-400">
                                No journey events found for this contact.
                            </div>
                        </div>
                    </div>
                </div>
            </Transition>
        </Teleport>
    </AppLayout>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import axios from 'axios';
import Chart from 'chart.js/auto';
import AppLayout from '@/Layouts/AppLayout.vue';
import Pagination from '@/Components/Pagination.vue';
import CwDateTimePicker from '@/Components/CwDateTimePicker.vue';
import CwSelect from '@/Components/CwSelect.vue';
import { useTenantTimezone } from '@/Composables/useTenantTimezone';

const { formatDateTime } = useTenantTimezone();

const props = defineProps({
    automation: Object,
    nodeStats: Object,
    contacts: Object,
    events: Object,
    filters: Object,
});

const activeTab = ref('overview');
const contactSearch = ref(props.filters.contact_search || '');
const logFilter = ref(props.filters.event_type || '');
const startDate = ref(props.filters.start_date || '');
const endDate = ref(props.filters.end_date || '');

// Contact Journey Drawer State
const selectedContact = ref(null);
const contactJourney = ref([]);
const loadingJourney = ref(false);
const isDrawerOpen = ref(false);

const tabs = [
    { id: 'overview', label: 'Overview' },
    { id: 'steps', label: 'Steps Performance' },
    { id: 'contacts', label: 'Enrolled Contacts' },
    { id: 'logs', label: 'Activity Logs' },
];

const nodes = computed(() => props.automation.settings.nodes || []);
const edges = computed(() => props.automation.settings.edges || []);

const triggerNode = computed(() => nodes.value.find(n => n.type === 'trigger'));
const totalSteps = computed(() => nodes.value.length);
const emailNodesCount = computed(() => nodes.value.filter(n => n.type === 'email' || n.type === 'campaign_email').length);

const activeContactsCount = computed(() => {
    return Math.max(0, (props.automation.enrolled_count ?? 0) - (props.automation.completed_count ?? 0));
});

// Calculate Open and Click rates
const openRate = computed(() => {
    const sent = props.automation.emails_sent ?? 0;
    const opens = props.automation.unique_opens ?? 0;
    return sent > 0 ? ((opens / sent) * 100).toFixed(1) : '0.0';
});

const clickRate = computed(() => {
    const sent = props.automation.emails_sent ?? 0;
    const clicks = props.automation.unique_clicks ?? 0;
    return sent > 0 ? ((clicks / sent) * 100).toFixed(1) : '0.0';
});

const bounceRate = computed(() => {
    const sent = props.automation.emails_sent ?? 0;
    const bounces = props.automation.emails_bounced ?? 0;
    return sent > 0 ? ((bounces / sent) * 100).toFixed(1) : '0.0';
});

// Order steps logically by walking down the edges from trigger node
const orderedNodes = computed(() => {
    if (nodes.value.length === 0) return [];
    
    const trigger = nodes.value.find(n => n.type === 'trigger');
    if (!trigger) return nodes.value;

    const ordered = [];
    const visited = new Set();

    function traverse(nodeId) {
        if (visited.has(nodeId)) return;
        visited.add(nodeId);
        
        const node = nodes.value.find(n => n.id === nodeId);
        if (node) ordered.push(node);

        // Find child edges
        const children = edges.value.filter(e => e.source === nodeId).map(e => e.target);
        children.forEach(traverse);
    }

    traverse(trigger.id);

    // Append any orphaned nodes that were not reachable
    nodes.value.forEach(node => {
        if (!visited.has(node.id)) {
            ordered.push(node);
        }
    });

    return ordered;
});

// Chart.js Configuration & Funnel Render
const funnelChartCanvas = ref(null);
let chartInstance = null;

function renderFunnelChart() {
    if (!funnelChartCanvas.value) return;

    if (chartInstance) {
        chartInstance.destroy();
    }

    const steps = orderedNodes.value;
    if (steps.length === 0) return;

    const labels = steps.map(node => node.title);

    // Total reached = success + processing + error
    const totalReachedData = steps.map(node => {
        const stats = props.nodeStats[node.id] || {};
        return (stats.success ?? 0) + (stats.processing ?? 0) + (stats.error ?? 0);
    });

    // Succeeded at step
    const successData = steps.map(node => {
        const stats = props.nodeStats[node.id] || {};
        return stats.success ?? 0;
    });

    const ctx = funnelChartCanvas.value.getContext('2d');
    
    const successGradient = ctx.createLinearGradient(0, 0, 0, 300);
    successGradient.addColorStop(0, 'rgba(15, 118, 110, 0.8)');
    successGradient.addColorStop(1, 'rgba(20, 184, 166, 0.15)');

    const lineGradient = ctx.createLinearGradient(0, 0, 0, 300);
    lineGradient.addColorStop(0, 'rgba(59, 130, 246, 0.4)');
    lineGradient.addColorStop(1, 'rgba(59, 130, 246, 0.01)');

    chartInstance = new Chart(funnelChartCanvas.value, {
        type: 'bar',
        data: {
            labels,
            datasets: [
                {
                    type: 'line',
                    label: 'Total Reached',
                    data: totalReachedData,
                    borderColor: '#3b82f6',
                    backgroundColor: lineGradient,
                    borderWidth: 2,
                    tension: 0.3,
                    pointRadius: 4,
                    pointBackgroundColor: '#3b82f6',
                    fill: true,
                },
                {
                    type: 'bar',
                    label: 'Succeeded',
                    data: successData,
                    backgroundColor: successGradient,
                    borderColor: '#0f766e',
                    borderWidth: 1.5,
                    borderRadius: 6,
                    barPercentage: 0.45,
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        boxWidth: 12,
                        font: { family: 'Inter, system-ui, sans-serif', size: 12 }
                    }
                },
                tooltip: {
                    backgroundColor: '#0f172a',
                    padding: 12,
                    titleFont: { family: 'Inter, system-ui, sans-serif', weight: 'bold' },
                    bodyFont: { family: 'Inter, system-ui, sans-serif' },
                    callbacks: {
                        label: function(context) {
                            const value = context.raw;
                            const label = context.dataset.label;
                            const index = context.dataIndex;
                            
                            let suffix = '';
                            if (index > 0 && totalReachedData[0] > 0) {
                                const initial = totalReachedData[0];
                                const pct = ((value / initial) * 100).toFixed(1);
                                suffix = ` (${pct}% conversion from start)`;
                            } else if (index === 0 && value > 0) {
                                suffix = ' (Baseline - 100%)';
                            }
                            
                            return `${label}: ${value.toLocaleString()}${suffix}`;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: { color: '#f8fafc' },
                    ticks: {
                        precision: 0,
                        color: '#64748b',
                        font: { family: 'Inter, system-ui, sans-serif' }
                    }
                },
                x: {
                    grid: { display: false },
                    ticks: {
                        color: '#475569',
                        font: { family: 'Inter, system-ui, sans-serif', weight: 600, size: 12 }
                    }
                }
            }
        }
    });
}

onMounted(() => {
    if (activeTab.value === 'overview') {
        renderFunnelChart();
    }
});

watch(activeTab, (newTab) => {
    if (newTab === 'overview') {
        nextTick(() => {
            renderFunnelChart();
        });
    }
});

function getNodeTitle(nodeId) {
    const node = nodes.value.find(n => n.id === nodeId);
    return node ? node.title : null;
}

function getNodeColor(type) {
    const colors = {
        trigger: '#3b82f6',     // Blue
        email: '#2563eb',       // Indigo
        campaign_email: '#0284c7', // Sky Blue
        wait: '#f59e0b',        // Amber/Orange
        condition: '#8b5cf6',   // Purple
        apply_tag: '#10b981',   // Green
        remove_tag: '#10b981',  // Green
        apply_list: '#06b6d4',  // Cyan
        remove_list: '#06b6d4', // Cyan
        webhook: '#ec4899',     // Pink
        ab_split: '#6366f1',    // Indigo-light
        update_field: '#14b8a6',// Teal
        end: '#6b7280',         // Gray
    };
    return colors[type] || '#94a3b8';
}

function statusClass(status) {
    return {
        active: 'ar-badge--active',
        paused: 'ar-badge--paused',
        draft: 'ar-badge--draft',
    }[status] || 'ar-badge--draft';
}

function triggerLabel(sub) {
    const map = {
        'New User Sign Up': 'New User Sign Up',
        'Contact Subscribes to List': 'Contact Subscribes to List',
        'Tag Applied': 'Tag Applied',
        'Contact Created': 'Contact Created',
        new_user_signup: 'New User Sign Up',
        subscribes_to_list: 'Contact Subscribes to List',
        tag_applied: 'Tag Applied',
        contact_created: 'Contact Created',
    };
    return map[sub] || sub;
}

// Contacts Search method
let searchTimer = null;
function onContactSearch() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
        router.get(`/automation/${props.automation.id}/report`, {
            contact_search: contactSearch.value || undefined,
            contact_status: props.filters.contact_status || undefined,
            event_type: logFilter.value || undefined,
            start_date: startDate.value || undefined,
            end_date: endDate.value || undefined,
        }, { preserveState: true, replace: true, only: ['contacts'] });
    }, 400);
}

// Contacts Status tabs filter
function filterContactsByStatus(status) {
    router.get(`/automation/${props.automation.id}/report`, {
        contact_search: contactSearch.value || undefined,
        contact_status: status || undefined,
        event_type: logFilter.value || undefined,
        start_date: startDate.value || undefined,
        end_date: endDate.value || undefined,
    }, { preserveState: true, replace: true, only: ['contacts', 'filters'] });
}

// Log filters change
function onLogFilterChange() {
    router.get(`/automation/${props.automation.id}/report`, {
        contact_search: contactSearch.value || undefined,
        contact_status: props.filters.contact_status || undefined,
        event_type: logFilter.value || undefined,
        start_date: startDate.value || undefined,
        end_date: endDate.value || undefined,
    }, { preserveState: true, replace: true, only: ['events'] });
}

function onDateChange() {
    router.get(`/automation/${props.automation.id}/report`, {
        contact_search: contactSearch.value || undefined,
        contact_status: props.filters.contact_status || undefined,
        event_type: logFilter.value || undefined,
        start_date: startDate.value || undefined,
        end_date: endDate.value || undefined,
    }, { preserveState: true, replace: true });
}

function clearDates() {
    startDate.value = '';
    endDate.value = '';
    onDateChange();
}

// Contact Journey Drawer API trigger
function viewContactJourney(contact) {
    selectedContact.value = contact;
    loadingJourney.value = true;
    isDrawerOpen.value = true;

    axios.get(`/automation/${props.automation.id}/contacts/${contact.id}/journey`)
        .then(res => {
            contactJourney.value = res.data.journey || [];
            loadingJourney.value = false;
        })
        .catch(err => {
            console.error('Failed to load contact journey', err);
            loadingJourney.value = false;
        });
}

function closeDrawer() {
    isDrawerOpen.value = false;
    selectedContact.value = null;
    contactJourney.value = [];
}

// Relative time ago formatting
function formatTimeAgo(isoString) {
    if (!isoString) return '';
    const date = new Date(isoString);
    const now = new Date();
    const diffMs = now - date;
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHr = Math.floor(diffMin / 60);
    
    if (diffSec < 60) return 'Just now';
    if (diffMin < 60) return `${diffMin}m ago`;
    if (diffHr < 24) return `${diffHr}h ago`;
    return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
</script>

<style scoped>
.ar-header {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.02);

    @media (max-width: 640px) {
        padding: 16px;
    }
}

.ar-back {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    font-weight: 500;
    color: var(--text-secondary);
    text-decoration: none;
    margin-bottom: 16px;
    transition: color 0.15s;
}
.ar-back:hover {
    color: var(--text-primary);
}

.ar-title-row {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 20px;

    @media (max-width: 640px) {
        flex-direction: column;
        gap: 12px;
    }
}

.ar-title {
    font-size: 24px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0 0 8px 0;

    @media (max-width: 640px) {
        font-size: 20px;
    }
}

.ar-meta {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
    color: var(--text-secondary);
    font-size: 13px;
}

.ar-meta-sep {
    color: var(--text-muted);
    margin: 0 6px;
    font-weight: 600;
}

.ar-badge {
    display: inline-block;
    font-size: 11px;
    font-weight: 600;
    padding: 3px 10px;
    border-radius: 100px;
}

.ar-badge--active {
    background: var(--success-light);
    color: var(--success);
}

.ar-badge--paused {
    background: var(--warning-light);
    color: var(--warning);
}

.ar-badge--draft {
    background: var(--bg-hover);
    color: var(--text-secondary);
}

.ar-title-actions {
    flex-shrink: 0;
}

/* KPI Overview Grid */
.ar-kpi-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 20px;
    margin-bottom: 24px;

    @media (max-width: 480px) {
        grid-template-columns: 1fr;
    }
}

.ar-kpi-card {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.02);

    @media (max-width: 480px) {
        padding: 16px;
    }
}

.ar-kpi-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.ar-kpi-icon.is-blue { background: var(--info-light, #eff6ff); color: var(--info, #3b82f6); }
.ar-kpi-icon.is-yellow { background: var(--warning-light, #fffbeb); color: var(--warning, #d97706); }
.ar-kpi-icon.is-green { background: var(--success-light, #ecfdf5); color: var(--success, #10b981); }
.ar-kpi-icon.is-red { background: var(--danger-light, #fef2f2); color: var(--danger, #ef4444); }

.ar-kpi-info {
    display: flex;
    flex-direction: column;
}

.ar-kpi-val {
    font-size: 26px;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1.1;
}

.ar-kpi-label {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-secondary);
    margin: 4px 0 2px;
}

.ar-kpi-sub {
    font-size: 11px;
    color: var(--text-muted);
}

/* Tabs */
.ar-tabs-wrap {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    margin-bottom: 24px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.02);
    overflow: hidden;
}

.ar-tabs {
    display: flex;
    padding: 0 12px;
    overflow-x: auto;
}

.ar-tab {
    padding: 16px 20px;
    font-size: 14px;
    font-weight: 600;
    color: var(--text-secondary);
    border: none;
    background: none;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    transition: all 0.15s ease;
    white-space: nowrap;
    flex-shrink: 0;
}

.ar-tab:hover {
    color: var(--text-primary);
}

.ar-tab.is-active {
    color: var(--active-text, #2563eb);
    border-bottom-color: var(--active-text, #2563eb);
}

/* Tab Pane content */
.ar-tab-pane {
    display: flex;
    flex-direction: column;
    gap: 24px;
}

/* Row Grid */
.ar-row-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
}

@media (max-width: 768px) {
    .ar-row-grid {
        grid-template-columns: 1fr;
    }
}

.ar-card {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.02);
    overflow: hidden;
}

.ar-card-header {
    padding: 18px 24px;
    font-size: 15px;
    font-weight: 700;
    color: var(--text-primary);
    background: var(--bg-hover);
    border-bottom: 1px solid var(--border-color);
}

.ar-card-body {
    padding: 24px;

    @media (max-width: 480px) {
        padding: 16px;
    }
}

.ar-summary-row {
    display: flex;
    justify-content: space-between;
    padding: 12px 0;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
    flex-wrap: wrap;
    gap: 6px;
}

.ar-summary-row:last-child {
    border-bottom: none;
}

.ar-summary-row .label {
    color: var(--text-secondary);
}

.ar-summary-row .value {
    font-weight: 600;
    color: var(--text-primary);
}

/* Email performance display */
.ar-email-metrics {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;

    @media (max-width: 480px) {
        grid-template-columns: 1fr;
    }
}

.metric-item {
    background: var(--bg-hover);
    border-radius: 8px;
    padding: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    border: 1px solid var(--border-color);
}

.metric-num {
    font-size: 20px;
    font-weight: 700;
    color: var(--text-primary);
}

.metric-lbl {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
    margin-top: 4px;
}

.metric-sub {
    font-size: 10px;
    color: var(--text-muted);
    margin-top: 2px;
}

/* Tables */
.ar-table-scroll {
    overflow-x: auto;
}

.ar-table {
    width: 100%;
    border-collapse: collapse;
}

.ar-table th {
    text-align: left;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--text-secondary);
    background: var(--bg-hover);
    padding: 12px 24px;
    border-bottom: 1px solid var(--border-color);
    white-space: nowrap;
}

.ar-table td {
    padding: 14px 24px;
    font-size: 13px;
    color: var(--text-primary);
    border-bottom: 1px solid var(--border-color);

    @media (max-width: 640px) {
        padding: 10px 14px;
    }
}

.ar-table tr:last-child td {
    border-bottom: none;
}

.ar-table tr:hover td {
    background: var(--bg-hover);
}

/* Contact name link */
.ar-contact-link {
    color: var(--active-text, #2563eb);
    text-decoration: none;
    font-weight: 600;
}
.ar-contact-link:hover {
    text-decoration: underline;
}

/* Controls bar */
.ar-controls-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 12px 20px;
    margin-bottom: 20px;
    flex-wrap: wrap;

    @media (max-width: 640px) {
        flex-direction: column;
        align-items: flex-start;
        padding: 12px;
    }
}

.controls-title-wrap {
    display: flex;
    align-items: center;
    gap: 6px;
}

.controls-title {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-secondary);
}

.ar-date-filters {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.date-input-wrap {
    min-width: 140px;

    @media (max-width: 480px) {
        min-width: 100%;
    }
}

.date-sep {
    font-size: 13px;
    color: var(--text-muted);
    white-space: nowrap;
}

/* Drawer / slide-in panel */
.ar-drawer-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.3);
    z-index: 600;
    backdrop-filter: blur(2px);
}

.ar-drawer {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    width: 420px;
    background: var(--bg-surface);
    box-shadow: -4px 0 24px rgba(0,0,0,0.1);
    z-index: 610;
    display: flex;
    flex-direction: column;

    @media (max-width: 640px) {
        width: 100%;
    }
}

.ar-table td {
    font-size: 13.5px;
    color: #334155;
    padding: 16px 24px;
    border-bottom: 1px solid #f1f5f9;
}

.ar-table tbody tr:hover {
    background: #f8fafc;
}

.ar-empty-state {
    text-align: center;
    padding: 48px 24px !important;
    color: #94a3b8;
}

.ar-node-name-cell {
    display: flex;
    align-items: center;
    gap: 12px;
}

.ar-node-bullet {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    flex-shrink: 0;
}

.node-title {
    font-weight: 600;
    color: #0f172a;
}

.node-sub {
    font-size: 11px;
    color: #94a3b8;
    margin-top: 2px;
}

.ar-node-type-badge {
    font-size: 10px;
    font-weight: 700;
    background: #f1f5f9;
    color: #475569;
    padding: 2px 6px;
    border-radius: 4px;
}

.ar-status-pill {
    display: inline-block;
    font-size: 10px;
    font-weight: 700;
    padding: 2px 8px;
    border-radius: 100px;
}

.ar-status-pill.is-active {
    background: #e0f2fe;
    color: #0369a1;
}

.ar-status-pill.is-completed {
    background: #dcfce7;
    color: #15803d;
}

.ar-status-pill.is-failed {
    background: #fee2e2;
    color: #b91c1c;
}

.ar-log-badge {
    display: inline-block;
    font-size: 9px;
    font-weight: 700;
    padding: 1px 6px;
    border-radius: 4px;
}

.ar-log-badge.is-enrolled { background: #dbeafe; color: #1e40af; }
.ar-log-badge.is-node_processing { background: #fef3c7; color: #92400e; }
.ar-log-badge.is-node_success { background: #dcfce7; color: #166534; }
.ar-log-badge.is-sent { background: #e0f2fe; color: #075985; }
.ar-log-badge.is-node_error { background: #fee2e2; color: #991b1b; }
.ar-log-badge.is-completed { background: #f3e8ff; color: #6b21a8; }

.ar-log-reason {
    max-width: 320px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #64748b;
}

.ar-card-footer {
    padding: 16px 24px;
    border-top: 1px solid #f1f5f9;
    display: flex;
    justify-content: flex-end;
}

/* Custom details styling */
.font-semibold { font-weight: 600; }
.font-medium { font-weight: 500; }
.text-green { color: #10b981; }
.text-yellow { color: #f59e0b; }
.text-red { color: #ef4444; }
.flex { display: flex; }
.justify-between { justify-content: space-between; }
.items-center { align-items: center; }
.flex-wrap { flex-wrap: wrap; }
.gap-4 { gap: 16px; }

/* Filter select box and search */
.ar-select {
    padding: 6px 12px;
    border: 1px solid #cbd5e1;
    border-radius: 6px;
    font-size: 13.5px;
    background-color: #fff;
    outline: none;
}

.ar-search-box {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 6px;
    padding: 0 12px;
    height: 36px;
    width: 240px;
    transition: border-color 0.15s, box-shadow 0.15s;
}

.ar-search-box:hover {
    border-color: var(--active-text);
}

.ar-search-box:focus-within {
    border-color: var(--active-text);
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12);
}

.ar-search-box input {
    border: none !important;
    background: transparent !important;
    font-size: 12px;
    color: var(--text-primary);
    outline: none !important;
    box-shadow: none !important;
    width: 100%;
    height: 100%;
    padding: 0;
}

.ar-search-box input:focus {
    outline: none !important;
    box-shadow: none !important;
    border: none !important;
}

.ar-search-box svg {
    color: #94a3b8;
}

/* Global Date Range Filter Control Bar */
.ar-controls-bar {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 16px;
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    padding: 14px 24px;
    margin-bottom: 24px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.02);
    flex-wrap: wrap;
}

.controls-title-wrap {
    display: flex;
    align-items: center;
    gap: 8px;
}

.controls-title {
    font-size: 13px;
    font-weight: 600;
    color: #475569;
}

.ar-date-filters {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.date-input-wrap {
    width: 160px;
}

.date-sep {
    font-size: 12px;
    color: #94a3b8;
    font-weight: 500;
}

.clear-dates-btn {
    color: #64748b !important;
    border-color: #e2e8f0 !important;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0 !important;
    width: 30px;
    height: 30px;
    min-height: 30px;
}

.clear-dates-btn:hover {
    background: #f1f5f9 !important;
    color: #0f172a !important;
}

/* DRAWER SIDEBAR */
.ar-drawer-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(15, 23, 42, 0.4);
    backdrop-filter: blur(4px);
    z-index: 600;
}

.ar-drawer {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    width: 480px;
    max-width: 100%;
    background: #fff;
    box-shadow: -4px 0 24px rgba(0,0,0,0.1);
    z-index: 610;
    display: flex;
    flex-direction: column;
}

.ar-drawer-header {
    padding: 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.ar-drawer-title {
    font-size: 18px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 4px 0;
}

.ar-drawer-close {
    background: none;
    border: none;
    cursor: pointer;
    color: var(--text-muted);
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    transition: all 0.15s ease;
}

.ar-drawer-close:hover {
    color: var(--text-primary);
    background: var(--bg-hover);
}

.ar-drawer-body {
    flex-grow: 1;
    overflow-y: auto;
    padding: 24px;
}

.ar-drawer-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 16px;
    height: 200px;
    color: var(--text-secondary);
    font-size: 14px;
}

.ar-spinner {
    width: 28px;
    height: 28px;
    border: 3px solid var(--border-color);
    border-top-color: #0d9488;
    border-radius: 50%;
    animation: ar-spin 0.8s linear infinite;
}

@keyframes ar-spin {
    to { transform: rotate(360deg); }
}

/* Timeline elements */
.ar-journey-timeline {
    position: relative;
    padding-left: 8px;
}

.ar-journey-item {
    position: relative;
    padding-left: 32px;
    padding-bottom: 32px;
}

.ar-journey-item:last-child {
    padding-bottom: 0;
}

.ar-journey-line {
    position: absolute;
    left: 4px;
    top: 24px;
    bottom: -12px;
    width: 2px;
    background: var(--border-color);
}

.ar-journey-bullet {
    position: absolute;
    left: -4px;
    top: 4px;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 3px solid var(--bg-surface);
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.bullet-inner {
    width: 6px;
    height: 6px;
    background: var(--bg-surface);
    border-radius: 50%;
}

.ar-journey-content {
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 16px;
}

.step-title {
    font-size: 14px;
    margin: 0;
    color: var(--text-primary);
}

.step-time {
    font-size: 11px;
    color: var(--text-muted);
    white-space: nowrap;
}

.step-date-full {
    display: block;
    font-size: 10px;
    color: var(--text-muted);
    margin-top: 12px;
    text-align: right;
}

.ar-step-status-pill {
    display: inline-block;
    font-size: 8px;
    font-weight: 800;
    padding: 1px 5px;
    border-radius: 3px;
}

.ar-step-status-pill.is-enrolled { background: var(--info-light, #dbeafe); color: var(--info, #1e40af); }
.ar-step-status-pill.is-node_processing { background: var(--warning-light, #fef3c7); color: var(--warning, #92400e); }
.ar-step-status-pill.is-node_success { background: var(--success-light, #dcfce7); color: var(--success, #166534); }
.ar-step-status-pill.is-sent { background: var(--info-light, #e0f2fe); color: var(--info, #075985); }
.ar-step-status-pill.is-node_error { background: var(--danger-light, #fee2e2); color: var(--danger, #991b1b); }
.ar-step-status-pill.is-completed { background: rgba(124, 58, 237, 0.1); color: #7c3aed; }

.slide-drawer-enter-active,
.slide-drawer-leave-active {
    transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}

.slide-drawer-enter-from,
.slide-drawer-leave-to {
    transform: translateX(100%);
}
</style>
