/* global React */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* =========================================================================
   Ícones — line, 1.5px, neutros (sem decoração)
   ========================================================================= */
const Icon = ({ name, size = 16, className = '', style }) => {
  const props = {
    width: size, height: size, viewBox: '0 0 24 24',
    fill: 'none', stroke: 'currentColor', strokeWidth: 1.5,
    strokeLinecap: 'round', strokeLinejoin: 'round',
    className: 'nav-icon ' + className, style,
  };
  switch (name) {
    case 'pipeline':
      return (<svg {...props}><path d="M4 6h6"/><path d="M4 12h10"/><path d="M4 18h4"/><circle cx="14" cy="6" r="1.5"/><circle cx="18" cy="12" r="1.5"/><circle cx="12" cy="18" r="1.5"/></svg>);
    case 'kanban':
      return (<svg {...props}><rect x="3.5" y="4" width="5" height="16" rx="1"/><rect x="10" y="4" width="5" height="10" rx="1"/><rect x="16.5" y="4" width="4" height="13" rx="1"/></svg>);
    case 'contacts':
      return (<svg {...props}><circle cx="9" cy="9" r="3.5"/><path d="M3.5 19c.8-3 3-4.5 5.5-4.5s4.7 1.5 5.5 4.5"/><path d="M16 11a3 3 0 0 0 0-6"/><path d="M17 19h3.5c-.4-2-1.6-3.3-3.3-4"/></svg>);
    case 'inbox':
      return (<svg {...props}><path d="M4 13l1.5-7a1.5 1.5 0 0 1 1.5-1h10a1.5 1.5 0 0 1 1.5 1L20 13"/><path d="M4 13v5a1.5 1.5 0 0 0 1.5 1.5h13A1.5 1.5 0 0 0 20 18v-5"/><path d="M4 13h4l1 2h6l1-2h4"/></svg>);
    case 'calendar':
      return (<svg {...props}><rect x="3.5" y="5" width="17" height="15" rx="1.5"/><path d="M3.5 9.5h17"/><path d="M8 3.5v3M16 3.5v3"/></svg>);
    case 'reports':
      return (<svg {...props}><path d="M4 19h16"/><path d="M7 19v-7"/><path d="M12 19v-11"/><path d="M17 19v-5"/></svg>);
    case 'settings':
      return (<svg {...props}><circle cx="12" cy="12" r="2.5"/><path d="M12 4v2M12 18v2M4 12h2M18 12h2M6.3 6.3l1.4 1.4M16.3 16.3l1.4 1.4M6.3 17.7l1.4-1.4M16.3 7.7l1.4-1.4"/></svg>);
    case 'search':
      return (<svg {...props}><circle cx="11" cy="11" r="6"/><path d="m20 20-3.5-3.5"/></svg>);
    case 'plus':
      return (<svg {...props}><path d="M12 5v14M5 12h14"/></svg>);
    case 'filter':
      return (<svg {...props}><path d="M4 5h16l-6 8v5l-4 2v-7L4 5z"/></svg>);
    case 'sort':
      return (<svg {...props}><path d="M7 4v16M7 20l-3-3M7 20l3-3"/><path d="M17 20V4M17 4l-3 3M17 4l3 3"/></svg>);
    case 'more':
      return (<svg {...props}><circle cx="6" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="18" cy="12" r="1"/></svg>);
    case 'more-v':
      return (<svg {...props}><circle cx="12" cy="6" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="12" cy="18" r="1"/></svg>);
    case 'close':
      return (<svg {...props}><path d="M6 6l12 12M18 6L6 18"/></svg>);
    case 'arrow-up':
      return (<svg {...props}><path d="M12 19V5M12 5l-5 5M12 5l5 5"/></svg>);
    case 'arrow-down':
      return (<svg {...props}><path d="M12 5v14M12 19l-5-5M12 19l5-5"/></svg>);
    case 'arrow-right':
      return (<svg {...props}><path d="M5 12h14M19 12l-5-5M19 12l-5 5"/></svg>);
    case 'phone':
      return (<svg {...props}><path d="M5 4.5h3l1.5 4-2 1.5a11 11 0 0 0 6.5 6.5l1.5-2 4 1.5v3a1.5 1.5 0 0 1-1.5 1.5A14.5 14.5 0 0 1 3.5 6 1.5 1.5 0 0 1 5 4.5z"/></svg>);
    case 'mail':
      return (<svg {...props}><rect x="3.5" y="5.5" width="17" height="13" rx="1.5"/><path d="m4 7 8 6 8-6"/></svg>);
    case 'whatsapp':
      return (<svg {...props}><path d="M4 20l1.5-4A8 8 0 1 1 9 19.5L4 20z"/><path d="M9 10c.5 2 1.5 3 3.5 4 1 .5 1.5 0 2 -.5l.5-.5c.3-.3.5-.3 1 0l1.5 1c.3.2.3.5 0 1-.5.8-1.5 1.2-2.5 1-2.5-.5-5-3-5.5-5.5-.2-1 .2-2 1-2.5.5-.3.8-.3 1 0l1 1.5c.3.5.3.7 0 1l-.5.5c-.5.5-1 1-.5 2z"/></svg>);
    case 'note':
      return (<svg {...props}><path d="M5 4.5h10l4 4V19a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5.5a1 1 0 0 1 1-1z"/><path d="M14 4.5v4h4"/><path d="M8 12h8M8 15h6"/></svg>);
    case 'check':
      return (<svg {...props}><path d="M5 12l4 4 10-10"/></svg>);
    case 'edit':
      return (<svg {...props}><path d="M4 20h4l10-10-4-4L4 16v4z"/><path d="m13 6 4 4"/></svg>);
    case 'drag':
      return (<svg {...props}><circle cx="9" cy="6" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="9" cy="18" r="1"/><circle cx="15" cy="6" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="18" r="1"/></svg>);
    case 'trash':
      return (<svg {...props}><path d="M4.5 7h15M9.5 7V5a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v2"/><path d="M6 7l1 12.5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1L18 7"/></svg>);
    case 'flame':
      return (<svg {...props}><path d="M12 3c1 4 5 5 5 9a5 5 0 1 1-10 0c0-2 1-3 2-4 0 2 1 3 2 3 0-3-1-5 1-8z"/></svg>);
    case 'pin':
      return (<svg {...props}><path d="M12 2a5 5 0 0 1 5 5c0 4-5 11-5 11S7 11 7 7a5 5 0 0 1 5-5z"/><circle cx="12" cy="7" r="2"/></svg>);
    case 'sparkle':
      return (<svg {...props}><path d="M12 4v4M12 16v4M4 12h4M16 12h4M6.5 6.5l2.5 2.5M15 15l2.5 2.5M6.5 17.5l2.5-2.5M15 9l2.5-2.5"/></svg>);
    case 'list':
      return (<svg {...props}><path d="M8 6h12M8 12h12M8 18h12"/><circle cx="4" cy="6" r="0.8"/><circle cx="4" cy="12" r="0.8"/><circle cx="4" cy="18" r="0.8"/></svg>);
    case 'building':
      return (<svg {...props}><rect x="4" y="4" width="16" height="16" rx="1"/><path d="M9 4v16M15 4v16M4 9h5M15 9h5M4 14h5M15 14h5"/></svg>);
    case 'map':
      return (<svg {...props}><path d="M3 6.5 9 4l6 2.5 6-2.5V18l-6 2.5L9 18l-6 2.5v-14z"/><path d="M9 4v14M15 6.5v14"/></svg>);
    default: return null;
  }
};

window.Icon = Icon;

/* =========================================================================
   Avatar
   ========================================================================= */
function Avatar({ name, initials, bg, fg, size = 'md', ring = false }) {
  const ini = initials || (name || '').split(' ').map(s => s[0]).slice(0,2).join('').toUpperCase();
  return (
    <div
      className={`avatar ${size === 'sm' ? 'sm' : size === 'lg' ? 'lg' : size === 'xl' ? 'xl' : ''} ${ring ? 'avatar-ring' : ''}`}
      style={{ background: bg || '#0f3d2e', color: fg || '#e8efe9' }}
      title={name}
    >
      {ini}
    </div>
  );
}
window.Avatar = Avatar;

/* =========================================================================
   Sidebar
   ========================================================================= */
function Sidebar({ counts, view, onView, authUser }) {
  const items1 = [
    { id: 'kanban',   label: 'Pipeline',    icon: 'kanban',   count: counts.total },
    { id: 'list',     label: 'Lista',       icon: 'list' },
    { id: 'reports',  label: 'Relatórios',  icon: 'reports' },
  ];
  const items2 = [
    { id: 'contacts', label: 'Clientes',    icon: 'contacts', count: counts.contacts },
    { id: 'inbox',    label: 'Caixa',       icon: 'inbox' },
    { id: 'calendar', label: 'Agenda',      icon: 'calendar' },
  ];
  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark">R</div>
        <div className="brand-name">RP <em>CRM</em></div>
      </div>

      <div className="nav-section">
        <div className="nav-label">Vendas</div>
        {items1.map(it => (
          <div key={it.id}
               className={'nav-item ' + (view === it.id ? 'active' : '')}
               onClick={() => onView(it.id)}>
            <Icon name={it.icon}/>
            <span>{it.label}</span>
            {it.count != null && <span className="nav-count">{it.count}</span>}
          </div>
        ))}
      </div>

      <div className="nav-section">
        <div className="nav-label">Relacionamento</div>
        {items2.map(it => (
          <div key={it.id}
               className={'nav-item ' + (view === it.id ? 'active' : '')}
               onClick={() => onView(it.id)}>
            <Icon name={it.icon}/>
            <span>{it.label}</span>
            {it.count != null && <span className="nav-count">{it.count}</span>}
          </div>
        ))}
      </div>

      <div className="nav-section">
        <div className="nav-label">Conta</div>
        <div className="nav-item">
          <Icon name="settings"/>
          <span>Configurações</span>
        </div>
      </div>

      <div className="sidebar-footer">
        <Avatar size="sm" initials="RP" bg="#0f3d2e" fg="#e8efe9"/>
        <div className="user-card">
          <div>
            <div className="name">{authUser?.name || 'Usuário'}</div>
            <div className="role">{authUser?.email || 'Conta autenticada'}</div>
          </div>
        </div>
      </div>
    </aside>
  );
}
window.Sidebar = Sidebar;

/* =========================================================================
   Helpers
   ========================================================================= */
function fmtBRL(n, opts = {}) {
  if (n == null) return '—';
  const compact = opts.compact;
  if (compact && n >= 1000) return (n/1000).toFixed(n % 1000 === 0 ? 0 : 1) + 'k';
  return n.toLocaleString('pt-BR');
}
window.fmtBRL = fmtBRL;

function daysLabel(n) {
  if (n === 0) return 'hoje';
  if (n === 1) return 'há 1 dia';
  if (n < 30) return `há ${n} dias`;
  const m = Math.floor(n/30);
  return `há ${m} ${m === 1 ? 'mês' : 'meses'}`;
}
window.daysLabel = daysLabel;
