const { NavItem, SearchField, IconButton, Avatar, Icon, Dialog, QuickAction, Button, ListItem } = window.MyBrokerPantanalDesignSystem_2460cb;

const NAV = [
  { id: 'dashboard', icon: 'layout-dashboard', label: 'Painel' },
  { id: 'properties', icon: 'house', label: 'Imóveis' },
  { id: 'contracts', icon: 'file-text', label: 'Contratos' },
  { id: 'billing', icon: 'receipt', label: 'Finanças' },
  { id: 'payouts', icon: 'wallet', label: 'Repasses' },
  { id: 'people', icon: 'users', label: 'Pessoas' },
  { id: 'inspections', icon: 'clipboard-check', label: 'Vistorias' },
  { id: 'maintenance', icon: 'wrench', label: 'Manutenção' },
  { id: 'reports', icon: 'chart-column', label: 'Relatórios' },
  { id: 'settings', icon: 'settings', label: 'Configurações' },
];
const ASSET = './assets/';

function useContainerMode(ref) {
  const [w, setW] = React.useState(1280);
  React.useLayoutEffect(() => {
    if (!ref.current) return;
    const measure = () => ref.current && setW(ref.current.offsetWidth);
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(ref.current);
    window.addEventListener('resize', measure);
    return () => { ro.disconnect(); window.removeEventListener('resize', measure); };
  }, []);
  return w < 760 ? 'mobile' : w < 1120 ? 'tablet' : 'desktop';
}

function Sidebar({ route, go, collapsed, logoUrl }) {
  return (
    <aside style={{ width: collapsed ? 'var(--sidebar-w-collapsed)' : 'var(--sidebar-w)', flexShrink: 0, margin: 12, marginRight: 0, background: 'var(--surface-card)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', display: 'flex', flexDirection: 'column', padding: collapsed ? '20px 14px' : '22px 14px', gap: 2, alignItems: collapsed ? 'center' : 'stretch' }}>
      <div style={{ height: 36, display: 'flex', alignItems: 'center', padding: collapsed ? 0 : '0 8px', marginBottom: 18 }}>
        {/* A logo-mark (ícone pequeno, barra recolhida) é um ativo fixo à parte — só a logo
            completa (expandida) é a trocada em Configurações. */}
        <img src={collapsed ? ASSET + 'logo-mark.png' : (logoUrl || ASSET + 'logo-mybroker-pantanal.png')} alt="MyBroker Pantanal" style={{ height: collapsed ? 28 : 30, width: 'auto', maxWidth: collapsed ? undefined : 160, objectFit: 'contain' }} />
      </div>
      {NAV.map((n) => <NavItem key={n.id} icon={n.icon} label={n.label} badge={n.badge} active={route === n.id || ((route === 'contract-new' || route === 'contract-type') && n.id === 'contracts')} collapsed={collapsed} onClick={() => go(n.id)} />)}
      <div style={{ flex: 1 }} />
      <NavItem icon="life-buoy" label="Ajuda e suporte" collapsed={collapsed} />
      <NavItem icon="log-out" label="Sair" collapsed={collapsed} onClick={() => go('login')} />
    </aside>
  );
}

// Painel de "Contratos a vencer" aberto pelo sininho — só lista o que vence nos próximos 30
// dias (é exatamente esse conjunto que deixa o sininho vermelho).
function NotificacoesDialog({ open, onClose, items, onOpenLocacoes }) {
  return (
    <Dialog open={open} onClose={onClose} size="sm" strategy="absolute" placement="center" icon="file-text" tone="warning"
      title="Contratos a vencer" description="Locações ativas vencendo nos próximos 30 dias"
      footer={<Button variant="secondary" onClick={onClose}>Fechar</Button>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 360, overflowY: 'auto' }}>
        {(!items || items.length === 0) ? (
          <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Nenhum contrato vencendo nos próximos 30 dias.</span>
        ) : items.map((r, i) => (
          <ListItem key={r.propertyId + i} variant="card"
            onClick={() => { onOpenLocacoes && onOpenLocacoes(r.propertyId); onClose(); }}
            style={{ padding: '10px 12px', cursor: 'pointer' }}
            leading={<span style={{ fontSize: 11, color: 'var(--text-subtle)', width: 20 }}>{String(i + 1).padStart(2, '0')}</span>}
            title={r.title} description={r.sub}
            trailing={<span style={{ fontSize: 12, fontWeight: 600, color: r.dias <= 7 ? 'var(--status-danger-text)' : 'var(--status-warning-text)', whiteSpace: 'nowrap' }}>{r.dias} {r.dias === 1 ? 'dia' : 'dias'}</span>} />
        ))}
      </div>
    </Dialog>
  );
}

function Topbar({ user, onSearch, mode, notifItems, onOpenLocacoes }) {
  const [notifOpen, setNotifOpen] = React.useState(false);
  const temNotif = !!(notifItems && notifItems.length > 0);
  if (mode === 'mobile') {
    return (
      <header style={{ position: 'sticky', top: 0, zIndex: 20, display: 'flex', alignItems: 'center', gap: 6, height: 60, padding: '0 12px 0 16px', background: 'rgba(244,245,249,.82)', backdropFilter: 'var(--blur-glass)', WebkitBackdropFilter: 'var(--blur-glass)' }}>
        <img src={ASSET + 'logo-mark.png'} alt="MyBroker Pantanal" style={{ height: 26 }} />
        <div style={{ flex: 1 }} />
        <IconButton icon="search" label="Buscar" variant="ghost" size="lg" onClick={onSearch} />
        <IconButton icon="bell" label="Notificações" variant="ghost" size="lg" badge={temNotif} onClick={() => setNotifOpen(true)} />
        <Avatar name={user.name} size={32} />
        <NotificacoesDialog open={notifOpen} onClose={() => setNotifOpen(false)} items={notifItems} onOpenLocacoes={onOpenLocacoes} />
      </header>
    );
  }
  return (
    <header style={{ display: 'flex', alignItems: 'center', gap: 12, height: 'var(--topbar-h)', padding: '0 var(--page-pad)' }}>
      <div onClick={onSearch} style={{ width: '100%', maxWidth: 420 }}>
        <SearchField placeholder="Buscar imóveis, contratos, pessoas…" readOnly style={{ cursor: 'pointer' }} />
      </div>
      <div style={{ flex: 1 }} />
      <IconButton icon="bell" label="Notificações" variant="ghost" badge={temNotif} onClick={() => setNotifOpen(true)} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <Avatar name={user.name} size={34} />
        {mode === 'desktop' && <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.25 }}><span style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-strong)' }}>{user.name}</span><span style={{ fontSize: 11, color: 'var(--text-subtle)' }}>{user.role}</span></div>}
      </div>
      <NotificacoesDialog open={notifOpen} onClose={() => setNotifOpen(false)} items={notifItems} onOpenLocacoes={onOpenLocacoes} />
    </header>
  );
}

function MobileNav({ route, go, onPlus, onMenu }) {
  const item = (id, icon, label, onClick) => {
    const active = route === id;
    return (
      <button key={id} type="button" onClick={onClick || (() => go(id))} style={{ flex: 1, height: '100%', border: 0, background: 'transparent', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 3, color: active ? 'var(--text-accent)' : 'var(--text-muted)', fontFamily: 'var(--font-sans)', fontSize: 10.5, fontWeight: active ? 600 : 400, cursor: 'pointer' }}>
        <Icon name={icon} size={22} />{label}
      </button>
    );
  };
  return (
    <nav style={{ position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 30, height: 'var(--mobile-nav-h)', display: 'flex', alignItems: 'center', padding: '0 6px', background: 'rgba(255,255,255,.88)', backdropFilter: 'var(--blur-glass)', WebkitBackdropFilter: 'var(--blur-glass)', borderTop: '1px solid var(--border-subtle)' }}>
      {item('dashboard', 'layout-dashboard', 'Painel')}
      {item('properties', 'house', 'Imóveis')}
      <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
        <button type="button" aria-label="Criar" onClick={onPlus} style={{ width: 52, height: 52, marginTop: -22, borderRadius: '50%', border: '4px solid var(--bg-app)', background: 'var(--mb-black)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--shadow-md)', cursor: 'pointer' }}><Icon name="plus" size={22} /></button>
      </div>
      {item('billing', 'receipt', 'Finanças')}
      {item('menu', 'menu', 'Menu', onMenu)}
    </nav>
  );
}

function MobileMenuSheet({ open, onClose, route, go, user }) {
  return (
    <Dialog open={open} onClose={onClose} placement="sheet" strategy="absolute" icon="menu" tone="neutral" title="Menu">
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 12, borderRadius: 'var(--radius-md)', background: 'var(--surface-sunken)', marginBottom: 12 }}>
        <Avatar name={user.name} size={40} />
        <div style={{ display: 'flex', flexDirection: 'column', flex: 1 }}><span style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-strong)' }}>{user.name}</span><span style={{ fontSize: 12, color: 'var(--text-subtle)' }}>{user.role}</span></div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {NAV.map((n) => <NavItem key={n.id} icon={n.icon} label={n.label} badge={n.badge} active={route === n.id} onClick={() => { go(n.id); onClose(); }} style={{ height: 44 }} />)}
        <NavItem icon="log-out" label="Sair" onClick={() => { go('login'); onClose(); }} style={{ height: 44 }} />
      </div>
    </Dialog>
  );
}

function CreateSheet({ open, onClose, actions, onAction }) {
  return (
    <Dialog open={open} onClose={onClose} placement="sheet" strategy="absolute" icon="plus" tone="accent" title="Criar" description="Atalhos para as tarefas mais frequentes">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0,1fr))', gap: 10 }}>
        {actions.map((a) => <QuickAction key={a.id} icon={a.icon} label={a.label} variant={a.primary ? 'primary' : 'default'} onClick={() => { onAction(a.id); onClose(); }} />)}
      </div>
    </Dialog>
  );
}

// Badge coloridinho de ícone — cada seção do site com sua cor/ícone (imóveis, pessoas,
// finanças etc.), reaproveitado em título de página e em cabeçalho de card.
const BADGE_TONE = {
  accent: { bg: 'var(--mb-blue-100)', fg: 'var(--text-accent)' },
  success: { bg: 'var(--status-success-bg)', fg: 'var(--status-success-text)' },
  warning: { bg: 'var(--status-warning-bg)', fg: 'var(--status-warning-text)' },
  info: { bg: 'var(--status-info-bg)', fg: 'var(--status-info-text)' },
  danger: { bg: 'var(--status-danger-bg)', fg: 'var(--status-danger-text)' },
  neutral: { bg: 'var(--surface-sunken)', fg: 'var(--text-strong)' },
};
function IconBadge({ icon, tone = 'accent', size = 40 }) {
  const t = BADGE_TONE[tone] || BADGE_TONE.accent;
  return (
    <div style={{ width: size, height: size, borderRadius: Math.round(size * 0.28), flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: t.bg }}>
      <Icon name={icon} size={Math.round(size * 0.5)} color={t.fg} />
    </div>
  );
}

function PageHeader({ title, subtitle, actions, mode, display, icon, tone }) {
  const m = mode === 'mobile';
  return (
    <div style={{ display: 'flex', alignItems: m ? 'flex-start' : 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', marginBottom: m ? 16 : 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
        {icon && <IconBadge icon={icon} tone={tone} size={m ? 36 : 44} />}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0 }}>
          {display
            ? <h1 style={{ margin: 0, fontSize: m ? 22 : 26, fontWeight: 500, letterSpacing: '-0.01em', color: 'var(--text-strong)', lineHeight: 1.15 }}>{title}</h1>
            : <h1 style={{ margin: 0, fontSize: m ? 24 : 32, fontWeight: 600, fontStretch: '125%', textTransform: 'uppercase', letterSpacing: '0.01em', color: 'var(--text-strong)', lineHeight: 1.05 }}>{title}</h1>}
          {subtitle && <p style={{ margin: 0, fontSize: 13, color: 'var(--text-muted)', textWrap: 'pretty' }}>{subtitle}</p>}
        </div>
      </div>
      {actions && <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>{actions}</div>}
    </div>
  );
}

function PropertyThumb({ size = 44, type }) {
  const icon = type === 'Comercial' ? 'building-2' : type === 'Apartamento' ? 'building' : type === 'Rural' ? 'map-pin' : 'house';
  return (
    <span style={{ width: size, height: size, flexShrink: 0, borderRadius: size > 60 ? 16 : 10, background: 'linear-gradient(135deg, var(--mb-blue-50), var(--mb-gray-100))', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--mb-blue-400)' }}>
      <Icon name={icon} size={Math.round(size * 0.42)} strokeWidth={1.5} />
    </span>
  );
}

function Placeholder({ label, mode, action }) {
  return (
    <div style={{ padding: mode === 'mobile' ? 16 : 'var(--page-pad)' }}>
      <PageHeader title={label} mode={mode} actions={action} />
      <div style={{ borderRadius: 'var(--radius-lg)', border: '1.5px dashed var(--border-strong)', padding: 40, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, textAlign: 'center', color: 'var(--text-muted)' }}>
        <Icon name="layout-grid" size={32} strokeWidth={1.25} color="var(--mb-gray-400)" />
        <span style={{ fontSize: 14, color: 'var(--text-strong)', fontWeight: 500 }}>Tela não incluída neste UI kit</span>
        <span style={{ fontSize: 13, maxWidth: 380 }}>Componha esta página com os mesmos módulos do Painel e de Imóveis (Card, ListItem, MetaField, Tabs, Badge).</span>
      </div>
    </div>
  );
}

Object.assign(window, { NAV, ASSET, useContainerMode, Sidebar, Topbar, MobileNav, MobileMenuSheet, CreateSheet, PageHeader, PropertyThumb, Placeholder });
