<template>
    <AppLayout>
        <Head title="Dashboard" />

        <!-- Welcome Banner -->
        <div class="dashboard-welcome">
            <div class="dashboard-welcome-body">
                <h2>Welcome back, {{ user.name }}</h2>
                <p>
                    Here's what's happening with your email marketing, updated just now.
                </p>
                <div class="dashboard-welcome-meta">
                    <span v-if="latestCampaign">
                        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect x="2" y="2" width="9" height="9" rx="2" fill="#EA4335"/><rect x="13" y="2" width="9" height="9" rx="2" fill="#4285F4"/><rect x="2" y="13" width="9" height="9" rx="2" fill="#FBBC05"/><rect x="13" y="13" width="9" height="9" rx="2" fill="#34A853"/></svg>
                        {{ latestCampaign.title }} - {{ latestCampaign.openRate }}% open rate · {{ timeAgo(latestCampaign.sentAt) }}
                    </span>
                    <span v-else>
                        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect x="2" y="2" width="9" height="9" rx="2" fill="#EA4335"/><rect x="13" y="2" width="9" height="9" rx="2" fill="#4285F4"/><rect x="2" y="13" width="9" height="9" rx="2" fill="#FBBC05"/><rect x="13" y="13" width="9" height="9" rx="2" fill="#34A853"/></svg>
                        No campaigns sent yet
                    </span>
                    <span>
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><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.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"/></svg>
                        {{ formatNumber(stats.total_contacts) }} contacts across all lists
                    </span>
                </div>
            </div>
            <div class="dashboard-welcome-illustration">
                <svg viewBox="0 0 120 100" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect x="10" y="20" width="100" height="70" rx="8" fill="var(--bg-hover-strong)" stroke="var(--border-color)" stroke-width="2"/>
                    <rect x="20" y="35" width="80" height="6" rx="3" fill="var(--border-color)"/>
                    <rect x="20" y="48" width="60" height="4" rx="2" fill="var(--text-muted)"/>
                    <rect x="20" y="58" width="70" height="4" rx="2" fill="var(--text-muted)"/>
                    <rect x="20" y="68" width="50" height="4" rx="2" fill="var(--text-muted)"/>
                    <rect x="35" y="80" width="50" height="5" rx="2.5" fill="#4285F4"/>
                    <circle cx="60" cy="15" r="8" fill="#4285F4"/>
                    <path d="M55 15l3 3 7-7" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
        </div>

        <!-- High-level Stat cards -->
        <div class="dashboard-stats">
            <a href="/contacts" class="card stat-card">
                <div class="stat-value">{{ formatNumber(stats.active_contacts) }}</div>
                <div class="stat-label">Active Contacts</div>
            </a>
            <a href="/campaigns" class="card stat-card">
                <div class="stat-value">{{ formatNumber(stats.campaigns) }}</div>
                <div class="stat-label">Campaigns</div>
            </a>
            <div class="card stat-card">
                <div class="stat-value">{{ formatNumber(stats.emails_sent) }}</div>
                <div class="stat-label">Emails Sent</div>
            </div>
            <a href="/tags" class="card stat-card">
                <div class="stat-value">{{ formatNumber(stats.tags) }}</div>
                <div class="stat-label">Tags</div>
            </a>
            <div class="card stat-card">
                <div class="stat-value" style="color:var(--info, #4285F4)">{{ formatNumber(stats.email_templates) }}</div>
                <div class="stat-label">Email Templates</div>
            </div>
            <a href="/automation" class="card stat-card">
                <div class="stat-value">{{ formatNumber(stats.active_automations) }}</div>
                <div class="stat-label">Active Automations</div>
            </a>
        </div>

        <!-- Operations Analysis & Toggle Controls Section -->
        <div class="card operations-section">
            <div class="operations-header">
                <div>
                    <h3 class="operations-title">
                        <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="ops-header-icon">
                            <path d="M22 12h-4l-3 9L9 3l-3 9H2"/>
                        </svg>
                        Operations Analysis & Monitoring
                    </h3>
                    <p class="operations-subtitle">
                        Analyze campaign executions, automations, and background dispatch processes.
                    </p>
                </div>

                <!-- Toggle Controls Toolbar -->
                <div class="operations-toolbar">
                    <!-- Consolidated Toggle: All Operations vs Running Own Operations -->
                    <div class="toggle-group" title="Toggle between All Operations and Running Own Operations">
                        <button
                            type="button"
                            class="toggle-btn"
                            :class="{ active: opScope === 'all' }"
                            @click="setOpScope('all')"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="btn-icon">
                                <polygon points="12 2 2 7 12 12 22 7 12 2"></polygon>
                                <polyline points="2 17 12 22 22 17"></polyline>
                                <polyline points="2 12 12 17 22 12"></polyline>
                            </svg>
                            <span>All Operations</span>
                        </button>
                        <button
                            type="button"
                            class="toggle-btn"
                            :class="{ active: opScope === 'my' }"
                            @click="setOpScope('my')"
                        >
                            <span class="pulse-indicator" :class="{ 'is-running': opKpis.running_operations > 0 }"></span>
                            <span>Running Own Operations</span>
                            <span class="badge-count" v-if="opKpis.running_operations > 0">{{ opKpis.running_operations }}</span>
                        </button>
                    </div>

                    <!-- Manual Refresh Button -->
                    <button
                        type="button"
                        class="btn-refresh"
                        @click="fetchOperations"
                        :disabled="loadingOps"
                        title="Refresh operations analysis"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" :class="{ spinning: loadingOps }">
                            <path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"></path>
                            <path d="M21 3v5h-5"></path>
                        </svg>
                    </button>
                </div>
            </div>

            <!-- Operations KPI Overview Cards -->
            <div class="ops-kpi-grid">
                <div class="ops-kpi-card">
                    <div class="ops-kpi-header">
                        <span class="ops-kpi-title">Total Operations</span>
                    </div>
                    <div class="ops-kpi-value">{{ formatNumber(opKpis.total_operations) }}</div>
                    <div class="ops-kpi-sub">
                        <span class="text-success">{{ opKpis.sent_operations }} sent</span> · 
                        <span class="text-warning">{{ opKpis.draft_operations }} draft</span>
                    </div>
                </div>

                <div class="ops-kpi-card highlight-card">
                    <div class="ops-kpi-header">
                        <span class="ops-kpi-title">Running / Active</span>
                        <span class="live-dot-wrap">
                            <span class="live-pulse"></span>
                            Live
                        </span>
                    </div>
                    <div class="ops-kpi-value text-blue">{{ formatNumber(opKpis.running_operations) }}</div>
                    <div class="ops-kpi-sub">
                        Active sending & queued background jobs
                    </div>
                </div>

                <div class="ops-kpi-card">
                    <div class="ops-kpi-header">
                        <span class="ops-kpi-title">Delivery Rate</span>
                        <span class="ops-kpi-badge info">{{ formatNumber(opKpis.total_sent) }} Emails</span>
                    </div>
                    <div class="ops-kpi-value text-success">{{ opKpis.delivery_rate }}%</div>
                    <div class="ops-kpi-sub">
                        {{ formatNumber(opKpis.total_bounced) }} bounced or failed
                    </div>
                </div>

                <div class="ops-kpi-card">
                    <div class="ops-kpi-header">
                        <span class="ops-kpi-title">Avg Engagement</span>
                        <span class="ops-kpi-badge accent">Opens & Clicks</span>
                    </div>
                    <div class="ops-kpi-value text-purple">{{ opKpis.open_rate }}%</div>
                    <div class="ops-kpi-sub">
                        Click Rate: <strong>{{ opKpis.click_rate }}%</strong>
                    </div>
                </div>
            </div>

            <!-- Operations Charts Row -->
            <div class="ops-charts-grid">
                <!-- Status Breakdown Chart -->
                <div class="ops-chart-card">
                    <div class="ops-chart-header">
                        <h4 class="ops-chart-title">Status Distribution</h4>
                        <span class="ops-chart-sub">Breakdown by current execution state</span>
                    </div>
                    <div class="ops-chart-body">
                        <canvas ref="statusCanvas" height="180"></canvas>
                    </div>
                </div>

                <!-- Performance Breakdown Chart -->
                <div class="ops-chart-card">
                    <div class="ops-chart-header">
                        <h4 class="ops-chart-title">Operations Delivery Metrics</h4>
                        <span class="ops-chart-sub">Volume of Sent, Opens, Clicks & Bounces</span>
                    </div>
                    <div class="ops-chart-body">
                        <canvas ref="perfCanvas" height="180"></canvas>
                    </div>
                </div>
            </div>

            <!-- Live Operations Monitoring Table -->
            <div class="ops-table-wrap">
                <div class="ops-table-header">
                    <h4 class="ops-table-title">Recent & Active Operations</h4>
                    <span class="ops-table-count">Showing {{ operationsList.length }} operations</span>
                </div>

                <div v-if="loadingOps" class="ops-loading-state">
                    <div class="spinner"></div>
                    <span>Updating operation analysis data...</span>
                </div>

                <div v-else-if="operationsList.length === 0" class="ops-empty-state">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
                    </svg>
                    <p>No operations found for the selected scope or filters.</p>
                </div>

                <div v-else class="table-responsive">
                    <table class="ops-table">
                        <thead>
                            <tr>
                                <th>Operation</th>
                                <th>Type</th>
                                <th>Owner</th>
                                <th>Status</th>
                                <th>Progress / Delivery</th>
                                <th>Open Rate</th>
                                <th>Last Activity</th>
                                <th class="text-right">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="op in operationsList" :key="op.id">
                                <td>
                                    <div class="op-title-cell">
                                        <a :href="op.view_url" class="op-name" @click.prevent="navigateTo(op.view_url, op.id)">{{ op.title }}</a>
                                        <span v-if="op.email_subject" class="op-subject">{{ op.email_subject }}</span>
                                    </div>
                                </td>
                                <td>
                                    <span class="op-type-badge" :class="op.type">
                                        {{ formatType(op.type) }}
                                    </span>
                                </td>
                                <td>
                                    <span class="op-owner-badge" :class="{ 'is-me': op.is_owner }">
                                        {{ op.is_owner ? 'You' : op.creator_name }}
                                    </span>
                                </td>
                                <td>
                                    <span class="op-status-badge" :class="op.status">
                                        <span class="status-dot" :class="{ pulse: ['sending', 'processing', 'active'].includes(op.status) }"></span>
                                        {{ formatStatus(op.status) }}
                                    </span>
                                </td>
                                <td>
                                    <div class="op-progress-cell">
                                        <div class="op-progress-text">
                                            <span>{{ formatNumber(op.emails_sent) }} / {{ formatNumber(op.recipients_count) }}</span>
                                            <span class="op-pct">{{ getProgressPct(op) }}%</span>
                                        </div>
                                        <div class="op-progress-bar">
                                            <div class="op-progress-fill" :style="{ width: getProgressPct(op) + '%' }"></div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="op-stat-val">
                                        {{ op.emails_sent > 0 ? ((op.unique_opens / op.emails_sent) * 100).toFixed(1) + '%' : '0%' }}
                                    </span>
                                </td>
                                <td>
                                    <span class="op-date">{{ timeAgo(op.updated_at) }}</span>
                                </td>
                                <td class="text-right">
                                    <button
                                        class="btn btn-outline btn-xs btn-view-action"
                                        :class="{ 'is-loading': navigatingId === op.id }"
                                        :disabled="navigatingId === op.id"
                                        @click.prevent="navigateTo(op.view_url, op.id)"
                                    >
                                        <span v-if="navigatingId === op.id" class="brand-spinner"></span>
                                        <span v-else>View</span>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Subscribers Growth chart section -->
        <div class="card">
            <div class="chart-toolbar">
                <span class="chart-title">Subscribers Growth</span>
                <div class="chart-toolbar-actions">
                    <CwSelect
                        v-slot:default
                        v-model="dateRange"
                        :options="dateRangeOptions"
                        @change="handleRangeChange"
                        placeholder="Select range"
                        style="width: 150px;"
                    />
                    <template v-if="dateRange === 'custom'">
                        <div class="chart-date-input">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><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.5"/></svg>
                            <input type="date" v-model="chartFrom" placeholder="Start date">
                        </div>
                        <span class="chart-date-sep">To</span>
                        <div class="chart-date-input">
                            <input type="date" v-model="chartTo" placeholder="End date">
                        </div>
                        <button class="btn btn-primary btn-sm" @click="loadGrowth" :disabled="loadingGrowth">Apply</button>
                    </template>
                </div>
            </div>
            <div class="chart-legend">
                <div class="chart-legend-item">
                    <div class="chart-legend-bar"></div>
                    By Date
                </div>
                <div class="chart-legend-item">
                    <div class="chart-legend-line"></div>
                    Cumulative
                </div>
            </div>
            <div class="chart-canvas-wrap">
                <canvas ref="growthCanvas" id="growthChart" height="90"></canvas>
            </div>
        </div>
    </AppLayout>
</template>

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

const props = defineProps({
    stats: { type: Object, required: true },
    latestCampaign: { type: Object, default: null },
    initialOperations: { type: Object, default: () => ({}) },
});

const page = usePage();
const user = computed(() => page.props.auth?.user ?? { name: 'User' });
const { theme } = useTheme();

const isDarkMode = computed(() => theme.value === 'dark');

const navigatingId = ref(null);

function navigateTo(url, id) {
    if (!url) return;
    navigatingId.value = id;
    router.visit(url, {
        onFinish: () => {
            navigatingId.value = null;
        },
    });
}

const formatNumber = (n) => new Intl.NumberFormat('en-US').format(n ?? 0);

const timeAgo = (isoDate) => {
    if (!isoDate) return '';
    const days = Math.floor((Date.now() - new Date(isoDate).getTime()) / 86400000);
    if (days <= 0) return 'today';
    if (days === 1) return '1 day ago';
    return `${days} days ago`;
};

// ----------------------------------------------------
// Operations Analysis & Toggle Controls Logic
// ----------------------------------------------------
const opScope = ref(props.initialOperations?.scope || 'all');
const opRunningOnly = ref(props.initialOperations?.running_only || false);
const loadingOps = ref(false);

const opKpis = ref(props.initialOperations?.kpis || {
    total_operations: 0,
    running_operations: 0,
    sent_operations: 0,
    draft_operations: 0,
    paused_operations: 0,
    total_sent: 0,
    total_bounced: 0,
    delivery_rate: 100,
    open_rate: 0,
    click_rate: 0,
});

const statusBreakdown = ref(props.initialOperations?.status_breakdown || {});
const operationsList = ref(props.initialOperations?.operations_list || []);

const statusCanvas = ref(null);
const perfCanvas = ref(null);
let statusChartInstance = null;
let perfChartInstance = null;

function setOpScope(scope) {
    if (scope === 'my') {
        opScope.value = 'my';
        opRunningOnly.value = true;
    } else {
        opScope.value = 'all';
        opRunningOnly.value = false;
    }
    fetchOperations();
}

function toggleRunningOnly() {
    opRunningOnly.value = !opRunningOnly.value;
    fetchOperations();
}

async function fetchOperations() {
    loadingOps.value = true;
    try {
        const { data } = await window.axios.get(route('dashboard.operations'), {
            params: {
                scope: opScope.value,
                running_only: opRunningOnly.value ? 1 : 0,
            },
        });

        opKpis.value = data.kpis;
        statusBreakdown.value = data.status_breakdown;
        operationsList.value = data.operations_list;

        renderOperationsCharts(data);
    } catch (e) {
        console.error('Failed to fetch operations analytics:', e);
    } finally {
        loadingOps.value = false;
    }
}

function formatType(type) {
    const map = {
        campaign: 'Campaign',
        automation: 'Automation',
        recurring_master: 'Recurring',
        recurring_occurrence: 'Occurrence',
        sequence: 'Sequence',
    };
    return map[type] || type;
}

function formatStatus(status) {
    const map = {
        sent: 'Sent',
        completed: 'Completed',
        sending: 'Sending...',
        processing: 'Processing...',
        scheduled: 'Scheduled',
        active: 'Active',
        draft: 'Draft',
        paused: 'Paused',
        failed: 'Failed',
    };
    return map[status] || status;
}

function getProgressPct(op) {
    if (!op.recipients_count || op.recipients_count <= 0) {
        return op.emails_sent > 0 ? 100 : 0;
    }
    return Math.min(100, Math.round((op.emails_sent / op.recipients_count) * 100));
}

function renderOperationsCharts(data) {
    const isDark = isDarkMode.value;
    const gridColor = isDark ? '#2b3648' : '#f1f5f9';
    const textColor = isDark ? '#b6c0cf' : '#64748b';
    const borderColor = isDark ? '#1b2330' : '#ffffff';

    nextTick(() => {
        // Render Status Breakdown Doughnut Chart
        if (statusCanvas.value) {
            const sb = data?.status_breakdown || statusBreakdown.value;
            const labels = ['Sent', 'Sending', 'Scheduled', 'Active', 'Draft', 'Paused', 'Failed'];
            const chartValues = [
                sb.sent || 0,
                sb.sending || 0,
                sb.scheduled || 0,
                sb.active || 0,
                sb.draft || 0,
                sb.paused || 0,
                sb.failed || 0,
            ];
            const colors = ['#34A853', '#4285F4', '#FBBC05', '#10B981', '#9CA3AF', '#F59E0B', '#EF4444'];

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

            statusChartInstance = new Chart(statusCanvas.value, {
                type: 'doughnut',
                data: {
                    labels,
                    datasets: [{
                        data: chartValues,
                        backgroundColor: colors,
                        borderWidth: 2,
                        borderColor: borderColor,
                    }],
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'bottom', labels: { boxWidth: 12, padding: 12, color: textColor } },
                    },
                    cutout: '65%',
                },
            });
        }

        // Render Performance Metrics Bar Chart
        if (perfCanvas.value) {
            const kpis = data?.kpis || opKpis.value;
            const perfLabels = ['Emails Sent', 'Unique Opens', 'Unique Clicks', 'Bounced/Failed'];
            const perfValues = [
                kpis.total_sent || 0,
                Math.round((kpis.total_sent * (kpis.open_rate || 0)) / 100),
                Math.round((kpis.total_sent * (kpis.click_rate || 0)) / 100),
                kpis.total_bounced || 0,
            ];

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

            perfChartInstance = new Chart(perfCanvas.value, {
                type: 'bar',
                data: {
                    labels: perfLabels,
                    datasets: [{
                        label: 'Volume',
                        data: perfValues,
                        backgroundColor: [
                            'rgba(66, 133, 244, 0.75)',
                            'rgba(52, 168, 83, 0.75)',
                            'rgba(168, 85, 247, 0.75)',
                            'rgba(239, 68, 68, 0.75)',
                        ],
                        borderRadius: 6,
                    }],
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: {
                        y: { beginAtZero: true, grid: { color: gridColor }, ticks: { color: textColor } },
                        x: { grid: { display: false }, ticks: { color: textColor } },
                    },
                },
            });
        }
    });
}

// ----------------------------------------------------
// Growth Chart Logic
// ----------------------------------------------------
const today = new Date();
const defaultFrom = new Date(today.getTime() - 29 * 86400000).toISOString().slice(0, 10);
const defaultTo = today.toISOString().slice(0, 10);

const chartFrom = ref(defaultFrom);
const chartTo = ref(defaultTo);
const loadingGrowth = ref(false);
const growthCanvas = ref(null);
let growthChartInstance = null;
let lastGrowthData = null;

const dateRange = ref('30d');
const dateRangeOptions = [
    { label: 'Last 30 days',   value: '30d' },
    { label: 'Last 90 days',   value: '90d' },
    { label: 'Last 12 months', value: '12m' },
    { label: 'Custom range',   value: 'custom' },
];

function handleRangeChange(val) {
    if (val === 'custom') return;
    const now = new Date();
    let days = 29;
    if (val === '90d') days = 89;
    if (val === '12m') days = 364;

    chartFrom.value = new Date(now.getTime() - days * 86400000).toISOString().slice(0, 10);
    chartTo.value = now.toISOString().slice(0, 10);
    loadGrowth();
}

async function loadGrowth() {
    loadingGrowth.value = true;
    try {
        const { data } = await window.axios.get(route('dashboard.growth'), {
            params: { from: chartFrom.value, to: chartTo.value },
        });
        lastGrowthData = data;
        renderGrowthChart(data);
    } finally {
        loadingGrowth.value = false;
    }
}

function renderGrowthChart(data) {
    if (!data) data = lastGrowthData;
    if (!data || !growthCanvas.value) return;
    const { labels, newAdds, cumulative } = data;

    const isDark = isDarkMode.value;
    const gridColor = isDark ? '#2b3648' : '#f1f5f9';
    const textColor = isDark ? '#b6c0cf' : '#64748b';

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

    growthChartInstance = new Chart(growthCanvas.value, {
        type: 'bar',
        data: {
            labels,
            datasets: [
                {
                    type: 'bar',
                    label: 'By Date',
                    data: newAdds,
                    backgroundColor: 'rgba(66,133,244,0.45)',
                    borderRadius: 4,
                    yAxisID: 'y',
                },
                {
                    type: 'line',
                    label: 'Cumulative',
                    data: cumulative,
                    borderColor: '#34A853',
                    backgroundColor: 'rgba(52,168,83,0.12)',
                    borderWidth: 2,
                    tension: 0.35,
                    pointRadius: 0,
                    fill: false,
                    yAxisID: 'y1',
                },
            ],
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: { mode: 'index', intersect: false },
            plugins: { legend: { display: false } },
            scales: {
                y:  { beginAtZero: true, position: 'left',  grid: { color: gridColor }, ticks: { color: textColor } },
                y1: { beginAtZero: true, position: 'right', grid: { drawOnChartArea: false }, ticks: { color: textColor } },
                x:  { ticks: { color: textColor }, grid: { display: false } },
            },
        },
    });
}

// Watch theme changes to re-render charts dynamically
watch(theme, () => {
    renderOperationsCharts();
    renderGrowthChart();
});

onMounted(() => {
    loadGrowth();
    renderOperationsCharts(props.initialOperations);
});

onBeforeUnmount(() => {
    growthChartInstance?.destroy();
    statusChartInstance?.destroy();
    perfChartInstance?.destroy();
});
</script>

<style scoped>
/* Operations Analysis Section Styles - Theme & Responsive Sync */
.operations-section {
    margin-top: 1.5rem;
    margin-bottom: 1.5rem;
    padding: 1.5rem;
    background: var(--bg-surface, #ffffff);
    border: 1px solid var(--border-color, #e2e8f0);
    border-radius: var(--radius-lg, 12px);
    transition: background-color 0.2s ease, border-color 0.2s ease;
}

.operations-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    flex-wrap: wrap;
    gap: 1rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid var(--border-color, #e2e8f0);
}

.operations-title {
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--text-primary, #1e293b);
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin: 0;
}

.ops-header-icon {
    width: 24px;
    height: 24px;
    color: var(--info, #4285F4);
    flex-shrink: 0;
}

.operations-subtitle {
    font-size: 0.875rem;
    color: var(--text-secondary, #64748b);
    margin: 0.25rem 0 0 0;
}

/* Toolbar & Toggles */
.operations-toolbar {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    flex-wrap: wrap;
}

.toggle-group {
    display: inline-flex;
    background: var(--bg-hover-strong, #f1f5f9);
    border-radius: var(--radius-md, 8px);
    padding: 3px;
    border: 1px solid var(--border-color, #e2e8f0);
}

.toggle-btn {
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    padding: 0.45rem 0.85rem;
    font-size: 0.8125rem;
    font-weight: 600;
    color: var(--text-secondary, #64748b);
    background: transparent;
    border: none;
    border-radius: var(--radius, 6px);
    cursor: pointer;
    transition: all 0.15s ease-in-out;
    white-space: nowrap;
}

.toggle-btn:hover {
    color: var(--text-primary, #1e293b);
}

.toggle-btn.active {
    background: var(--bg-surface, #ffffff);
    color: var(--active-text, #4285F4);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
}

.btn-icon {
    width: 16px;
    height: 16px;
    flex-shrink: 0;
}

.pulse-indicator {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: var(--text-muted, #94a3b8);
    display: inline-block;
}

.pulse-indicator.is-running {
    background-color: #10b981;
    box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
    animation: pulse-ring 1.5s infinite;
}

@keyframes pulse-ring {
    0% {
        box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
    }
    70% {
        box-shadow: 0 0 0 6px rgba(16, 185, 129, 0);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
    }
}

.badge-count {
    background: var(--info, #2563eb);
    color: #ffffff;
    font-size: 0.7rem;
    padding: 1px 6px;
    border-radius: 10px;
}

.btn-refresh {
    background: var(--bg-surface, #ffffff);
    border: 1px solid var(--border-color, #e2e8f0);
    padding: 0.45rem;
    border-radius: var(--radius-md, 8px);
    cursor: pointer;
    color: var(--text-secondary, #64748b);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    transition: color 0.15s ease, background-color 0.15s ease;
}

.btn-refresh:hover {
    color: var(--text-primary, #1e293b);
    background: var(--bg-hover, #f8fafc);
}

.btn-refresh svg {
    width: 18px;
    height: 18px;
}

.spinning {
    animation: spin 1s linear infinite;
}

@keyframes spin {
    100% { transform: rotate(360deg); }
}

/* KPI Cards Grid */
.ops-kpi-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
    gap: 1rem;
    margin-top: 1.25rem;
}

.ops-kpi-card {
    background: var(--bg-hover, #f8fafc);
    border: 1px solid var(--border-color, #e2e8f0);
    border-radius: var(--radius-md, 10px);
    padding: 1rem;
}

.ops-kpi-card.highlight-card {
    background: var(--active-bg, rgba(66, 133, 244, 0.1));
    border-color: var(--info-border, #bfdbfe);
}

.ops-kpi-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 0.785rem;
    color: var(--text-secondary, #64748b);
    font-weight: 600;
}

.ops-kpi-value {
    font-size: 1.65rem;
    font-weight: 800;
    color: var(--text-primary, #1e293b);
    margin: 0.35rem 0;
}

.ops-kpi-sub {
    font-size: 0.75rem;
    color: var(--text-secondary, #64748b);
}

.ops-kpi-badge {
    font-size: 0.7rem;
    padding: 2px 6px;
    border-radius: 4px;
    font-weight: 600;
}

.ops-kpi-badge.scope-tag { background: var(--bg-hover-strong, #e2e8f0); color: var(--text-secondary, #475569); }
.ops-kpi-badge.private-tag { background: var(--success-light, #dcfce7); color: var(--success, #15803d); }
.ops-kpi-badge.info { background: var(--info-light, #dbeafe); color: var(--info, #1e40af); }
.ops-kpi-badge.accent { background: rgba(147, 51, 234, 0.15); color: #9333ea; }

.live-dot-wrap {
    display: flex;
    align-items: center;
    gap: 4px;
    color: var(--success, #059669);
    font-weight: 700;
    font-size: 0.725rem;
}

.live-pulse {
    width: 6px;
    height: 6px;
    background: #10b981;
    border-radius: 50%;
    animation: pulse-ring 1.5s infinite;
}

.text-blue { color: var(--info, #2563eb) !important; }
.text-success { color: var(--success, #16a34a) !important; }
.text-warning { color: var(--warning, #d97706) !important; }
.text-purple { color: #9333ea !important; }

/* Operations Charts */
.ops-charts-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1.25rem;
    margin-top: 1.5rem;
}

.ops-chart-card {
    border: 1px solid var(--border-color, #e2e8f0);
    border-radius: var(--radius-md, 10px);
    padding: 1rem;
    background: var(--bg-surface, #ffffff);
}

.ops-chart-title {
    font-size: 0.95rem;
    font-weight: 700;
    color: var(--text-primary, #1e293b);
    margin: 0;
}

.ops-chart-sub {
    font-size: 0.75rem;
    color: var(--text-muted, #64748b);
}

.ops-chart-body {
    height: 180px;
    margin-top: 0.75rem;
    position: relative;
}

/* Responsive Table Wrapper */
.ops-table-wrap {
    margin-top: 1.5rem;
    border: 1px solid var(--border-color, #e2e8f0);
    border-radius: var(--radius-md, 10px);
    overflow: hidden;
    background: var(--bg-surface, #ffffff);
}

.ops-table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.85rem 1.25rem;
    background: var(--bg-hover, #f8fafc);
    border-bottom: 1px solid var(--border-color, #e2e8f0);
}

.ops-table-title {
    font-size: 0.95rem;
    font-weight: 700;
    margin: 0;
    color: var(--text-primary, #1e293b);
}

.ops-table-count {
    font-size: 0.75rem;
    color: var(--text-muted, #64748b);
}

.table-responsive {
    width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.ops-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.8125rem;
}

.ops-table th {
    background: var(--bg-hover-strong, #f1f5f9);
    color: var(--text-secondary, #475569);
    font-weight: 600;
    text-align: left;
    padding: 0.65rem 1rem;
    border-bottom: 1px solid var(--border-color, #e2e8f0);
    white-space: nowrap;
}

.ops-table td {
    padding: 0.75rem 1rem;
    border-bottom: 1px solid var(--border-color, #e2e8f0);
    vertical-align: middle;
    color: var(--text-primary, #1e293b);
}

.ops-table tr:hover {
    background: var(--bg-hover, #f8fafc);
}

.op-title-cell {
    display: flex;
    flex-direction: column;
    min-width: 160px;
}

.op-name {
    font-weight: 600;
    color: var(--text-primary, #1e293b);
    text-decoration: none;
}

.op-name:hover {
    color: var(--active-text, #2563eb);
}

.op-subject {
    font-size: 0.75rem;
    color: var(--text-muted, #64748b);
}

.op-type-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.7rem;
    font-weight: 600;
    background: var(--bg-hover-strong, #e2e8f0);
    color: var(--text-secondary, #475569);
    white-space: nowrap;
}

.op-type-badge.campaign { background: var(--info-light, #dbeafe); color: var(--info, #1d4ed8); }
.op-type-badge.automation { background: var(--warning-light, #fef3c7); color: var(--warning, #b45309); }
.op-type-badge.sequence { background: rgba(147, 51, 234, 0.15); color: #9333ea; }
.op-type-badge.recurring_master { background: var(--success-light, #dcfce7); color: var(--success, #15803d); }

.op-owner-badge {
    font-size: 0.725rem;
    padding: 2px 6px;
    border-radius: 4px;
    background: var(--bg-hover-strong, #f1f5f9);
    color: var(--text-secondary, #64748b);
    white-space: nowrap;
}

.op-owner-badge.is-me {
    background: var(--active-bg, #e0e7ff);
    color: var(--active-text, #4338ca);
    font-weight: 700;
}

.op-status-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: 0.725rem;
    font-weight: 600;
    padding: 2px 8px;
    border-radius: 12px;
    white-space: nowrap;
}

.op-status-badge.sent, .op-status-badge.completed { background: var(--success-light, #dcfce7); color: var(--success, #166534); }
.op-status-badge.sending, .op-status-badge.processing { background: var(--info-light, #dbeafe); color: var(--info, #1e40af); }
.op-status-badge.scheduled { background: var(--warning-light, #fef3c7); color: var(--warning, #92400e); }
.op-status-badge.active { background: var(--success-light, #ecfdf5); color: var(--success, #047857); }
.op-status-badge.draft { background: var(--bg-hover-strong, #f1f5f9); color: var(--text-muted, #64748b); }
.op-status-badge.paused { background: var(--warning-light, #ffedd5); color: var(--warning, #c2410c); }
.op-status-badge.failed { background: var(--danger-light, #fee2e2); color: var(--danger, #991b1b); }

.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: currentColor;
}

.status-dot.pulse {
    animation: pulse-ring 1.5s infinite;
}

.op-progress-cell {
    width: 140px;
    min-width: 120px;
}

.op-progress-text {
    display: flex;
    justify-content: space-between;
    font-size: 0.7rem;
    color: var(--text-muted, #64748b);
    margin-bottom: 2px;
}

.op-pct { font-weight: 700; color: var(--text-primary, #1e293b); }

.op-progress-bar {
    height: 5px;
    background: var(--border-color, #e2e8f0);
    border-radius: 3px;
    overflow: hidden;
}

.op-progress-fill {
    height: 100%;
    background: var(--info, #3b82f6);
    border-radius: 3px;
}

.op-stat-val {
    font-weight: 600;
    color: var(--text-primary, #1e293b);
}

.op-date {
    font-size: 0.75rem;
    color: var(--text-muted, #64748b);
    white-space: nowrap;
}

.text-right { text-align: right; }

.btn-xs {
    padding: 0.25rem 0.6rem;
    font-size: 0.725rem;
    border-radius: var(--radius-sm, 4px);
    border: 1px solid var(--border-color, #e2e8f0);
    color: var(--text-primary, #1e293b);
    background: var(--bg-surface, #ffffff);

    &:hover {
        background: var(--bg-hover-strong, #f1f5f9);
    }
}

.ops-loading-state, .ops-empty-state {
    padding: 2.5rem;
    text-align: center;
    color: var(--text-muted, #64748b);
}

.ops-empty-state svg {
    width: 36px;
    height: 36px;
    color: var(--text-muted, #94a3b8);
    margin-bottom: 0.5rem;
}

/* ───────────────────────────────────────────── */
/* Responsive Media Queries (Mobile & Tablet)   */
/* ───────────────────────────────────────────── */
@media (max-width: 768px) {
    .operations-header {
        flex-direction: column;
        align-items: stretch;
        gap: 0.75rem;
    }

    .operations-toolbar {
        width: 100%;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        gap: 8px;
    }

    .toggle-group {
        flex: 1;
        display: flex;
        width: auto;
    }

    .toggle-btn {
        flex: 1;
        justify-content: center;
        padding: 0.5rem 0.5rem;
        font-size: 0.8rem;
        white-space: nowrap;
    }

    .btn-refresh {
        flex-shrink: 0;
        width: 38px;
        height: 38px;
        padding: 0;
    }

    .ops-charts-grid {
        grid-template-columns: 1fr;
    }

    .ops-kpi-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 480px) {
    .operations-section {
        padding: 1rem;
    }

    .toggle-btn {
        padding: 0.45rem 0.3rem;
        font-size: 0.75rem;
        gap: 0.25rem;
        white-space: nowrap;
    }

    .btn-icon {
        width: 14px;
        height: 14px;
        flex-shrink: 0;
    }

    .ops-kpi-grid {
        grid-template-columns: 1fr;
    }
}
</style>
