"use client";
import type { MailFolder } from "@/app/[lang]/dashboard/mail/page";
import { useDictionary } from "@/components/DictionaryContext";

const FOLDER_ICONS: Record<string, string> = {
  "\\Inbox": "📥",
  "\\Sent": "📤",
  "\\Drafts": "📝",
  "\\Trash": "🗑️",
  "\\Junk": "⚠️",
  "\\Archive": "📦",
};

function getFolderIcon(folder: MailFolder): string {
  if (folder.specialUse && FOLDER_ICONS[folder.specialUse]) return FOLDER_ICONS[folder.specialUse];
  const lower = folder.path.toLowerCase();
  if (lower === "inbox") return "📥";
  if (lower.includes("sent")) return "📤";
  if (lower.includes("draft")) return "📝";
  if (lower.includes("trash")) return "🗑️";
  if (lower.includes("junk") || lower.includes("spam")) return "⚠️";
  if (lower.includes("archive")) return "📦";
  return "📁";
}

export default function FolderList({ folders, active, onSelect }: {
  folders: MailFolder[];
  active: string;
  onSelect: (path: string) => void;
}) {
  const dict = useDictionary();

  const getFolderLabel = (folder: MailFolder): string => {
    const name = folder.name || folder.path;
    const lower = name.toLowerCase();
    if (lower === "inbox") return dict.mailClient.inbox || "Inbox";
    if (lower === "sent") return dict.mailClient.sent || "Sent";
    if (lower === "drafts") return dict.mailClient.drafts || "Drafts";
    if (lower === "trash") return dict.mailClient.trash || "Trash";
    if (lower === "junk" || lower === "spam") return dict.mailClient.junk || "Junk";
    if (lower === "archive") return dict.mailClient.archive || "Archive";
    return name;
  };

  const sorted = [...folders].sort((a, b) => {
    if (a.path === "INBOX") return -1;
    if (b.path === "INBOX") return 1;
    if (a.specialUse && !b.specialUse) return -1;
    if (!a.specialUse && b.specialUse) return 1;
    return a.name.localeCompare(b.name);
  });

  return (
    <div className="folder-list">
      {sorted.map((f) => (
        <button
          key={f.path}
          className={`folder-item ${active === f.path ? "active" : ""}`}
          onClick={() => onSelect(f.path)}
        >
          <span className="folder-icon">{getFolderIcon(f)}</span>
          <span className="folder-name">{getFolderLabel(f)}</span>
          {f.unseen > 0 && <span className="folder-badge">{f.unseen}</span>}
        </button>
      ))}
    </div>
  );
}
