// Componente de Gráfico de Flujo de Caja
// Arquitectura modular - Componente avanzado con métricas profesionales

function CashFlowChart() {
  const { useEffect, useRef, useState } = React;
  const chartRef = useRef(null);
  const chartInstance = useRef(null);
  const [selectedPeriod, setSelectedPeriod] = useState('6m');

  // Usar datos y utilidades globales
  const cashFlowData = window.mockData?.cashFlowData || {};
  const helpers = window.analyticsHelpers || {};
  const { formatCurrency, calculateGrowth, getGrowthStatus, getBaseChartConfig } = helpers;

  useEffect(() => {
    if (chartRef.current && cashFlowData.datasets) {
      const ctx = chartRef.current;
      
      // Destruir gráfico anterior si existe
      if (chartInstance.current) {
        chartInstance.current.destroy();
      }

      // Configuración avanzada del gráfico
      const config = {
        type: 'line',
        data: cashFlowData,
        options: {
          ...(getBaseChartConfig ? getBaseChartConfig() : {}),
          interaction: {
            mode: 'index',
            intersect: false,
          },
          plugins: {
            legend: {
              labels: { 
                color: '#fff', 
                font: { size: 14, weight: "600" },
                usePointStyle: true,
                pointStyle: 'circle',
                padding: 20
              },
              position: 'top'
            },
            tooltip: {
              backgroundColor: "rgba(17, 17, 17, 0.95)",
              titleColor: '#fff',
              bodyColor: '#fff',
              borderColor: '#3A6BDA',
              borderWidth: 2,
              cornerRadius: 8,
              callbacks: {
                label: function(context) {
                  const value = formatCurrency ? formatCurrency(context.parsed.y) : `$${context.parsed.y}`;
                  return context.dataset.label + ': ' + value;
                },
                afterBody: function(tooltipItems) {
                  if (tooltipItems.length >= 3) {
                    const ingresos = tooltipItems.find(item => item.dataset.label === 'Ingresos')?.parsed.y || 0;
                    const gastos = tooltipItems.find(item => item.dataset.label === 'Gastos')?.parsed.y || 0;
                    const margen = ingresos > 0 ? ((ingresos - gastos) / ingresos * 100).toFixed(1) : '0.0';
                    return [`Margen: ${margen}%`];
                  }
                  return [];
                }
              }
            }
          },
          scales: {
            x: {
              ticks: { 
                color: '#fff', 
                font: { size: 13, weight: "500" } 
              },
              grid: { 
                color: "rgba(255, 255, 255, 0.1)",
                drawOnChartArea: true,
                drawTicks: false
              }
            },
            y: {
              ticks: { 
                color: '#fff', 
                font: { size: 13, weight: "500" },
                callback: function(value) {
                  return formatCurrency ? formatCurrency(value) : `$${value}`;
                }
              },
              grid: { 
                color: "rgba(255, 255, 255, 0.1)",
                drawOnChartArea: true,
                drawTicks: false
              },
              beginAtZero: false
            }
          },
          elements: {
            line: {
              tension: 0.4
            },
            point: {
              radius: 6,
              hoverRadius: 10
            }
          },
          animation: {
            duration: 1200,
            easing: "easeInOutQuart"
          },
          responsive: true,
          maintainAspectRatio: false
        }
      };

      chartInstance.current = new Chart(ctx, config);
    }

    return () => {
      if (chartInstance.current) {
        chartInstance.current.destroy();
      }
    };
  }, [cashFlowData, selectedPeriod]);

  // Cálculos de métricas (con verificaciones de seguridad)
  const flujoNetoData = cashFlowData.datasets?.[2]?.data || [];
  const ingresosData = cashFlowData.datasets?.[0]?.data || [];
  const gastosData = cashFlowData.datasets?.[1]?.data || [];

  const currentMonth = flujoNetoData[flujoNetoData.length - 1] || 0;
  const previousMonth = flujoNetoData[flujoNetoData.length - 2] || 0;
  const growth = calculateGrowth ? calculateGrowth(currentMonth, previousMonth) : 0;
  const growthStatus = getGrowthStatus ? getGrowthStatus(growth) : { color: '#3A6BDA' };

  const totalIngresos = ingresosData.reduce((sum, val) => sum + (val || 0), 0);
  const totalGastos = gastosData.reduce((sum, val) => sum + (val || 0), 0);
  const margenPromedio = totalIngresos > 0 ? ((totalIngresos - totalGastos) / totalIngresos * 100) : 0;

  const isPositiveGrowth = growth > 0;

  const periodOptions = [
    { value: '3m', label: '3 Meses' },
    { value: '6m', label: '6 Meses' },
    { value: '12m', label: '12 Meses' }
  ];

  return React.createElement('div', { className: 'cash-flow-container' },
    // Header mejorado con controles
    React.createElement('div', { className: 'cash-flow-header' },
      React.createElement('div', { className: 'cash-flow-title-section' },
        React.createElement('h3', { className: 'cash-flow-title' }, 'Flujo de Caja'),
        React.createElement('div', { className: 'cash-flow-growth' },
          React.createElement('span', { 
            className: `growth-indicator ${isPositiveGrowth ? 'positive' : 'negative'}`,
            style: { borderColor: growthStatus.color }
          },
            React.createElement('i', { 
              className: `fas fa-arrow-${isPositiveGrowth ? 'up' : 'down'}` 
            }),
            React.createElement('span', null, Math.abs(growth).toFixed(1) + '%')
          ),
          React.createElement('span', { className: 'growth-label' }, 'vs mes anterior')
        )
      ),
      React.createElement('div', { className: 'cash-flow-controls' },
        React.createElement('div', { className: 'period-selector' },
          periodOptions.map(option =>
            React.createElement('button', {
              key: option.value,
              className: `period-btn ${selectedPeriod === option.value ? 'active' : ''}`,
              onClick: () => setSelectedPeriod(option.value)
            }, option.label)
          )
        )
      )
    ),

    // Panel de métricas clave
    React.createElement('div', { className: 'cash-flow-metrics' },
      React.createElement('div', { className: 'metric-card primary' },
        React.createElement('div', { className: 'metric-icon' },
          React.createElement('i', { className: 'fas fa-chart-line' })
        ),
        React.createElement('div', { className: 'metric-content' },
          React.createElement('span', { className: 'metric-label' }, 'Flujo Neto Actual'),
          React.createElement('span', { className: 'metric-value' }, 
            formatCurrency ? formatCurrency(currentMonth) : `$${currentMonth}`
          )
        )
      ),
      React.createElement('div', { className: 'metric-card success' },
        React.createElement('div', { className: 'metric-icon' },
          React.createElement('i', { className: 'fas fa-percentage' })
        ),
        React.createElement('div', { className: 'metric-content' },
          React.createElement('span', { className: 'metric-label' }, 'Margen Promedio'),
          React.createElement('span', { className: 'metric-value' }, `${margenPromedio.toFixed(1)}%`)
        )
      ),
      React.createElement('div', { className: 'metric-card info' },
        React.createElement('div', { className: 'metric-icon' },
          React.createElement('i', { className: 'fas fa-calendar-alt' })
        ),
        React.createElement('div', { className: 'metric-content' },
          React.createElement('span', { className: 'metric-label' }, 'Período'),
          React.createElement('span', { className: 'metric-value' }, 
            periodOptions.find(p => p.value === selectedPeriod)?.label || '6 Meses'
          )
        )
      )
    ),
    
    // Contenedor del gráfico
    React.createElement('div', { className: 'cash-flow-chart-container' },
      React.createElement('canvas', { 
        ref: chartRef,
        id: 'cashFlowChart'
      })
    ),

    // Panel de insights
    React.createElement('div', { className: 'cash-flow-insights' },
      React.createElement('h4', null, 'Insights Clave'),
      React.createElement('div', { className: 'insights-grid' },
        React.createElement('div', { className: 'insight-item' },
          React.createElement('i', { className: 'fas fa-lightbulb' }),
          React.createElement('span', null, `El flujo neto ${isPositiveGrowth ? 'creció' : 'decreció'} ${Math.abs(growth).toFixed(1)}% este mes`)
        ),
        React.createElement('div', { className: 'insight-item' },
          React.createElement('i', { className: 'fas fa-target' }),
          React.createElement('span', null, `Margen de ganancia del ${margenPromedio.toFixed(1)}%`)
        ),
        React.createElement('div', { className: 'insight-item' },
          React.createElement('i', { className: 'fas fa-trending-up' }),
          React.createElement('span', null, 'Tendencia general positiva en los últimos 6 meses')
        )
      )
    )
  );
}

// Hacer disponible globalmente
if (typeof window !== 'undefined') {
  window.CashFlowChart = CashFlowChart;
}
