// Persistent left rail. Subjects come from Supabase via useSubjects().

function Sidebar() {
  const { path } = useRoute();
  const auth = useAuth();
  const subjects = useSubjects();
  const userGuides = useGuides();
  const events = useEvents();
  const [showAddSubject, setShowAddSubject] = React.useState(false);

  const userEmail = auth.user?.email || '';
  const userInitials = userEmail ? userEmail.slice(0, 2).toUpperCase() : 'U';

  const isHome = path === '/';
  const isLibrary = path === '/library';
  const isCalendar = path === '/calendar';
  const subjectMatch = path.match(/^\/subject\/([^/]+)/);
  const activeSubject = subjectMatch ? subjectMatch[1] : null;

  const items = [
    { id: 'home',     icon: '◧', label: 'Dashboard',  to: '/',         active: isHome },
    { id: 'library',  icon: '▤', label: 'All guides', to: '/library',  active: isLibrary },
    { id: 'calendar', icon: '▦', label: 'Calendar',   to: '/calendar', active: isCalendar, badge: events.length || null },
  ];

  const handleLogout = async () => { await signOut(); };

  const handleNewGuide = () => {
    if (subjects.length === 0) { setShowAddSubject(true); return; }
    navigate(`/subject/${subjects[0].id}/upload`);
  };

  return (
    <aside style={{
      width: 220, flexShrink: 0,
      background: 'var(--bg)', borderRight: '1px solid var(--line)',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      {/* App mark */}
      <div style={{ padding: '14px 14px 10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Link to="/" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ width: 22, height: 22, borderRadius: 5, background: 'var(--ink)', color: 'white', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 11 }}>sb</div>
          <span style={{ fontSize: 13, fontWeight: 600 }}>studybuddy</span>
        </Link>
      </div>

      {/* Quick add */}
      <div style={{ padding: '4px 10px 10px' }}>
        <button className="btn"
          onClick={handleNewGuide}
          style={{ width: '100%', justifyContent: 'flex-start', padding: '7px 10px', fontSize: 12 }}>
          {Icon.plus} <span style={{ flex: 1, textAlign: 'left' }}>New guide</span>
          <span className="kbd" style={{ background: 'rgba(255,255,255,0.15)', color: 'rgba(255,255,255,0.85)', borderColor: 'transparent' }}>N</span>
        </button>
      </div>

      <div style={{ padding: '4px 6px' }}>
        {items.map((it) => (
          <Link key={it.id} to={it.to} style={{
            display: 'flex', alignItems: 'center', gap: 9,
            padding: '6px 10px', borderRadius: 6,
            background: it.active ? 'var(--line-soft)' : 'transparent',
            color: it.active ? 'var(--ink)' : 'var(--ink-soft)',
            fontWeight: it.active ? 600 : 400,
            fontSize: 12.5, cursor: 'pointer', marginBottom: 1,
          }}>
            <span style={{ width: 14, color: 'var(--ink-mute)', fontSize: 12 }}>{it.icon}</span>
            <span style={{ flex: 1 }}>{it.label}</span>
            {it.badge != null && <span className="mono" style={{ fontSize: 10, color: 'var(--ink-mute)' }}>{it.badge}</span>}
          </Link>
        ))}
      </div>

      {/* Subjects */}
      <div style={{ padding: '14px 14px 6px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-mute)' }}>Subjects</span>
        <button onClick={() => setShowAddSubject(true)} title="Add subject"
          style={{ border: 'none', background: 'transparent', color: 'var(--ink-mute)', cursor: 'pointer', padding: 0, display: 'flex' }}>
          {Icon.plus}
        </button>
      </div>
      <div style={{ padding: '0 6px', flex: 1, overflowY: 'auto' }}>
        {subjects.length === 0 ? (
          <div style={{ padding: '4px 10px', fontSize: 11, color: 'var(--ink-mute)', lineHeight: 1.4 }}>
            No subjects yet. <a href="#" onClick={(e) => { e.preventDefault(); setShowAddSubject(true); }} style={{ color: 'var(--blue-deep)' }}>Add one</a> to start generating guides.
          </div>
        ) : subjects.map((s) => {
          const active = s.id === activeSubject;
          const guideCount = userGuides.filter((g) => g.subjectId === s.id).length;
          return (
            <Link key={s.id} to={`/subject/${s.id}`} style={{
              display: 'flex', alignItems: 'center', gap: 9,
              padding: '5px 10px', borderRadius: 6, fontSize: 12.5,
              background: active ? 'var(--ink)' : 'transparent',
              color: active ? 'white' : 'var(--ink-soft)',
              fontWeight: active ? 500 : 400, cursor: 'pointer', marginBottom: 1,
            }}>
              <span style={{ fontSize: 13, width: 14 }}>{s.emoji}</span>
              <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</span>
              {guideCount > 0 && <span className="mono" style={{ fontSize: 10, opacity: 0.55 }}>{guideCount}</span>}
            </Link>
          );
        })}
      </div>

      {/* Footer: user */}
      <div style={{ borderTop: '1px solid var(--line-soft)', padding: '10px 12px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Avatar initials={userInitials} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{userEmail || 'Signed in'}</div>
            <div style={{ fontSize: 10, color: 'var(--ink-mute)' }}>Personal account</div>
          </div>
          <button
            onClick={handleLogout}
            title="Sign out"
            style={{ border: 'none', background: 'transparent', color: 'var(--ink-mute)', cursor: 'pointer', padding: '4px 6px', borderRadius: 4, fontSize: 10.5 }}
            onMouseEnter={(e) => (e.currentTarget.style.background = 'var(--line-soft)')}
            onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
          >
            Log out
          </button>
        </div>
      </div>

      {showAddSubject && <SubjectDialog onClose={() => setShowAddSubject(false)} />}
    </aside>
  );
}

function Page({ children }) {
  return (
    <div className="sg" style={{ display: 'flex', height: '100%' }}>
      <Sidebar />
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {children}
      </div>
    </div>
  );
}

function PageHeader({ title, breadcrumb, actions, sub }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '12px 22px', borderBottom: '1px solid var(--line)',
      background: 'var(--bg)', minHeight: 48,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        {breadcrumb && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--ink-mute)' }}>
            {breadcrumb.map((b, i) => {
              const isLast = i === breadcrumb.length - 1;
              const label = typeof b === 'object' ? b.label : b;
              const to = typeof b === 'object' ? b.to : null;
              const node = (
                <span style={{ color: isLast ? 'var(--ink)' : 'var(--ink-mute)', fontWeight: isLast ? 500 : 400, cursor: to ? 'pointer' : 'default' }}>{label}</span>
              );
              return (
                <React.Fragment key={i}>
                  {i > 0 && <span style={{ color: 'var(--ink-whisper)' }}>/</span>}
                  {to ? <Link to={to}>{node}</Link> : node}
                </React.Fragment>
              );
            })}
          </div>
        )}
        {title && <div style={{ fontSize: 13, fontWeight: 600 }}>{title}</div>}
        {sub && <div style={{ fontSize: 11.5, color: 'var(--ink-mute)' }}>{sub}</div>}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>{actions}</div>
    </div>
  );
}

Object.assign(window, { Sidebar, Page, PageHeader });
