/* ── LAYOUT: Shell, Sidebar, Topbar ─────────────────────────────────────── */

const { useState, useEffect, useRef, useCallback } = React;

/* ── Icons (inline SVG helpers) ── */
const Icon = {
  dashboard: () => <svg width="15" height="15" viewBox="0 0 15 15" fill="none"><rect x="1" y="1" width="5.5" height="5.5" rx="1" stroke="currentColor" strokeWidth="1.2"/><rect x="8.5" y="1" width="5.5" height="5.5" rx="1" stroke="currentColor" strokeWidth="1.2"/><rect x="1" y="8.5" width="5.5" height="5.5" rx="1" stroke="currentColor" strokeWidth="1.2"/><rect x="8.5" y="8.5" width="5.5" height="5.5" rx="1" stroke="currentColor" strokeWidth="1.2"/></svg>,
  carteiras: () => <svg width="15" height="15" viewBox="0 0 15 15" fill="none"><path d="M2 3h11v9H2z" stroke="currentColor" strokeWidth="1.2"/><path d="M5 3V2a2 2 0 014 0v1" stroke="currentColor" strokeWidth="1.2"/><path d="M2 7h11" stroke="currentColor" strokeWidth="1.2"/></svg>,
  comp: () => <svg width="15" height="15" viewBox="0 0 15 15" fill="none"><path d="M2 12l3.5-4L8 11l2.5-5L13 3" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  findings: () => <svg width="15" height="15" viewBox="0 0 15 15" fill="none"><circle cx="7.5" cy="7.5" r="5.5" stroke="currentColor" strokeWidth="1.2"/><path d="M7.5 4.5v4M7.5 10v.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>,
  receitas: () => <svg width="15" height="15" viewBox="0 0 15 15" fill="none"><rect x="1" y="4" width="13" height="9" rx="1" stroke="currentColor" strokeWidth="1.2"/><path d="M4 4V3a1 1 0 011-1h5a1 1 0 011 1v1" stroke="currentColor" strokeWidth="1.2"/><path d="M5 8h5M5 10.5h3" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>,
  import: () => <svg width="15" height="15" viewBox="0 0 15 15" fill="none"><path d="M7.5 2v8M4.5 7l3 3 3-3" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/><path d="M2 11v1a1 1 0 001 1h9a1 1 0 001-1v-1" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>,
  users: () => <svg width="15" height="15" viewBox="0 0 15 15" fill="none"><circle cx="5.5" cy="4.5" r="2.5" stroke="currentColor" strokeWidth="1.2"/><path d="M1 13c0-2.5 2-4 4.5-4s4.5 1.5 4.5 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/><path d="M10.5 2a2.5 2.5 0 010 5M12 9c1.5.5 2.5 1.5 2.5 3.5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>,
  chevron: () => <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M2 4l4 4 4-4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  close: () => <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>,
  plus: () => <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><path d="M6.5 1v11M1 6.5h11" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>,
  pdf: () => <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 1h6l3 3v9H3z" stroke="currentColor" strokeWidth="1.2"/><path d="M9 1v3h3" stroke="currentColor" strokeWidth="1.2"/><path d="M4.5 7.5h5M4.5 9.5h3" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>,
  check: () => <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><path d="M2 7l3.5 3.5L11 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  alert: () => <svg width="15" height="15" viewBox="0 0 15 15" fill="none"><path d="M7.5 1L14 13H1L7.5 1z" stroke="currentColor" strokeWidth="1.2"/><path d="M7.5 5.5v3.5M7.5 10.5v.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>,
  export: () => <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><path d="M6.5 1v7M4 5.5l2.5 2.5L9 5.5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/><path d="M1 9v2a1 1 0 001 1h9a1 1 0 001-1V9" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>,
  back: () => <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><path d="M8 2L3 6.5 8 11" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  burger: () => <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M2 4.5h14M2 9h14M2 13.5h14" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>,
};

/* ── Sidebar ── */
function Sidebar({ view, setView, currentMonth, months, onMonthChange, user, onLogout, open, onClose }) {
  const pick = (fn) => (...args) => { fn(...args); if (onClose) onClose(); };
  return (
    <aside className={`sidebar${open ? ' open' : ''}`}>
      <div className="sidebar-brand">
        <img src={(window.__resources && window.__resources.logo) || "logo.png"} alt="Mirabaud 1819" style={{ width: 56, height: 'auto', display: 'block', marginBottom: 12 }} />
        <div className="sidebar-brand-name">Mirabaud</div>
        <div className="sidebar-brand-sub">Family Office</div>
      </div>

      <div className="sidebar-section">
        <div className="sidebar-section-label">Painel</div>
        {[
          { id: 'dashboard', label: 'Dashboard',   icon: Icon.dashboard },
          { id: 'comparative', label: 'Comparativo', icon: Icon.comp },
          { id: 'findings',  label: 'Achados',      icon: Icon.findings },
          { id: 'receitas',  label: 'Receitas & ROA', icon: Icon.receitas },
        ].map(item => (
          <div key={item.id} className={`sidebar-item${view===item.id?' active':''}`} onClick={() => pick(setView)(item.id)}>
            <item.icon />{item.label}
          </div>
        ))}
      </div>

      <div className="sidebar-section" style={{ marginTop: 8 }}>
        <div className="sidebar-section-label">Gestão</div>
        {[
          { id: 'import', label: 'Importar PDFs', icon: Icon.import },
          { id: 'users',  label: 'Usuários',      icon: Icon.users  },
        ].map(item => (
          <div key={item.id} className={`sidebar-item${view===item.id?' active':''}`} onClick={() => pick(setView)(item.id)}>
            <item.icon />{item.label}
          </div>
        ))}
      </div>

      <div className="sidebar-footer">
        <div className="sidebar-user">
          <div className="sidebar-user-name">{user?.nome || 'Admin'}</div>
          <div className="sidebar-user-role">{user?.role || 'administrador'}</div>
        </div>
        <div className="sidebar-logout" onClick={onLogout}>← Sair</div>
      </div>
    </aside>
  );
}

/* ── Topbar ── */
function Topbar({ title, subtitle, currentMonth, actions, onBurgerClick }) {
  return (
    <div className="topbar">
      {onBurgerClick && (
        <button className="topbar-burger" onClick={onBurgerClick} aria-label="Abrir menu">
          <Icon.burger />
        </button>
      )}
      <div className="topbar-title">{title}</div>
      {subtitle && <span style={{ fontSize: '0.72rem', color: 'var(--muted)' }}>{subtitle}</span>}
      {currentMonth && (
        <span className="topbar-month">{currentMonth.label}</span>
      )}
      {actions}
    </div>
  );
}

/* ── Shell (orchestrates layout) ── */
function Shell({ view, setView, currentMonth, months, onMonthChange, user, onLogout, children, topbarTitle, topbarSub, topbarActions }) {
  const [menuOpen, setMenuOpen] = useState(false);
  // Fechar o drawer com tecla Escape (acessibilidade)
  useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [menuOpen]);

  return (
    <div className={`shell${menuOpen ? ' menu-open' : ''}`}>
      <div
        className={`sidebar-backdrop${menuOpen ? ' open' : ''}`}
        onClick={() => setMenuOpen(false)}
        aria-hidden="true"
      />
      <Sidebar
        view={view} setView={setView}
        currentMonth={currentMonth} months={months}
        onMonthChange={onMonthChange}
        user={user} onLogout={onLogout}
        open={menuOpen}
        onClose={() => setMenuOpen(false)}
      />
      <div className="main">
        <Topbar
          title={topbarTitle}
          subtitle={topbarSub}
          currentMonth={currentMonth}
          actions={topbarActions}
          onBurgerClick={() => setMenuOpen(true)}
        />
        <div className="page-content">
          {children}
        </div>
      </div>
    </div>
  );
}

/* ── Spark Line SVG ── */
function SparkLine({ values = [], width = 60, height = 22, color = 'var(--green)', positive = true }) {
  if (!values || values.length < 2) return <span style={{ color: 'var(--muted)', fontSize: '0.7rem' }}>—</span>;
  const min = Math.min(...values);
  const max = Math.max(...values);
  const range = max - min || 1;
  const pts = values.map((v, i) => {
    const x = (i / (values.length - 1)) * width;
    const y = height - ((v - min) / range) * (height - 2) - 1;
    return `${x},${y}`;
  }).join(' ');
  const last = values[values.length - 1];
  const first = values[0];
  const c = last >= first ? 'var(--green)' : 'var(--red)';
  return (
    <svg className="spark" width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
      <polyline points={pts} fill="none" stroke={c} strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

/* ── Mini line chart (for carteira history) ── */
function LineChart({ data, width = '100%', height = 180, color = 'var(--navy)' }) {
  if (!data || data.length < 2) return <div style={{ height, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)', fontSize: '0.8rem' }}>Dados insuficientes</div>;
  const vals = data.map(d => d.value);
  const labels = data.map(d => d.label);
  const min = Math.min(...vals);
  const max = Math.max(...vals);
  const range = max - min || 1;
  const W = 600, H = height;
  const pad = { t: 16, r: 20, b: 28, l: 20 };
  const iW = W - pad.l - pad.r;
  const iH = H - pad.t - pad.b;
  const x = i => pad.l + (i / (vals.length - 1)) * iW;
  const y = v => pad.t + iH - ((v - min) / range) * iH;
  const pts = vals.map((v, i) => `${x(i)},${y(v)}`).join(' ');
  const areaClose = ` L${x(vals.length-1)},${H-pad.b} L${x(0)},${H-pad.b} Z`;
  const pathD = `M ${pts.replace(' ','  ').split(' ').join(' L ')}`;
  const areaD = pathD + areaClose;
  const positive = vals[vals.length-1] >= vals[0];
  const c = positive ? 'var(--green)' : 'var(--red)';

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width, height, display: 'block' }} preserveAspectRatio="none">
      <defs>
        <linearGradient id="chartGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={c} stopOpacity="0.12" />
          <stop offset="100%" stopColor={c} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={areaD} fill="url(#chartGrad)" />
      <polyline points={pts} fill="none" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
      {vals.map((v, i) => (
        <circle key={i} cx={x(i)} cy={y(v)} r="3" fill="white" stroke={c} strokeWidth="1.5" />
      ))}
      {labels.map((l, i) => (
        <text key={i} x={x(i)} y={H - 8} textAnchor={i===0?'start':i===labels.length-1?'end':'middle'} fontSize="9" fill="var(--muted)" fontFamily="Inter, sans-serif">{l}</text>
      ))}
    </svg>
  );
}

/* ── Modal wrapper ── */
function Modal({ open, onClose, title, children, footer }) {
  if (!open) return null;
  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal">
        <div className="modal-header">
          <h3>{title}</h3>
          <button onClick={onClose} style={{ color: 'var(--muted)' }}><Icon.close /></button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-footer">{footer}</div>}
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, Topbar, Shell, SparkLine, LineChart, Modal, Icon });
