// Sidebar component — collapsible, with SVG icons and logout
(function () {
  const { useState, useEffect, useRef } = React;

  const NAV = [
    { id: 'dashboard', label: 'Dashboard' },
    { id: 'products',  label: 'Productos' },
    { id: 'finanzas',  label: 'Contabilidad' },
  ];

  function IconGrid() {
    return React.createElement('svg', { viewBox:'0 0 16 16', width:16, height:16, fill:'currentColor' },
      React.createElement('rect', { x:1,  y:1,  width:6, height:6, rx:1.5 }),
      React.createElement('rect', { x:9,  y:1,  width:6, height:6, rx:1.5 }),
      React.createElement('rect', { x:1,  y:9,  width:6, height:6, rx:1.5 }),
      React.createElement('rect', { x:9,  y:9,  width:6, height:6, rx:1.5 })
    );
  }

  function IconBox() {
    return React.createElement('svg', { viewBox:'0 0 16 16', width:16, height:16, fill:'none',
      stroke:'currentColor', strokeWidth:1.6, strokeLinecap:'round', strokeLinejoin:'round' },
      React.createElement('path', { d:'M8 1.5L14 4.5v7L8 14.5 2 11.5v-7z' }),
      React.createElement('path', { d:'M2 4.5l6 3 6-3' }),
      React.createElement('line', { x1:8, y1:7.5, x2:8, y2:14.5 })
    );
  }

  function IconChart() {
    return React.createElement('svg', { viewBox:'0 0 16 16', width:16, height:16, fill:'currentColor' },
      React.createElement('rect', { x:1,   y:9,  width:3.5, height:5.5, rx:0.8 }),
      React.createElement('rect', { x:6.3, y:5.5, width:3.5, height:9, rx:0.8 }),
      React.createElement('rect', { x:11.5, y:1.5, width:3.5, height:13, rx:0.8 })
    );
  }

  function IconLogout() {
    return React.createElement('svg', { viewBox:'0 0 16 16', width:16, height:16, fill:'none',
      stroke:'currentColor', strokeWidth:1.6, strokeLinecap:'round', strokeLinejoin:'round' },
      React.createElement('path', { d:'M6 14H3a1 1 0 01-1-1V3a1 1 0 011-1h3' }),
      React.createElement('polyline', { points:'10 11 13 8 10 5' }),
      React.createElement('line', { x1:13, y1:8, x2:5, y2:8 })
    );
  }

  const NAV_ICONS = { dashboard: IconGrid, products: IconBox, finanzas: IconChart };

  function CamthonLogo({ collapsed }) {
    return React.createElement('div', { style:{ display:'flex', alignItems:'center', gap:10 } },
      React.createElement('svg', {
        xmlns:'http://www.w3.org/2000/svg', width:32, height:32, viewBox:'0 0 36 36',
        style:{ flexShrink:0 },
      },
        React.createElement('defs', null,
          React.createElement('linearGradient', { id:'camGrad2', x1:'0', y1:'0', x2:'0.4', y2:'1' },
            React.createElement('stop', { offset:'0%',   stopColor:'#9333ea' }),
            React.createElement('stop', { offset:'45%',  stopColor:'#ec4899' }),
            React.createElement('stop', { offset:'100%', stopColor:'#f59e0b' })
          )
        ),
        React.createElement('path', {
          d:'M 27 10.5 A 12 12 0 1 0 27 25.5', fill:'none',
          stroke:'url(#camGrad2)', strokeWidth:7, strokeLinecap:'round',
        })
      ),
      !collapsed && React.createElement('div', null,
        React.createElement('div', { className:'sidebar-logo-name' }, 'camthon'),
        React.createElement('div', { className:'sidebar-logo-sub' }, 'Analytics · EU')
      )
    );
  }

  function Sidebar({ active, onNav }) {
    const [collapsed, setCollapsed] = useState(() => localStorage.getItem('fba_sb_col') === '1');
    const [status, setStatus]       = useState(null);
    const [syncing, setSyncing]     = useState(false);
    const pollRef = useRef(null);

    function toggleCollapse() {
      setCollapsed(c => {
        const next = !c;
        localStorage.setItem('fba_sb_col', next ? '1' : '0');
        return next;
      });
    }

    function loadStatus() {
      API.syncStatus().then(d => setStatus(d)).catch(() => {});
    }

    useEffect(() => {
      loadStatus();
      pollRef.current = setInterval(loadStatus, 30_000);
      return () => clearInterval(pollRef.current);
    }, []);

    async function handleSync() {
      if (syncing) return;
      setSyncing(true);
      try {
        await API.syncIncremental();
        let polls = 0;
        const iv = setInterval(() => {
          loadStatus();
          if (++polls > 60) { clearInterval(iv); setSyncing(false); return; }
          API.syncStatus().then(d => {
            if (d?.current?.status !== 'running') { clearInterval(iv); setSyncing(false); }
          }).catch(() => {});
        }, 3000);
      } catch { setSyncing(false); }
    }

    function handleLogout() {
      localStorage.clear();
      window.location.reload();
    }

    const last      = status?.lastFinancial;
    const running   = syncing || status?.current?.status === 'running';
    const syncOk    = last?.status === 'completed';
    const syncDate  = last?.completed_at
      ? new Date(last.completed_at).toLocaleString('es-ES', { day:'2-digit', month:'short', hour:'2-digit', minute:'2-digit' })
      : null;
    const dotClass  = running ? 'running' : syncOk ? 'ok' : 'idle';
    const labelText = running ? 'Sincronizando...' : syncOk ? 'Sincronizado' : 'Sin sincronizar';

    return React.createElement('aside', { className:`sidebar${collapsed ? ' collapsed' : ''}` },

      // Logo — click to collapse
      React.createElement('div', {
        className:'sidebar-logo',
        onClick: toggleCollapse,
        title: collapsed ? 'Expandir menú' : 'Colapsar menú',
      },
        React.createElement(CamthonLogo, { collapsed })
      ),

      // Nav
      React.createElement('nav', { className:'sidebar-nav' },
        NAV.map(item => {
          const Icon = NAV_ICONS[item.id];
          return React.createElement('button', {
            key:       item.id,
            onClick:   () => onNav(item.id),
            className: `nav-item${active === item.id ? ' active' : ''}`,
            title:     collapsed ? item.label : undefined,
          },
            React.createElement('span', { className:'nav-icon' },
              Icon ? React.createElement(Icon) : null
            ),
            !collapsed && item.label
          );
        })
      ),

      React.createElement('div', { className:'sidebar-spacer' }),

      // Sync box (hidden when collapsed)
      !collapsed && React.createElement('div', { className:'sync-box' },
        React.createElement('div', { className:'sync-row' },
          React.createElement('div', { className:`sync-dot ${dotClass}` }),
          React.createElement('div', null,
            React.createElement('div', { className:`sync-label ${dotClass}` }, labelText),
            syncDate && !running && React.createElement('div', { className:'sync-date' }, syncDate)
          )
        ),
        React.createElement('button', {
          className: 'btn-sync',
          onClick:   handleSync,
          disabled:  running,
        }, running ? 'Sincronizando...' : 'Sincronizar ahora')
      ),

      // Logout button
      React.createElement('button', {
        className: `logout-btn${collapsed ? ' collapsed' : ''}`,
        onClick:   handleLogout,
        title:     collapsed ? 'Cerrar sesión' : undefined,
      },
        React.createElement('span', { className:'nav-icon', style:{ color:'#ef4444' } },
          React.createElement(IconLogout)
        ),
        !collapsed && React.createElement('span', { className:'logout-label' }, 'Cerrar sesión')
      )
    );
  }

  window.Sidebar = Sidebar;
})();
