import type { SessionSummary } from "@qjclaw/shared-types"

type SendPhase = "idle" | "preparing" | "streaming" | "finalizing"

interface SessionListProps {
  visible: boolean
  label: string
  sessions: SessionSummary[]
  activeSessionId: string
  sessionTitles: Record<string, string>
  projectActionPending: boolean
  sendPhase: SendPhase
  activeStreamSessionId?: string
  closeLabel: string
  formatSessionTitle(title: string, index: number): string
  onOpenSession(sessionId: string): void
  onCloseSession(sessionId: string): void
}

export function SessionList({
  visible,
  label,
  sessions,
  activeSessionId,
  sessionTitles,
  projectActionPending,
  sendPhase,
  activeStreamSessionId,
  closeLabel,
  formatSessionTitle,
  onOpenSession,
  onCloseSession
}: SessionListProps) {
  if (!visible) {
    return null
  }

  return (
    <section className="sidebar-section sidebar-section-fill compact sidebar-session-section">
      <div className="sidebar-section-head sidebar-section-head-subtle">
        <div className="sidebar-section-copy">
          <span className="sidebar-section-label">{label}</span>
        </div>
      </div>
      <div className="sidebar-session-list">
        {sessions.map((session, index) => (
          <div key={session.id} className={"sidebar-session-card" + (activeSessionId === session.id ? " active" : "")}>
            <button
              type="button"
              className="sidebar-session-main app-no-drag"
              aria-current={activeSessionId === session.id ? "true" : undefined}
              disabled={projectActionPending}
              onClick={() => onOpenSession(session.id)}
            >
              <strong>{sessionTitles[session.id] ?? formatSessionTitle(session.title, index)}</strong>
            </button>
            {sessions.length > 1 ? (
              <button
                type="button"
                className="sidebar-session-close app-no-drag"
                aria-label={closeLabel}
                title={closeLabel}
                disabled={projectActionPending || (sendPhase !== "idle" && activeStreamSessionId === session.id)}
                onClick={() => onCloseSession(session.id)}
              >
                <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
                  <path d="M4.25 4.25 11.75 11.75M11.75 4.25 4.25 11.75" />
                </svg>
              </button>
            ) : null}
          </div>
        ))}
      </div>
    </section>
  )
}
