// sidebar.jsx — Sidebar navigation

const { useState, useEffect, useRef } = React;

// Hub-URL: lokal /hub/, Dev hub.dev.haikara.it/, Live haikara.it/. Wird in
// app.jsx als window.HK_HUB_URL bereitgestellt; Fallback für den (unwahr-
// scheinlichen) Fall, dass das nicht gesetzt ist.
function getHubUrl() {
  if (typeof window !== 'undefined' && window.HK_HUB_URL) return window.HK_HUB_URL;
  const h = window.location.hostname;
  if (h === 'localhost' || h === '127.0.0.1') return window.location.origin + '/hub/';
  if (/\.dev\.haikara\.it$/i.test(h))         return 'https://hub.dev.haikara.it/';
  return 'https://haikara.it/';
}

const Sidebar = ({ route, setRoute, user, onLogout, darkMode, setDarkMode, topicAreas = [], sections = [], notes, userCan = () => true, roles = [], onOpenTweaks, hasUnseenRelease = false }) => {
  const roleObj = roles.find(r => r.id === user?.role);
  const [collapsed, setCollapsed] = useState({});
  const [searchVal, setSearchVal] = useState('');

  const handleSearch = (e) => {
    const v = e.target.value;
    setSearchVal(v);
    if (v.trim()) setRoute({ page: 'search', query: v });
    else setRoute({ page: 'dashboard' });
  };

  const toggle = (id) => setCollapsed(c => ({ ...c, [id]: !c[id] }));

  const navItem = (label, page, params = {}, icon, color, opts = {}) => {
    const active = route.page === page && (!params.sectionId || route.sectionId === params.sectionId);
    return (
      <button
        key={label}
        data-tour={opts.dataTour}
        onClick={() => setRoute({ page, ...params })}
        style={{
          display: 'flex', alignItems: 'center', gap: 8,
          width: '100%', padding: '7px 12px', borderRadius: 6,
          border: 'none', cursor: 'pointer', textAlign: 'left',
          background: active ? 'var(--accent-dim)' : 'transparent',
          color: active ? 'var(--accent)' : 'var(--text-muted)',
          fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: active ? 600 : 400,
          transition: 'all 0.15s',
          borderLeft: `2px solid ${active ? 'var(--accent)' : 'transparent'}`,
        }}
        onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--surface-2)'; }}
        onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}
      >
        {color ? (
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: color, flexShrink: 0, boxShadow: active ? `0 0 6px ${color}80` : 'none' }} />
        ) : (
          <Icon name={icon} size={14} color={active ? 'var(--accent)' : 'var(--text-muted)'} />
        )}
        <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
        {opts.dot && (
          <span title="Neue Version verfügbar" style={{
            width: 7, height: 7, borderRadius: '50%', background: 'var(--accent)',
            boxShadow: '0 0 6px var(--accent)', flexShrink: 0,
          }} />
        )}
      </button>
    );
  };

  return (
    <div style={{
      width: 'var(--sidebar-width)', flexShrink: 0,
      background: 'var(--sidebar-bg)', borderRight: '1px solid var(--border)',
      display: 'flex', flexDirection: 'column', height: '100vh',
      position: 'sticky', top: 0, overflow: 'hidden',
    }}>
      {/* Logo + Hub-Back */}
      <div style={{ padding: '16px 16px 12px', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
          <div style={{
            width: 28, height: 28, borderRadius: 6,
            background: 'linear-gradient(135deg, var(--accent), #6d28d9)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="zap" size={14} color="#fff" />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, color: 'var(--text)', letterSpacing: '-0.02em' }}>Heronry</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-muted)' }}>Wissens-Hub</div>
          </div>
          <a href={getHubUrl()} title="Zurück zum Haikara-Hub"
            data-tour="hub-back"
            style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              width: 28, height: 28, borderRadius: 6,
              background: 'var(--surface-2)', border: '1px solid var(--border)',
              color: 'var(--text-muted)', textDecoration: 'none',
              transition: 'all 0.15s', flexShrink: 0,
            }}
            onMouseEnter={e => { e.currentTarget.style.background = 'var(--accent-dim)'; e.currentTarget.style.color = 'var(--accent)'; e.currentTarget.style.borderColor = 'var(--accent)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'var(--surface-2)'; e.currentTarget.style.color = 'var(--text-muted)'; e.currentTarget.style.borderColor = 'var(--border)'; }}
          >
            <Icon name="grid" size={13} />
          </a>
        </div>
        {/* Search */}
        <div style={{ position: 'relative' }}>
          <div style={{ position: 'absolute', left: 8, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: 'var(--text-muted)' }}>
            <Icon name="search" size={12} />
          </div>
          <input
            value={searchVal} onChange={handleSearch}
            placeholder="Suchen... (Ctrl+K)"
            style={{
              width: '100%', boxSizing: 'border-box', padding: '6px 10px 6px 26px',
              background: 'var(--surface-2)', border: '1px solid var(--border)',
              borderRadius: 6, color: 'var(--text)', fontSize: 12,
              fontFamily: 'var(--font-sans)', outline: 'none',
            }}
            onFocus={e => e.target.style.borderColor = 'var(--accent)'}
            onBlur={e => e.target.style.borderColor = 'var(--border)'}
          />
        </div>
      </div>

      {/* Nav */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 8px', scrollbarWidth: 'thin', scrollbarColor: 'var(--border) transparent' }} data-tour="sidebar-nav">
        {/* Main nav */}
        <div style={{ marginBottom: 4 }}>
          {navItem('Dashboard', 'dashboard', {}, 'home')}
          {navItem('Graph / Mindmap', 'graph', {}, 'link', null, { dataTour: 'nav-graph' })}
          {navItem('Suche', 'search', { query: '' }, 'search')}
          {navItem('Kalender', 'calendar', {}, 'calendar', null, { dataTour: 'nav-calendar' })}
          {navItem('Patch Notes', 'patchnotes', {}, 'tag', null, { dot: hasUnseenRelease })}
          {userCan('users:manage') && navItem('Admin Panel', 'settings', { tab: 'admin' }, 'lock', '#f87171')}
        </div>

        <div style={{ height: 1, background: 'var(--border)', margin: '8px 4px' }} />

        {/* Topic Areas — jeweils mit flacher Section-Liste */}
        {topicAreas.map((area, idx) => {
          const areaSections = sections.filter(s => s.topicAreaId === area.id);
          return (
            <div key={area.id} data-tour={idx === 0 ? 'sidebar-sections' : undefined} style={{ marginBottom: 4 }}>
              <button
                onClick={() => toggle(area.id)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 6,
                  width: '100%', padding: '4px 8px', border: 'none',
                  background: 'transparent', cursor: 'pointer',
                  color: 'var(--text-dim)', fontSize: 10,
                  fontFamily: 'var(--font-mono)', textTransform: 'uppercase',
                  letterSpacing: '0.08em', fontWeight: 500,
                }}
              >
                <Icon name={collapsed[area.id] ? 'chevronRight' : 'chevronDown'} size={12} color="var(--text-dim)" />
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: area.color, flexShrink: 0 }} />
                {area.label}
              </button>
              {!collapsed[area.id] && (
                <div style={{ paddingLeft: 0 }}>
                  {areaSections.map(s => {
                    const noteCount = notes.filter(n => n.sectionId === s.id).length;
                    const isActive = route.page === 'section' && route.sectionId === s.id;
                    const display = s.short || s.label;
                    return (
                      <button
                        key={s.id}
                        onClick={() => setRoute({ page: 'section', sectionId: s.id })}
                        style={{
                          display: 'flex', alignItems: 'center', gap: 8,
                          width: '100%', padding: '6px 10px', border: 'none',
                          background: isActive ? 'var(--accent-dim)' : 'transparent',
                          cursor: 'pointer', borderRadius: 6,
                          borderLeft: `2px solid ${isActive ? s.color : 'transparent'}`,
                          transition: 'all 0.15s',
                        }}
                        onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = 'var(--surface-2)'; }}
                        onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}
                      >
                        <span style={{ width: 7, height: 7, borderRadius: '50%', background: s.color, flexShrink: 0, boxShadow: isActive ? `0 0 8px ${s.color}` : 'none' }} />
                        <span style={{
                          flex: 1, textAlign: 'left',
                          fontFamily: 'var(--font-mono)', fontSize: 11,
                          color: isActive ? 'var(--text)' : 'var(--text-muted)',
                          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                          fontWeight: isActive ? 600 : 400,
                        }}>{display}</span>
                        {noteCount > 0 && (
                          <span style={{
                            fontSize: 10, padding: '1px 5px', borderRadius: 10,
                            background: 'var(--surface-2)', color: 'var(--text-dim)',
                            fontFamily: 'var(--font-mono)',
                          }}>{noteCount}</span>
                        )}
                      </button>
                    );
                  })}
                  {areaSections.length === 0 && (
                    <div style={{ padding: '6px 10px', fontSize: 11, color: 'var(--text-dim)', fontStyle: 'italic' }}>
                      Keine Sections.
                    </div>
                  )}
                </div>
              )}
            </div>
          );
        })}

        <div style={{ height: 1, background: 'var(--border)', margin: '8px 4px' }} />

        {/* Neue Notiz Button — nur für Writer+ */}
        {userCan('notes:write') && (
          <button
            onClick={() => setRoute({ page: 'note-new', sectionId: null })}
            style={{
              display: 'flex', alignItems: 'center', gap: 8,
              width: '100%', padding: '7px 12px', borderRadius: 6,
              border: '1px dashed var(--border)', cursor: 'pointer',
              background: 'transparent', color: 'var(--text-muted)',
              fontSize: 13, fontFamily: 'var(--font-sans)',
              transition: 'all 0.15s',
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--accent)'; e.currentTarget.style.color = 'var(--accent)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.color = 'var(--text-muted)'; }}
          >
            <Icon name="plus" size={14} />
            Neue Notiz
          </button>
        )}
      </div>

      {/* Footer */}
      <div style={{ borderTop: '1px solid var(--border)', padding: 12, flexShrink: 0 }}>
        {/* Dark mode toggle */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <span style={{ fontSize: 12, color: 'var(--text-muted)', fontFamily: 'var(--font-sans)' }}>
            {darkMode ? 'Dark Mode' : 'Light Mode'}
          </span>
          <button
            onClick={() => setDarkMode(!darkMode)}
            style={{
              width: 40, height: 22, borderRadius: 11,
              background: darkMode ? 'var(--accent)' : 'var(--border)',
              border: 'none', cursor: 'pointer', position: 'relative',
              transition: 'background 0.2s',
            }}
          >
            <span style={{
              position: 'absolute', top: 3, left: darkMode ? 20 : 3,
              width: 16, height: 16, borderRadius: '50%', background: '#fff',
              transition: 'left 0.2s', display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name={darkMode ? 'moon' : 'sun'} size={10} color={darkMode ? '#7c3aed' : '#f59e0b'} />
            </span>
          </button>
        </div>

        {/* User */}
        {user && (
          <UserRow
            user={user} roleObj={roleObj}
            route={route} setRoute={setRoute}
            onLogout={onLogout} onOpenTweaks={onOpenTweaks}
            userCan={userCan}
          />
        )}
      </div>
    </div>
  );
};

// Avatar + Name unten — klickbar mit Dropdown-Menü.
// Quick-Access-Icons (Schloss, Sliders, Logout) bleiben parallel sichtbar (per Designentscheidung).
const UserRow = ({ user, roleObj, route, setRoute, onLogout, onOpenTweaks, userCan = () => true }) => {
  const [menuOpen, setMenuOpen] = useState(false);
  const rootRef = useRef(null);

  // Outside-click + Escape schließen
  useEffect(() => {
    if (!menuOpen) return;
    const onDoc = (e) => { if (rootRef.current && !rootRef.current.contains(e.target)) setMenuOpen(false); };
    const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDoc);
      document.removeEventListener('keydown', onKey);
    };
  }, [menuOpen]);

  const select = (fn) => () => { setMenuOpen(false); fn(); };
  const isAdmin = userCan('users:manage') || userCan('roles:manage') || userCan('settings:manage') || userCan('topic_areas:manage') || userCan('sections:manage');

  return (
    <div ref={rootRef} style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 8 }}>
      <button
        onClick={() => setMenuOpen(o => !o)}
        title="Profil & Einstellungen"
        style={{
          flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', gap: 8,
          background: menuOpen ? 'var(--surface-2)' : 'transparent',
          border: 'none', borderRadius: 6, padding: '4px 6px',
          cursor: 'pointer', textAlign: 'left',
          transition: 'background 0.15s',
        }}
        onMouseEnter={e => { if (!menuOpen) e.currentTarget.style.background = 'var(--surface-2)'; }}
        onMouseLeave={e => { if (!menuOpen) e.currentTarget.style.background = 'transparent'; }}
      >
        <Avatar initials={user.initials} size={30} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.name}</div>
          <div style={{ fontSize: 10, color: roleObj?.color || 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{roleObj?.label || user.role || 'keine Rolle'}</div>
        </div>
        <Icon name="chevronRight" size={12} color="var(--text-muted)" />
      </button>

      {/* Quick-Access-Icons — bleiben parallel zum Menü, können später raus */}
      <button
        data-tour="user-security"
        onClick={() => setRoute({ page: 'settings', tab: 'security' })}
        title="Konto & Sicherheit"
        style={{ background: 'none', border: 'none', cursor: 'pointer', color: route.page === 'settings' && route.tab === 'security' ? 'var(--accent)' : 'var(--text-muted)', padding: 4, borderRadius: 4, display: 'flex' }}
        onMouseEnter={e => { e.currentTarget.style.color = 'var(--accent)'; }}
        onMouseLeave={e => { e.currentTarget.style.color = (route.page === 'settings' && route.tab === 'security') ? 'var(--accent)' : 'var(--text-muted)'; }}
      >
        <Icon name="lock" size={15} />
      </button>
      {onOpenTweaks && (
        <button
          onClick={onOpenTweaks}
          title="Schnell-Tweaks (Ctrl+,)"
          style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', padding: 4, borderRadius: 4, display: 'flex' }}
          onMouseEnter={e => e.currentTarget.style.color = 'var(--accent)'}
          onMouseLeave={e => e.currentTarget.style.color = 'var(--text-muted)'}
        >
          <Icon name="sliders" size={15} />
        </button>
      )}
      <button
        onClick={onLogout}
        title="Abmelden"
        style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', padding: 4, borderRadius: 4, display: 'flex' }}
        onMouseEnter={e => e.currentTarget.style.color = '#f87171'}
        onMouseLeave={e => e.currentTarget.style.color = 'var(--text-muted)'}
      >
        <Icon name="logout" size={15} />
      </button>

      {/* Dropdown */}
      {menuOpen && (
        <div style={{
          position: 'absolute', bottom: 'calc(100% + 8px)', left: 0, right: 0,
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 10, boxShadow: '0 12px 32px rgba(0,0,0,0.4)',
          padding: 6, zIndex: 100,
          animation: 'fadeIn 0.12s ease',
        }}>
          <div style={{ padding: '8px 10px 6px', borderBottom: '1px solid var(--border)', marginBottom: 4 }}>
            <div style={{ fontSize: 11, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>{user.email}</div>
          </div>
          <MenuItem icon="sliders" label="Einstellungen" onClick={select(() => setRoute({ page: 'settings' }))} />
          <MenuItem icon="lock"     label="Konto & Sicherheit" onClick={select(() => setRoute({ page: 'settings', tab: 'security' }))} />
          {isAdmin && (
            <MenuItem icon="user" label="Verwaltung" onClick={select(() => setRoute({ page: 'settings', tab: 'admin' }))} />
          )}
          <MenuItem icon="info"     label="Patch-Notes" onClick={select(() => setRoute({ page: 'patchnotes' }))} />
          <div style={{ height: 1, background: 'var(--border)', margin: '4px 0' }} />
          <MenuItem icon="grid"     label="Zum Haikara-Hub" onClick={select(() => { window.location.assign(getHubUrl()); })} />
          <MenuItem icon="logout"   label="Abmelden" danger onClick={select(onLogout)} />
        </div>
      )}
    </div>
  );
};

const MenuItem = ({ icon, label, onClick, danger }) => {
  const [hover, setHover] = useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', alignItems: 'center', gap: 10,
        width: '100%', padding: '8px 10px',
        background: hover ? (danger ? 'rgba(248,113,113,0.12)' : 'var(--surface-2)') : 'transparent',
        border: 'none', borderRadius: 6, cursor: 'pointer',
        color: danger ? '#f87171' : 'var(--text)',
        fontSize: 13, fontFamily: 'var(--font-sans)', textAlign: 'left',
        transition: 'background 0.1s',
      }}
    >
      <Icon name={icon} size={14} color={danger ? '#f87171' : 'var(--text-muted)'} />
      {label}
    </button>
  );
};

Object.assign(window, { Sidebar });
