// Sidebar component
function Sidebar({ route, setRoute, properties, tenants, settings, mobileMenuOpen }) {
  const tenantCount = tenants ? Object.keys(tenants).length : 0;
  const platformName = settings?.platformName?.trim() || 'Hausgut';
  const ownerName = settings?.ownerName?.trim() || '';
  const ownerInitials = ownerName
    ? ownerName.split(/\s+/).map(s => s[0]).filter(Boolean).slice(0, 2).join('').toUpperCase()
    : '?';

  const NavItem = ({ id, icon, label, count }) => (
    <button
      className={`nav-item ${route.page === id ? 'active' : ''}`}
      onClick={() => setRoute({ page: id })}
    >
      {icon}
      <span>{label}</span>
      {count != null && count > 0 && <span className="nav-count">{count}</span>}
    </button>
  );

  return (
    <aside className={`sidebar${mobileMenuOpen ? ' mobile-open' : ''}`}>
      <div className="brand">
        <div className="brand-mark"></div>
        <div className="brand-name">{platformName}</div>
      </div>

      <div className="nav-section">
        <div className="nav-label">Übersicht</div>
        <NavItem id="dashboard" icon={<Icon.Dashboard />} label="Dashboard" />
        <NavItem id="properties" icon={<Icon.Building />} label="Objekte" count={properties.length} />
        <NavItem id="tenants" icon={<Icon.Users />} label="Mieter" count={tenantCount} />
        <NavItem id="contacts" icon={<Icon.Address />} label="Kontakte" />
        <NavItem id="messages" icon={<Icon.Mail />} label="Nachrichten" />
      </div>

      <div className="nav-section">
        <div className="nav-label">Operativ</div>
        <NavItem id="tasks" icon={<Icon.Doc />} label="Aufgaben" />
        <NavItem id="calendar" icon={<Icon.Calendar />} label="Kalender" />
        <NavItem id="maintenance" icon={<Icon.Wrench />} label="Wartung" />
        <NavItem id="contracts" icon={<Icon.Doc />} label="Verträge" />
        <NavItem id="rent-status" icon={<Icon.Chart />} label="Mieten-Status" />
        <NavItem id="reports" icon={<Icon.Chart />} label="Berichte" />
        <NavItem id="tax" icon={<Icon.Chart />} label="Steuer / AfA" />
      </div>

      <div className="nav-section">
        <div className="nav-label">Intelligenz</div>
        <NavItem id="analytics" icon={<Icon.Chart />} label="Analytik" />
        <NavItem id="assistant" icon={<Icon.Sparkle />} label="KI-Berater" />
      </div>

      <div className="sidebar-footer">
        <button className="nav-item" onClick={() => setRoute({ page: 'settings' })}>
          <Icon.Settings />
          <span>Einstellungen</span>
        </button>
        <button className="user-chip" onClick={() => setRoute({ page: 'settings' })} style={{ background: 'none', border: 0, padding: 0, font: 'inherit', textAlign: 'left', cursor: 'pointer' }}>
          <div className="avatar">{ownerInitials}</div>
          <div>
            <div className="user-name">{ownerName || 'Konto einrichten'}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>{ownerName ? 'Eigentümer' : '→ Einstellungen'}</div>
          </div>
        </button>
      </div>
    </aside>
  );
}

// Topbar with breadcrumbs
function Topbar({ route, setRoute, properties, tenants, onMenuToggle }) {
  const crumbs = [];
  if (route.page === 'dashboard') crumbs.push({ label: 'Dashboard' });
  else if (route.page === 'properties' && !route.propertyId) crumbs.push({ label: 'Objekte' });
  else if (route.propertyId) {
    crumbs.push({ label: 'Objekte', onClick: () => setRoute({ page: 'properties' }) });
    const prop = properties.find(p => p.id === route.propertyId);
    if (prop) {
      crumbs.push({ label: prop.name, onClick: route.unitId ? () => setRoute({ page: 'properties', propertyId: prop.id }) : null });
      if (route.unitId) {
        const unit = prop.units.find(u => u.id === route.unitId);
        if (unit) crumbs.push({ label: unit.label });
      }
    }
  }
  else if (route.page === 'tenants' && route.tenantId) {
    crumbs.push({ label: 'Mieter', onClick: () => setRoute({ page: 'tenants' }) });
    const t = tenants?.[route.tenantId];
    crumbs.push({ label: t?.name || 'Mieter' });
  }
  else if (route.page === 'tenants') crumbs.push({ label: 'Mieter' });
  else if (route.page === 'contacts' && route.contactId) {
    crumbs.push({ label: 'Kontakte', onClick: () => setRoute({ page: 'contacts' }) });
    const ct = (window.DEMO_DATA?.contacts || []).find(c => c.id === route.contactId);
    if (ct) crumbs.push({ label: ct.company });
  }
  else if (route.page === 'contacts') crumbs.push({ label: 'Kontakte' });
  else if (route.page === 'calendar') crumbs.push({ label: 'Kalender' });
  else if (route.page === 'maintenance') crumbs.push({ label: 'Wartung' });
  else if (route.page === 'contracts') crumbs.push({ label: 'Verträge' });
  else if (route.page === 'reports') crumbs.push({ label: 'Berichte' });
  else if (route.page === 'tax') crumbs.push({ label: 'Steuer / AfA' });
  else if (route.page === 'rent-status') crumbs.push({ label: 'Mieten-Status' });
  else if (route.page === 'tasks') crumbs.push({ label: 'Aufgaben' });
  else if (route.page === 'analytics') crumbs.push({ label: 'Analytik' });
  else if (route.page === 'assistant') crumbs.push({ label: 'KI-Berater' });
  else if (route.page === 'messages') crumbs.push({ label: 'Nachrichten' });
  else if (route.page === 'settings') crumbs.push({ label: 'Einstellungen' });

  return (
    <div className="topbar">
      <button
        type="button"
        className="hamburger-btn"
        onClick={onMenuToggle}
        aria-label="Menü öffnen"
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
          <line x1="3" y1="6" x2="21" y2="6" />
          <line x1="3" y1="12" x2="21" y2="12" />
          <line x1="3" y1="18" x2="21" y2="18" />
        </svg>
      </button>
      <div className="crumbs">
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="crumbs-sep">/</span>}
            {c.onClick ? (
              <button onClick={c.onClick}>{c.label}</button>
            ) : (
              <span className="current">{c.label}</span>
            )}
          </React.Fragment>
        ))}
      </div>
      <div className="search">
        <Icon.Search />
        <input placeholder="Suche Objekte, Mieter, Dokumente…" />
      </div>
      <NotificationBell setRoute={setRoute} />
    </div>
  );
}

Object.assign(window, { Sidebar, Topbar });
