"use client";
import type { MailEnvelope } from "@/app/dashboard/mail/page";

function timeAgo(dateStr: string): string {
  const now = new Date();
  const d = new Date(dateStr);
  const diff = now.getTime() - d.getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return "şimdi";
  if (mins < 60) return `${mins}dk`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}sa`;
  const days = Math.floor(hrs / 24);
  if (days < 7) return `${days}g`;
  return d.toLocaleDateString("tr-TR", { day: "numeric", month: "short" });
}

function senderName(msg: MailEnvelope): string {
  const f = msg.from[0];
  return f?.name || f?.address || "Bilinmeyen";
}

export default function MessageList({ messages, loading, selectedUid, onSelect, onDelete }: {
  messages: MailEnvelope[];
  loading: boolean;
  selectedUid: number | null;
  onSelect: (uid: number) => void;
  onDelete: (uid: number) => void;
}) {
  if (loading) {
    return <div className="empty-state" style={{ padding: 40 }}><span className="spinner" style={{ width: 20, height: 20 }} /></div>;
  }

  if (messages.length === 0) {
    return (
      <div className="empty-state" style={{ padding: 40 }}>
        <div style={{ fontSize: 13, color: "var(--text-muted)" }}>Bu klasörde mail yok</div>
      </div>
    );
  }

  return (
    <div className="message-list-inner">
      {messages.map((m) => (
        <div
          key={m.uid}
          className={`message-row ${selectedUid === m.uid ? "selected" : ""} ${!m.seen ? "unread" : ""}`}
          onClick={() => onSelect(m.uid)}
        >
          <div className="message-avatar">
            {senderName(m)[0]?.toUpperCase() ?? "?"}
          </div>
          <div className="message-content">
            <div className="message-top">
              <span className="message-sender">{senderName(m)}</span>
              <span className="message-time">{timeAgo(m.date)}</span>
            </div>
            <div className="message-subject">{m.subject}</div>
          </div>
          {m.hasAttachments && <span className="message-attach" title="Ek var">📎</span>}
        </div>
      ))}
    </div>
  );
}
