// Left sidebar: brand, primary nav, chat history, user card
function Sidebar({ view, setView, drawerOpen, currentUser, conversations, onNewChat, onOpenConversation, activeConversationId, onCollapse }) {
  const navItems = [
    { id: "chat",    label: "Advisor Chat",    icon: I.chat,  count: "6" },
    { id: "plan",    label: "Degree Plan",     icon: I.plan,  count: "78/120" },
    { id: "courses", label: "Course Catalog",  icon: I.book,  count: null },
    { id: "profile", label: "Profile",         icon: I.user,  count: null },
  ];

  const itemRefs = React.useRef({});
  const indicatorRef = React.useRef(null);

  // Slide the highlight to whichever tab is active, instead of each tab
  // fading its own background in/out in place.
  React.useLayoutEffect(() => {
    const activeEl = itemRefs.current[view];
    const indicator = indicatorRef.current;
    if (!activeEl || !indicator) return;
    indicator.style.transform = `translateY(${activeEl.offsetTop}px)`;
    indicator.style.height = `${activeEl.offsetHeight}px`;
  }, [view]);

  return (
    <aside className={`sidebar ${drawerOpen ? "drawer-open" : ""}`}>
      <div className="sidebar-head">
        <div className="mark">A</div>
        <div className="wordmark">
          Academic Advisor
          <small>Carolina · AI</small>
        </div>
        {onCollapse && (
          <button className="icon-btn" onClick={onCollapse} title="Collapse sidebar" style={{marginLeft: "auto"}}>
            <I.panel />
          </button>
        )}
      </div>

      <button className="new-chat" onClick={onNewChat}>
        <I.plus />
        New advisor chat
      </button>

      <div className="nav-section nav-section-workspace">
        <div className="nav-label">Workspace</div>
        <div className="nav-indicator" ref={indicatorRef} />
        {navItems.map(n => {
          const Ico = n.icon;
          return (
            <button
              key={n.id}
              ref={el => { itemRefs.current[n.id] = el; }}
              className={`nav-item ${view === n.id ? "active" : ""}`}
              onClick={() => setView(n.id)}
            >
              <Ico />
              <span>{n.label}</span>
              {n.count && <span className="count">{n.count}</span>}
            </button>
          );
        })}
      </div>

      <div className="nav-section" style={{paddingTop: 4}}>
        <div className="nav-label">Recent</div>
      </div>
      <div className="history-list">
        {conversations && conversations.length > 0 ? (
          conversations.map((c, i) => {
            const date = new Date(c.created_at);
            const now = new Date();
            const isToday = date.toDateString() === now.toDateString();
            const isYesterday = new Date(now - 86400000).toDateString() === date.toDateString();
            const timeStr = isToday
              ? date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" })
              : isYesterday
              ? "Yesterday"
              : date.toLocaleDateString("en-US", { month: "short", day: "numeric" });

            return (
              <button
                key={c.id}
                className={`history-item ${activeConversationId === c.id ? "active" : ""}`}
                onClick={() => onOpenConversation(c)}
                style={{
                  animation: `slideInHistory 0.25s ease forwards`,
                  animationDelay: `${i * 40}ms`,
                  opacity: 0,
                }}
              >
                {c.title}
                <span className="when">{timeStr}</span>
              </button>
            );
          })
        ) : (
          <div style={{padding:"8px 10px", fontFamily:"var(--mono)", fontSize:11, color:"var(--ink-4)"}}>
            No conversations yet
          </div>
        )}
      </div>

      <div className="user-card">
        <div className="avatar">{currentUser.initials}</div>
        <div className="who">
          <b>{currentUser.name}</b><br/>
          <span>{[
            currentUser.year !== "Not set" ? currentUser.year : null,
            currentUser.major !== "Not set" ? currentUser.major.split(",")[0] : null,
          ].filter(Boolean).join(" · ") || "Profile incomplete"}</span>
        </div>
        <button
          className="logout-btn"
          title="Log out"
          onClick={() => {
            localStorage.removeItem("token");
            window.location.href = "login.html";
          }}
        >
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
            <polyline points="16 17 21 12 16 7"/>
            <line x1="21" y1="12" x2="9" y2="12"/>
          </svg>
        </button>
      </div>
    </aside>
  );
}

window.Sidebar = Sidebar;
