'use client';

import type { Conversation } from '../../lib/types';

interface ConversationListProps {
  conversations: Conversation[];
  activeId?: string;
  onSelect: (id: string) => void;
}

function startOfDay(ts: number): number {
  const d = new Date(ts);
  d.setHours(0, 0, 0, 0);
  return d.getTime();
}

function formatGroup(ts: number, now: number): string {
  const today = startOfDay(now);
  const day = startOfDay(ts);
  const diffDays = Math.floor((today - day) / 86400000);
  if (diffDays <= 0) return 'Today';
  if (diffDays === 1) return 'Yesterday';
  if (diffDays <= 7) return 'Last 7 Days';
  if (diffDays <= 30) return 'Last 30 Days';
  return 'Older';
}

function formatTime(ts: number): string {
  const date = new Date(ts);
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}

export function ConversationList({ conversations, activeId, onSelect }: ConversationListProps) {
  const now = Date.now();
  const groups = new Map<string, Conversation[]>();

  const sorted = [...conversations].sort((a, b) => b.updatedAt - a.updatedAt);
  for (const conv of sorted) {
    const key = formatGroup(conv.updatedAt, now);
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key)!.push(conv);
  }

  if (conversations.length === 0) {
    return <p className="px-2 py-1 text-xs text-[var(--text-tertiary)]">No conversations yet</p>;
  }

  return (
    <div className="space-y-3">
      {[...groups.entries()].map(([group, items]) => (
        <section key={group}>
          <h3 className="mb-1 px-2 text-[10px] uppercase tracking-wide text-[var(--text-tertiary)]">
            {group}
          </h3>
          <div className="space-y-1">
            {items.map(conv => {
              const active = conv.id === activeId;
              return (
                <button
                  key={conv.id}
                  type="button"
                  onClick={() => onSelect(conv.id)}
                  className="w-full rounded px-2 py-1 text-left hover:bg-white/5"
                  style={{
                    borderLeft: active
                      ? '2px solid var(--accent-primary)'
                      : '2px solid transparent',
                    background: active ? 'rgba(90, 140, 255, 0.1)' : undefined,
                  }}
                  title={conv.title}
                >
                  <p className="truncate text-xs text-[var(--text-primary)]">{conv.title}</p>
                  <p className="mt-0.5 text-[10px] text-[var(--text-tertiary)]">
                    {conv.model || 'No model'} · {conv.messageCount} msgs ·{' '}
                    {formatTime(conv.updatedAt)}
                  </p>
                </button>
              );
            })}
          </div>
        </section>
      ))}
    </div>
  );
}
