"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CardDetailView = CardDetailView;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const child_process_1 = require("child_process");
const ink_1 = require("ink");
const TrelloContext_1 = require("../state/TrelloContext");
const NavigationContext_1 = require("../state/NavigationContext");
const CARD_DETAIL_HELP = [
    { key: "e", desc: "Edit card name" },
    { key: "D", desc: "Edit description (multi-line)" },
    { key: "m", desc: "Move card to a different list" },
    { key: "d", desc: "Set / update due date" },
    { key: "l", desc: "Toggle labels on card" },
    { key: "M", desc: "Toggle members on card" },
    { key: "c", desc: "Toggle checklist items" },
    { key: "C", desc: "Create new checklist on card" },
    { key: "A", desc: "Add attachment (URL or URL | description)" },
    { key: "a", desc: "View all attachments" },
    { key: "o", desc: "Open card in browser" },
    { key: "x", desc: "Archive card" },
    { key: "Esc/Enter", desc: "Close card detail" },
];
function CardDetailView() {
    var _a;
    const { state: trelloState, archiveCard, moveCard, updateCard, loadCardDetails, } = (0, TrelloContext_1.useTrello)();
    const { state: navState, dispatch, config } = (0, NavigationContext_1.useNavigation)();
    const [showHelp, setShowHelp] = (0, react_1.useState)(false);
    const lists = trelloState.lists;
    const currentList = lists[navState.selectedListIndex];
    const cards = currentList
        ? trelloState.cardsByList[currentList.id] || []
        : [];
    const card = cards[navState.selectedCardIndex];
    // Load checklists and attachments when entering card detail view
    (0, react_1.useEffect)(() => {
        if (card && navState.view === "card-detail") {
            loadCardDetails(card.id);
        }
    }, [card === null || card === void 0 ? void 0 : card.id, navState.view]);
    // Resolve member names from cache
    const memberNames = (0, react_1.useMemo)(() => {
        if (!card || !card.idMembers.length)
            return [];
        return card.idMembers.map((id) => {
            const member = trelloState.members.find((m) => m.id === id);
            return member ? member.fullName : id;
        });
    }, [card, trelloState.members]);
    (0, ink_1.useInput)((input, key) => {
        // Help screen takes priority
        if (showHelp) {
            if (key.escape || input === "?" || input === "q") {
                setShowHelp(false);
            }
            return;
        }
        if (input === "?") {
            setShowHelp(true);
            return;
        }
        if (key.escape || key.return) {
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            return;
        }
        // Edit card - switch to board view in edit mode
        if (input === "e" && card) {
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            dispatch({ type: "SET_MODE", mode: "edit-card", originView: "card-detail" });
            return;
        }
        // Move card - switch to board view in move mode
        if (input === "m" && card) {
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            dispatch({ type: "SET_MODE", mode: "move-card", originView: "card-detail" });
            return;
        }
        // Set due date - switch to board view in due mode
        if (input === "d" && card) {
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            dispatch({ type: "SET_MODE", mode: "set-due", originView: "card-detail" });
            return;
        }
        // Toggle labels - switch to board view in toggle-label mode
        if (input === "l" && card) {
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            dispatch({ type: "SET_MODE", mode: "toggle-label", originView: "card-detail" });
            return;
        }
        // Toggle members - switch to board view in toggle-member mode
        if (input === "M" && card) {
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            dispatch({ type: "SET_MODE", mode: "toggle-member", originView: "card-detail" });
            return;
        }
        // Edit description - switch to board view in edit-desc mode
        if (input === "D" && card) {
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            dispatch({ type: "SET_MODE", mode: "edit-desc", originView: "card-detail" });
            return;
        }
        // Open card in browser
        if (input === "o" && card) {
            openUrl(card.url);
            dispatch({ type: "SET_STATUS", message: `Opening in browser...` });
            setTimeout(() => dispatch({ type: "SET_STATUS", message: null }), 3000);
            return;
        }
        // Toggle checklist items - switch to board view in toggle-checklist mode
        if (input === "c" && card) {
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            dispatch({ type: "SET_MODE", mode: "toggle-checklist", originView: "card-detail" });
            return;
        }
        // Add checklist - switch to board view in add-checklist mode
        if (input === "C" && card) {
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            dispatch({ type: "SET_MODE", mode: "add-checklist", originView: "card-detail" });
            return;
        }
        // Add attachment - switch to board view in add-attachment mode
        if (input === "A" && card) {
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            dispatch({ type: "SET_MODE", mode: "add-attachment", originView: "card-detail" });
            return;
        }
        // View all attachments - switch to board view in view-attachments mode
        if (input === "a" && card) {
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            dispatch({ type: "SET_MODE", mode: "view-attachments", originView: "card-detail" });
            return;
        }
        if (input === "x" && card && currentList) {
            archiveCard(card.id, currentList.id);
            dispatch({ type: "SET_STATUS", message: `Archived "${card.name}"` });
            setTimeout(() => dispatch({ type: "SET_STATUS", message: null }), 3000);
            dispatch({ type: "SET_VIEW", view: "board", preserveSelection: true });
            return;
        }
    }, { isActive: navState.view === "card-detail" });
    if (!card) {
        return ((0, jsx_runtime_1.jsx)(ink_1.Box, { paddingX: 2, paddingY: 1, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.muted, children: "No card selected" }) }));
    }
    // Help overlay for card detail
    if (showHelp) {
        return ((0, jsx_runtime_1.jsxs)(ink_1.Box, { flexDirection: "column", borderStyle: "round", borderColor: config.theme.primary, paddingX: 2, paddingY: 1, marginX: 2, children: [(0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, color: config.theme.primary, children: "Card Detail Shortcuts" }), (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.muted, children: "Press ? or Esc to close" }), (0, jsx_runtime_1.jsx)(ink_1.Text, { children: " " }), CARD_DETAIL_HELP.map((item) => ((0, jsx_runtime_1.jsxs)(ink_1.Box, { children: [(0, jsx_runtime_1.jsx)(ink_1.Box, { width: 14, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.primary, bold: true, children: item.key }) }), (0, jsx_runtime_1.jsx)(ink_1.Text, { children: item.desc })] }, item.key)))] }));
    }
    const dueInfo = getDueInfo(card.due);
    return ((0, jsx_runtime_1.jsxs)(ink_1.Box, { flexDirection: "column", borderStyle: "round", borderColor: config.theme.primary, paddingX: 2, paddingY: 1, marginX: 2, children: [(0, jsx_runtime_1.jsxs)(ink_1.Text, { children: [(0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.secondary, children: ((_a = trelloState.currentBoard) === null || _a === void 0 ? void 0 : _a.name) || "Unknown" }), (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.muted, children: " / " }), (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.secondary, children: (currentList === null || currentList === void 0 ? void 0 : currentList.name) || "Unknown" }), (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.muted, children: " / " }), (0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, color: config.theme.primary, children: card.name })] }), (0, jsx_runtime_1.jsx)(ink_1.Text, { children: " " }), (0, jsx_runtime_1.jsxs)(ink_1.Box, { flexDirection: "column", children: [(0, jsx_runtime_1.jsxs)(ink_1.Box, { children: [(0, jsx_runtime_1.jsx)(ink_1.Box, { width: 12, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, children: "ID:" }) }), (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.secondary, children: card.id })] }), (0, jsx_runtime_1.jsxs)(ink_1.Box, { children: [(0, jsx_runtime_1.jsx)(ink_1.Box, { width: 12, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, children: "URL:" }) }), (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.secondary, children: card.url })] }), (0, jsx_runtime_1.jsx)(ink_1.Text, { children: " " }), card.labels.length > 0 && ((0, jsx_runtime_1.jsxs)(ink_1.Box, { children: [(0, jsx_runtime_1.jsx)(ink_1.Box, { width: 12, children: (0, jsx_runtime_1.jsxs)(ink_1.Text, { children: [(0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, children: "Labels:" }), (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.primary, children: " [l]" })] }) }), (0, jsx_runtime_1.jsx)(ink_1.Box, { children: card.labels.map((label) => ((0, jsx_runtime_1.jsxs)(ink_1.Text, { color: LABEL_COLORS[label.color] || config.theme.muted, children: [" ", "#", label.name || ""] }, label.id))) })] })), memberNames.length > 0 && ((0, jsx_runtime_1.jsxs)(ink_1.Box, { children: [(0, jsx_runtime_1.jsx)(ink_1.Box, { width: 12, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, children: "Members:" }) }), (0, jsx_runtime_1.jsx)(ink_1.Text, { children: memberNames.join(", ") })] })), dueInfo && ((0, jsx_runtime_1.jsxs)(ink_1.Box, { children: [(0, jsx_runtime_1.jsx)(ink_1.Box, { width: 12, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, children: "Due:" }) }), (0, jsx_runtime_1.jsxs)(ink_1.Text, { color: dueInfo.color, children: [dueInfo.icon, " ", dueInfo.fullText] })] })), card.desc ? ((0, jsx_runtime_1.jsxs)(ink_1.Box, { flexDirection: "column", marginTop: 1, children: [(0, jsx_runtime_1.jsxs)(ink_1.Text, { children: [(0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, children: "Description:" }), (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.primary, children: " [D]" })] }), (0, jsx_runtime_1.jsx)(ink_1.Box, { paddingLeft: 2, marginTop: 0, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { wrap: "wrap", children: card.desc }) })] })) : null, card.checklists && card.checklists.length > 0 && ((0, jsx_runtime_1.jsxs)(ink_1.Box, { flexDirection: "column", marginTop: 1, children: [(0, jsx_runtime_1.jsxs)(ink_1.Text, { children: [(0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, children: "Checklists:" }), (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.primary, children: " [c]" })] }), card.checklists.length === 1 ? (
                            // Single checklist — show items (max 5)
                            card.checklists.map((checklist) => {
                                const total = checklist.checkItems.length;
                                const done = checklist.checkItems.filter((ci) => ci.state === "complete").length;
                                const sorted = checklist.checkItems.sort((a, b) => a.pos - b.pos);
                                const shown = sorted.slice(0, 5);
                                const remaining = sorted.length - shown.length;
                                return ((0, jsx_runtime_1.jsxs)(ink_1.Box, { flexDirection: "column", paddingLeft: 2, children: [(0, jsx_runtime_1.jsxs)(ink_1.Text, { bold: true, color: config.theme.secondary, children: [checklist.name, " (", done, "/", total, ")"] }), shown.map((item) => ((0, jsx_runtime_1.jsxs)(ink_1.Box, { paddingLeft: 2, children: [(0, jsx_runtime_1.jsx)(ink_1.Text, { color: item.state === "complete"
                                                        ? config.theme.accent
                                                        : config.theme.muted, children: item.state === "complete" ? "[x] " : "[ ] " }), (0, jsx_runtime_1.jsx)(ink_1.Text, { strikethrough: item.state === "complete", color: item.state === "complete"
                                                        ? config.theme.muted
                                                        : undefined, children: item.name })] }, item.id))), remaining > 0 && ((0, jsx_runtime_1.jsx)(ink_1.Box, { paddingLeft: 2, children: (0, jsx_runtime_1.jsxs)(ink_1.Text, { color: config.theme.muted, italic: true, children: ["... and ", remaining, " more (press c to view all)"] }) }))] }, checklist.id));
                            })) : (
                            // Multiple checklists — title and count only
                            card.checklists.map((checklist) => {
                                const total = checklist.checkItems.length;
                                const done = checklist.checkItems.filter((ci) => ci.state === "complete").length;
                                return ((0, jsx_runtime_1.jsxs)(ink_1.Box, { paddingLeft: 2, children: [(0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, color: config.theme.secondary, children: checklist.name }), (0, jsx_runtime_1.jsxs)(ink_1.Text, { color: config.theme.muted, children: [" (", done, "/", total, ")"] })] }, checklist.id));
                            }))] })), card.attachments && card.attachments.length > 0 && ((0, jsx_runtime_1.jsxs)(ink_1.Box, { marginTop: 1, children: [(0, jsx_runtime_1.jsx)(ink_1.Text, { bold: true, children: "Attachments:" }), (0, jsx_runtime_1.jsxs)(ink_1.Text, { color: config.theme.muted, children: [" ", card.attachments.length] }), (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.primary, children: " [a]" })] }))] }), (0, jsx_runtime_1.jsx)(ink_1.Text, { children: " " }), (0, jsx_runtime_1.jsx)(ink_1.Box, { children: (0, jsx_runtime_1.jsx)(ink_1.Text, { color: config.theme.muted, children: "[Esc] Close  [e] Edit  [l] Labels  [d] Due date  [o] Open  [?] Help" }) })] }));
}
const LABEL_COLORS = {
    green: "green",
    yellow: "yellow",
    orange: "#FFA500",
    red: "red",
    purple: "magenta",
    blue: "blue",
    sky: "cyan",
    lime: "greenBright",
    pink: "magentaBright",
    black: "white",
};
function getDueInfo(due) {
    if (!due)
        return null;
    const dueDate = new Date(due);
    const now = new Date();
    const diffMs = dueDate.getTime() - now.getTime();
    const diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));
    const formatted = dueDate.toLocaleDateString("en-US", {
        weekday: "short",
        month: "short",
        day: "numeric",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
    });
    if (diffDays < 0) {
        return {
            fullText: `${formatted} (Overdue by ${Math.abs(diffDays)} days)`,
            color: "red",
            icon: "!!",
        };
    }
    if (diffDays === 0) {
        return { fullText: `${formatted} (Today)`, color: "yellow", icon: ">>" };
    }
    if (diffDays === 1) {
        return {
            fullText: `${formatted} (Tomorrow)`,
            color: "yellow",
            icon: ">>",
        };
    }
    if (diffDays <= 7) {
        return {
            fullText: `${formatted} (${diffDays} days)`,
            color: "green",
            icon: "..",
        };
    }
    return { fullText: formatted, color: "gray", icon: ".." };
}
function openUrl(url) {
    const platform = process.platform;
    const cmd = platform === "darwin" ? "open" :
        platform === "win32" ? "start" :
            "xdg-open";
    (0, child_process_1.exec)(`${cmd} ${JSON.stringify(url)}`);
}
