import { Colors, Typography } from "tokens.slint";

export struct NoteDisplayData {
    date: string,
    content: string,
    author-display: string,
    relative-time: string,
}

export struct ItemSquareData {
    item-id: string,
    display-name: string,
    initials: string,
    bg-color-index: int,
    has-image: bool,
    image-url: string,
    image: image,           // Loaded from local product image cache by Rust (D-08, SC19)
    is-dimmed: bool,   // true when unit was unassigned from this card (D-08)
    product-name: string,   // parent product name for display (G2-03)
    serial-id: string,      // full serial number; empty for parent product adds (G2-03)
    serial-label: string,   // truncated SN for display below square (first2...last4)
}

export component RecipientCard inherits Rectangle {
    in property <string> recipient-name: "Recipient";
    in property <string> status-pill: "Unknown";
    in property <string> status-date: "";
    in property <string> missing-label: "";
    in property <string> stale-label: "STALE";
    in property <bool> is-stale: false;
    in property <bool> show-refresh: false;
    in property <bool> refresh-disabled: false;
    in property <string> refresh-label: "Refresh";
    in property <string> retry-label: "Retry";
    in property <bool> show-error: false;
    in property <bool> refresh-error: false;
    // Archive state: 0=Active, 1=ToBeArchived, 2=Archived
    in property <int> archive-state: 0;

    // Discord / contact enrichment properties
    in property <string> discord-user-id: "";
    in property <string> contact-secondary: "";
    in property <string> recipient-initial: "?";
    in property <color> purpose-color: #ffffff;
    in property <string> purpose-label: "";
    in property <string> shopify-customer-url: "";
    in property <string> shopify-order-url: "";
    in property <string> github-issue-url: "";
    in property <string> email: "";

    in-out property <string> note-draft: "";

    // Remove confirmation state: true = showing "Confirm?" prompt
    in property <bool> remove-confirming: false;

    // Unassigned card state
    in property <bool> is-unassigned: false;
    in property <string> unassigned-customer-name: "";
    callback pick-recipient-clicked();

    // Item squares for the redesigned item area
    in property <[ItemSquareData]> item-squares: [];
    in property <string> item-display-label: "";
    in property <int> card-index: 0;
    callback remove-single-item(int);  // item-square-index
    callback item-square-clicked(int, string);  // card_index, item_id

    callback add-item-clicked();
    callback remove-item-clicked();
    callback confirm-remove-clicked();
    callback archive-clicked();
    callback unarchive-clicked();
    callback archive-now-clicked();

    // Communication and external link callbacks
    callback open-discord-dm();
    callback copy-email();
    callback open-shopify-customer();
    callback open-shopify-order();
    callback open-github-issue();
    callback refresh-clicked();
    // Computed visibility helpers for menu sections
    property <bool> has-communication-items: root.discord-user-id != "" || root.email != "";
    property <bool> has-external-link-items: root.shopify-customer-url != "" || root.shopify-order-url != "" || root.github-issue-url != "";

    // Discord username (Phase 16.1) — display only on card face; editing moved to recipient-detail sidebar (D-16)
    in property <string> discord-username: "";

    // Notes popover state (Phase 20.1.1 Plan 04)
    // note-draft already declared above; reused for composer draft
    in property <[NoteDisplayData]> notes: [];
    in-out property <bool> composer-expanded: false;
    callback on-post-note(string);            // (note-text)
    callback on-notes-popover-opened();       // fires on popover open

    // Start Return flow (Phase 19)
    callback start-return-confirmed();

    // Partial return warning (Phase 19, D-13, D-14)
    in property <bool> partial-return-warning: false;
    callback view-warning-clicked();

    // Avatar image (Phase 16.1)
    in property <image> avatar-image;
    in property <bool> has-avatar-image: false;

    // Recipient ID for callbacks
    in property <string> recipient-id: "";
    callback card-name-clicked(string);    // recipient-id — opens recipient detail sidebar (D-19)

    // Active discovery mode (0=StatusUpdated, 1=ShipDate, 2=Recipient, 3=ProductShipped)
    in property <int> active-mode-index: 0;

    border-radius: 10px;
    background: Colors.surface;
    clip: true;
    // Dimmed opacity for TBA (1) and Archived (2) cards
    opacity: archive-state > 0 ? 0.5 : 1.0;

    // D-11: passive card-level hover detector — placed FIRST so later siblings win clicks
    // has-hover is true whenever the cursor is anywhere over the card
    card-hover-zone := TouchArea {
        x: 0px;
        y: 0px;
        width: parent.width;
        height: parent.height;
        // no clicked handler — passive, only provides has-hover
    }

    // Recipient name row — absolute overlay covering top 38px
    // Clicking the name area opens the recipient detail sidebar (D-19).
    name-area := TouchArea {
        x: 0px;
        y: 0px;
        width: parent.width;
        height: 38px;
        mouse-cursor: pointer;

        clicked => {
            root.card-name-clicked(root.recipient-id);
        }
    }

    // Info icon button — absolute overlay, right-aligned in name row (left of dots button)
    info-icon-rect := Rectangle {
        x: parent.width - 54px;
        y: 8px;
        width: 20px;
        height: 20px;
        border-radius: 10px;
        background: info-hover.has-hover ? Colors.border-default : transparent;
        border-width: 1px;
        border-color: info-hover.has-hover ? Colors.text-muted : Colors.border-muted;

        Text {
            text: "i";
            width: parent.width;
            height: parent.height;
            color: Colors.text-dim;
            font-size: Typography.size-sm;
            font-italic: true;
            horizontal-alignment: center;
            vertical-alignment: center;
        }

        info-hover := TouchArea {
            mouse-cursor: pointer;
            clicked => {
                notes-popup.show();
                root.on-notes-popover-opened();
            }
        }
    }

    // Three-dots menu button — absolute overlay, top right corner
    Rectangle {
        x: parent.width - 30px;
        y: 8px;
        width: 20px;
        height: 20px;
        border-radius: 10px;
        background: root.refresh-error ? (dots-touch.has-hover ? #5a3818 : #4a2810) : (dots-touch.has-hover ? Colors.border-default : transparent);
        border-width: 1px;
        border-color: root.refresh-error ? Colors.warning : (dots-touch.has-hover ? Colors.text-muted : Colors.border-muted);

        Text {
            text: "...";
            width: parent.width;
            height: parent.height;
            horizontal-alignment: center;
            vertical-alignment: center;
            color: Colors.text-muted;
            font-size: Typography.size-sm;
        }

        dots-touch := TouchArea {
            mouse-cursor: pointer;
            clicked => {
                card-menu.show();
            }
        }
    }

    // Stale badge — absolute overlay, right-aligned on status row
    if root.is-stale : Rectangle {
        x: parent.width - 64px;
        y: 40px;
        width: 50px;
        height: 18px;
        border-radius: 9px;
        background: #3a2a00;
        Text {
            text: root.stale-label;
            width: parent.width;
            height: parent.height;
            horizontal-alignment: center;
            vertical-alignment: center;
            color: Colors.warning;
            font-size: Typography.size-xs;
        }
    }

    // Error / Retry button — absolute overlay
    if root.show-error : Rectangle {
        x: parent.width - 82px;
        y: 36px;
        width: 66px;
        height: 18px;
        border-radius: 9px;
        background: #3a1a1a;
        Text {
            text: root.retry-label;
            width: parent.width;
            height: parent.height;
            horizontal-alignment: center;
            vertical-alignment: center;
            color: #ef5350;
            font-size: Typography.size-xs;
        }
        TouchArea {
            mouse-cursor: pointer;
            clicked => {
                root.refresh-clicked();
            }
        }
    }

    // Card body — VerticalLayout for natural content-driven height
    VerticalLayout {
        padding-left: 12px;
        padding-right: 12px;
        padding-top: 8px;
        padding-bottom: 4px;
        spacing: 4px;

        // Contact secondary text — mode-dependent (@handle / email / status date)
        // 0=StatusUpdated: status date, 1=ShipDate: status date, 2=Recipient: email, 3=ProductShipped: status date
        property <string> mode-secondary: {
            if (root.active-mode-index == 2) {
                root.email != "" ? root.email : root.contact-secondary
            } else {
                root.status-date != "" ? root.status-date : root.contact-secondary
            }
        }

        // Row 1: Avatar + Name + Contact (horizontal)
        HorizontalLayout {
            spacing: 6px;
            alignment: start;

            // Avatar ring wrapper — 44x44 outer ring, 40x40 inner circle (D-01)
            // Unassigned cards: ring matches card bg, placeholder uses warning amber
            Rectangle {
                width: 44px;
                height: 44px;
                border-radius: 22px;
                background: root.is-unassigned ? Colors.background : root.purpose-color;

                avatar-touch := TouchArea {}

                // Inner avatar circle
                Rectangle {
                    x: 2px;
                    y: 2px;
                    width: 40px;
                    height: 40px;
                    border-radius: 20px;
                    background: root.is-unassigned ? #3a2a10 : Colors.avatar-bg;
                    clip: true;

                    // Real avatar image — shown when has-avatar-image is true
                    if root.has-avatar-image : Image {
                        width: 40px;
                        height: 40px;
                        source: root.avatar-image;
                        image-fit: cover;
                    }

                    // Initials fallback — shown when no avatar image
                    if !root.has-avatar-image : Text {
                        text: root.recipient-initial;
                        font-size: Typography.size-md;
                        font-weight: 700;
                        color: root.is-unassigned ? Colors.warning : Colors.avatar-text;
                        horizontal-alignment: center;
                        vertical-alignment: center;
                    }
                }
            }

            // Name column: recipient name + contact secondary stacked vertically
            VerticalLayout {
                spacing: 1px;
                alignment: center;
                horizontal-stretch: 1;

                // Normal recipient name (when assigned) — D-02: grown from size-md to 15px
                if !root.is-unassigned : Text {
                    text: root.recipient-name;
                    color: Colors.text-primary;
                    font-size: 15px;
                    overflow: elide;
                    horizontal-stretch: 1;
                }

                // Unassigned customer name — italic warning color — D-02: grown from size-md to 15px
                if root.is-unassigned : Text {
                    text: root.unassigned-customer-name;
                    color: Colors.warning;
                    font-size: 15px;
                    font-italic: true;
                    overflow: elide;
                    horizontal-stretch: 1;
                }

                // Contact secondary text directly under username (G2-03) — D-02: grown from size-xs to size-sm
                if mode-secondary != "" : Text {
                    text: mode-secondary;
                    color: Colors.text-dim;
                    font-size: Typography.size-sm;
                    overflow: elide;
                }
            }
        }

        // Row 2: Status pill + date
        HorizontalLayout {
            spacing: 6px;
            alignment: start;
            height: 22px;

            // Status pill — non-interactive display, dynamic width
            Rectangle {
                width: status-pill-text.preferred-width + 16px;
                height: 22px;
                border-radius: 11px;
                background: root.status-pill == "Packing" ? Colors.serial-state-packing
                          : root.status-pill == "In Transit" ? Colors.serial-state-in-transit
                          : root.status-pill == "Delivered" ? Colors.serial-state-delivered
                          : root.status-pill == "Return Created" ? Colors.serial-state-return-initiated
                          : root.status-pill == "Return Underway" ? Colors.serial-state-return-in-transit
                          : root.status-pill == "Returned" ? Colors.serial-state-returned
                          : Colors.avatar-bg;

                HorizontalLayout {
                    alignment: center;
                    padding-left: 8px;
                    padding-right: 8px;
                    status-pill-text := Text {
                        text: root.status-pill;
                        color: root.status-pill == "Packing" ? #7edcdc
                             : root.status-pill == "In Transit" ? #dcc070
                             : root.status-pill == "Delivered" ? #70dc70
                             : root.status-pill == "Return Created" ? #dcaa70
                             : root.status-pill == "Return Underway" ? #dca060
                             : root.status-pill == "Returned" ? #c080dc
                             : Colors.avatar-text;
                        font-size: Typography.size-sm;
                        vertical-alignment: center;
                    }
                }
            }

            // Status date
            Text {
                text: root.status-date;
                color: Colors.text-dim;
                font-size: Typography.size-sm;
                vertical-alignment: center;
                horizontal-stretch: 1;
            }
        }

        // Row 3: Item display label
        Text {
            height: 16px;
            text: root.item-display-label != "" ? root.item-display-label : "No items added";
            font-size: Typography.size-sm;
            color: root.item-display-label != "" ? Colors.text-muted : Colors.text-dim;
            overflow: elide;
        }

        // Row 4: Item squares area (G2-03: enlarged to fit product name + serial subtext; D-15: grown to 80px after Row 5 removal)
        Rectangle {
            height: 80px;

            // Item squares — each 58px wide with stride=58px to fit text labels below (D-11: scaled from 52px)
            // Unclipped wrapper so X button and hover label can overflow
            for sq[sq-index] in root.item-squares : Rectangle {
                x: sq-index * 58px;
                y: 0px;
                width: 58px;
                height: 80px;
                background: transparent;

                // Clipped inner square for image/initials — 52x52 centered in 80px row (D-11)
                Rectangle {
                    x: 3px;
                    y: 14px;                // D-11: centered in 80px row: (80 - 52) / 2 = 14
                    width: 52px;            // D-11: scaled from 44px
                    height: 52px;           // D-11: scaled from 44px
                    border-radius: 7px;     // D-11: scaled from 6px
                    clip: true;
                    opacity: sq.is-dimmed ? 0.4 : 1.0;

                    background:
                        sq.bg-color-index == 0 ? #2a3560 :
                        sq.bg-color-index == 1 ? #3a2a50 :
                        sq.bg-color-index == 2 ? #2a4a3a :
                        sq.bg-color-index == 3 ? #4a3a2a :
                        sq.bg-color-index == 4 ? #2a3a4a :
                        sq.bg-color-index == 5 ? #4a2a3a :
                        sq.bg-color-index == 6 ? #3a4a2a :
                        /* 7 */ #2a4a4a;

                    if !sq.has-image : Text {
                        text: sq.initials;
                        width: parent.width;
                        height: parent.height;
                        horizontal-alignment: center;
                        vertical-alignment: center;
                        color: Colors.avatar-text;
                        font-size: Typography.size-md;
                        font-weight: 700;
                    }

                    // D-06/SC19: product image letterboxed with contain fit when available
                    if sq.has-image : Image {
                        source: sq.image;
                        width: parent.width;
                        height: parent.height;
                        image-fit: contain;
                    }
                }

                // Label below the square: SN for units (larger text), product name for products
                if sq.serial-label != "" : Text {
                    x: 0px;
                    y: 68px;
                    width: 58px;
                    text: sq.serial-label;
                    font-size: Typography.size-sm;
                    color: Colors.text-muted;
                    horizontal-alignment: center;
                    overflow: elide;
                }
                if sq.serial-label == "" && sq.product-name != "" : Text {
                    x: 0px;
                    y: 68px;
                    width: 58px;
                    text: sq.product-name;
                    font-size: Typography.size-sm;
                    color: Colors.text-muted;
                    horizontal-alignment: center;
                    overflow: elide;
                }

                sq-touch := TouchArea {
                    width: 52px;            // D-11: match scaled inner square
                    height: 80px;
                    mouse-cursor: pointer;
                    clicked => {
                        root.item-square-clicked(root.card-index, sq.item-id);
                    }
                }

                // Hover label — shows full product name + serial on hover
                // Uses opaque background to fully cover the default item-display-label text above
                if sq-touch.has-hover : Rectangle {
                    x: 0px - sq-index * 58px;  // D-11: updated stride 52→58px
                    y: -20px;
                    width: root.width - 28px;
                    height: 16px;
                    background: root.background;

                    Text {
                        width: parent.width;
                        height: parent.height;
                        text: sq.serial-id != ""
                            ? sq.product-name + " / " + sq.serial-id
                            : sq.product-name;
                        font-size: Typography.size-sm;
                        color: Colors.text-primary;
                        overflow: elide;
                    }
                }
            }

            // Product-add button — always rendered, opacity-controlled to avoid flicker.
            // Using conditional rendering (`if has-hover`) causes a feedback loop where
            // the inner TouchArea steals hover from the outer zone, toggling visibility.
            // Always-present with opacity avoids this entirely.
            Rectangle {
                x: root.item-squares.length * 58px + 8px;  // 8px margin after last product
                y: 0px;
                width: 52px;
                height: 80px;
                background: transparent;
                opacity: card-hover-zone.has-hover || add-btn-touch.has-hover ? 1.0 : 0.0;

                // Inner circle
                Rectangle {
                    x: 0px;
                    y: 14px;
                    width: 52px;
                    height: 52px;
                    border-radius: 26px;
                    background: add-btn-touch.has-hover ? #1a3a1a : Colors.surface-popup;

                    Text {
                        text: "+";
                        width: parent.width;
                        height: parent.height;
                        horizontal-alignment: center;
                        vertical-alignment: center;
                        color: Colors.success;
                        font-size: 28px;
                    }

                    add-btn-touch := TouchArea {
                        mouse-cursor: pointer;
                        clicked => {
                            root.add-item-clicked();
                        }
                    }
                }
            }
        }

    }

    // Partial return warning marker (D-13) — yellow badge top-left of dots button
    if root.partial-return-warning : Rectangle {
        x: parent.width - 54px;
        y: 32px;
        width: 20px;
        height: 20px;
        border-radius: 10px;
        background: #d4a017;  // warning yellow

        Text {
            text: "\u{26A0}";
            width: parent.width;
            height: parent.height;
            font-size: 11px;
            color: #ffffff;
            horizontal-alignment: center;
            vertical-alignment: center;
        }
    }

    // Card action popup menu
    card-menu := PopupWindow {
        x: parent.width - 170px;
        y: 34px;
        width: 160px;

        Rectangle {
            background: Colors.surface-popup;
            border-radius: 6px;
            border-width: 1px;
            border-color: Colors.border-muted;

            VerticalLayout {
                padding: 4px;

                // --- Section 0: Unassigned action (Pick Recipient) ---

                // Pick Recipient — warning color, visible only for unassigned cards
                if root.is-unassigned : Rectangle {
                    height: 28px;
                    border-radius: 4px;
                    background: pick-touch.has-hover ? Colors.border-default : transparent;
                    Text {
                        text: "Pick Recipient";
                        x: 10px;
                        font-size: Typography.size-sm;
                        color: Colors.warning;
                        vertical-alignment: center;
                    }
                    pick-touch := TouchArea {
                        mouse-cursor: pointer;
                        clicked => {
                            root.pick-recipient-clicked();
                            card-menu.close();
                        }
                    }
                }

                // Separator after Pick Recipient when unassigned
                if root.is-unassigned : Rectangle {
                    height: 11px;
                    background: transparent;
                    Rectangle {
                        y: 5px;
                        width: parent.width;
                        height: 1px;
                        background: Colors.border-muted;
                    }
                }

                // --- Section 1: Communication ---

                // Open Discord DM — only when discord-user-id is set
                if root.discord-user-id != "" : Rectangle {
                    height: 28px;
                    border-radius: 4px;
                    background: dm-touch.has-hover ? Colors.border-default : transparent;
                    Text {
                        text: "Open Discord DM";
                        x: 10px;
                        font-size: Typography.size-sm;
                        color: Colors.avatar-text;
                        vertical-alignment: center;
                    }
                    dm-touch := TouchArea {
                        mouse-cursor: pointer;
                        clicked => {
                            root.open-discord-dm();
                            card-menu.close();
                        }
                    }
                }

                // Copy Email — only when email is set
                if root.email != "" : Rectangle {
                    height: 28px;
                    border-radius: 4px;
                    background: email-touch.has-hover ? Colors.border-default : transparent;
                    Text {
                        text: "Copy Email";
                        x: 10px;
                        font-size: Typography.size-sm;
                        color: Colors.avatar-text;
                        vertical-alignment: center;
                    }
                    email-touch := TouchArea {
                        mouse-cursor: pointer;
                        clicked => {
                            root.copy-email();
                            card-menu.close();
                        }
                    }
                }

                // Separator between Communication and External Links (5px margin above/below)
                if root.has-communication-items && root.has-external-link-items : Rectangle {
                    height: 11px;
                    background: transparent;
                    Rectangle {
                        y: 5px;
                        width: parent.width;
                        height: 1px;
                        background: Colors.border-muted;
                    }
                }

                // --- Section 2: External Links ---

                if root.shopify-customer-url != "" : Rectangle {
                    height: 28px;
                    border-radius: 4px;
                    background: cust-touch.has-hover ? Colors.border-default : transparent;
                    Text {
                        text: "Open Profile";
                        x: 10px;
                        font-size: Typography.size-sm;
                        color: Colors.text-secondary;
                        vertical-alignment: center;
                    }
                    cust-touch := TouchArea {
                        mouse-cursor: pointer;
                        clicked => {
                            root.open-shopify-customer();
                            card-menu.close();
                        }
                    }
                }

                if root.shopify-order-url != "" : Rectangle {
                    height: 28px;
                    border-radius: 4px;
                    background: order-touch.has-hover ? Colors.border-default : transparent;
                    Text {
                        text: "Open Order";
                        x: 10px;
                        font-size: Typography.size-sm;
                        color: Colors.text-secondary;
                        vertical-alignment: center;
                    }
                    order-touch := TouchArea {
                        mouse-cursor: pointer;
                        clicked => {
                            root.open-shopify-order();
                            card-menu.close();
                        }
                    }
                }

                if root.github-issue-url != "" : Rectangle {
                    height: 28px;
                    border-radius: 4px;
                    background: gh-touch.has-hover ? Colors.border-default : transparent;
                    Text {
                        text: "Open GH Issue";
                        x: 10px;
                        font-size: Typography.size-sm;
                        color: Colors.text-secondary;
                        vertical-alignment: center;
                    }
                    gh-touch := TouchArea {
                        mouse-cursor: pointer;
                        clicked => {
                            root.open-github-issue();
                            card-menu.close();
                        }
                    }
                }

                // Start Return — only for Delivered cards with a Shopify order URL
                if root.status-pill == "Delivered" && root.shopify-order-url != "" : Rectangle {
                    height: 28px;
                    border-radius: 4px;
                    background: start-return-touch.has-hover ? Colors.border-default : transparent;
                    Text {
                        text: "Start Return";
                        x: 10px;
                        font-size: Typography.size-sm;
                        color: Colors.warning;
                        vertical-alignment: center;
                    }
                    start-return-touch := TouchArea {
                        mouse-cursor: pointer;
                        clicked => {
                            root.start-return-confirmed();
                            card-menu.close();
                        }
                    }
                }

                // View Warning — only when partial return warning is active (D-14)
                if root.partial-return-warning : Rectangle {
                    height: 28px;
                    border-radius: 4px;
                    background: view-warning-touch.has-hover ? Colors.border-default : transparent;
                    Text {
                        text: "View Warning";
                        x: 10px;
                        font-size: Typography.size-sm;
                        color: #d4a017;  // warning yellow
                        vertical-alignment: center;
                    }
                    view-warning-touch := TouchArea {
                        mouse-cursor: pointer;
                        clicked => {
                            root.view-warning-clicked();
                            card-menu.close();
                        }
                    }
                }

                // Separator before Card Actions (5px margin above/below)
                if root.has-communication-items || root.has-external-link-items : Rectangle {
                    height: 11px;
                    background: transparent;
                    Rectangle {
                        y: 5px;
                        width: parent.width;
                        height: 1px;
                        background: Colors.border-muted;
                    }
                }

                // --- Section 3: Card Actions ---

                // Refresh option
                if root.show-refresh : Rectangle {
                    height: 28px;
                    border-radius: 4px;
                    background: refresh-menu-touch.has-hover ? Colors.border-default : transparent;

                    Text {
                        text: root.refresh-error ? "Refresh failed - retry" : root.refresh-label;
                        x: 10px;
                        font-size: Typography.size-sm;
                        color: root.refresh-disabled ? #555555 : Colors.avatar-text;
                        vertical-alignment: center;
                    }

                    refresh-menu-touch := TouchArea {
                        mouse-cursor: root.refresh-disabled ? default : pointer;
                        clicked => {
                            if !root.refresh-disabled {
                                root.refresh-clicked();
                            }
                            card-menu.close();
                        }
                    }
                }

                // Archive / Archive Now / Unarchive option
                Rectangle {
                    height: 28px;
                    border-radius: 4px;
                    background: archive-menu-touch.has-hover ? Colors.border-default : transparent;

                    Text {
                        text: root.archive-state == 0 ? "Archive" : root.archive-state == 1 ? "Archive Now" : "Unarchive";
                        x: 10px;
                        font-size: Typography.size-sm;
                        color: root.archive-state == 2 ? Colors.text-muted : Colors.warning;
                        vertical-alignment: center;
                    }

                    archive-menu-touch := TouchArea {
                        mouse-cursor: pointer;
                        clicked => {
                            if root.archive-state == 0 {
                                root.archive-clicked();
                            } else if root.archive-state == 1 {
                                root.archive-now-clicked();
                            } else {
                                root.unarchive-clicked();
                            }
                            card-menu.close();
                        }
                    }
                }
            }
        }
    }

    // Purpose tooltip — top-level overlay for correct z-order (renders above all card content)
    if avatar-touch.has-hover && root.purpose-label != "" : Rectangle {
        x: 12px;
        y: 42px;
        height: 22px;
        width: tooltip-text.preferred-width + 12px;
        border-radius: 4px;
        background: Colors.surface-popup;
        border-width: 1px;
        border-color: Colors.border-muted;

        tooltip-text := Text {
            text: root.purpose-label;
            font-size: Typography.size-xs;
            color: Colors.text-primary;
            horizontal-alignment: center;
            vertical-alignment: center;
        }
    }

    // Notes history popover — anchored near (i) button (Phase 20.1.1 Plan 04)
    // Token substitutions: surface-popup exists; accent-hover exists; text-on-accent uses text-primary (no text-on-accent token)
    notes-popup := PopupWindow {
        close-policy: close-on-click-outside;
        x: root.width - 280px - 6px;
        y: root.height + 4px;
        width: 300px;
        height: 380px;

        popup-notes-focus := FocusScope {
            key-pressed(event) => {
                if (event.text == Key.Escape) {
                    notes-popup.close();
                    root.composer-expanded = false;
                    return accept;
                }
                return reject;
            }

            Rectangle {
                background: Colors.surface-popup;
                border-radius: 8px;
                border-width: 1px;
                border-color: Colors.border-muted;

                VerticalLayout {
                    padding: 10px;
                    spacing: 8px;
                    alignment: stretch;

                    // Composer section (top of popover)
                    Rectangle {
                        vertical-stretch: 0;
                        height: root.composer-expanded ? 110px : 30px;

                        // Collapsed: "Add note" button
                        if !root.composer-expanded : Rectangle {
                            height: 28px;
                            border-radius: 4px;
                            background: add-note-touch.has-hover ? Colors.surface-elevated : Colors.surface;
                            border-width: 1px;
                            border-color: Colors.border-muted;
                            Text {
                                text: "+ Add note";
                                font-size: Typography.size-sm;
                                color: Colors.text-secondary;
                                horizontal-alignment: center;
                                vertical-alignment: center;
                            }
                            add-note-touch := TouchArea {
                                mouse-cursor: pointer;
                                clicked => {
                                    root.composer-expanded = true;
                                }
                            }
                        }

                        // Expanded: multi-line input + Send button
                        if root.composer-expanded : Rectangle {
                            height: 108px;
                            border-radius: 4px;
                            background: Colors.background;
                            border-width: 1px;
                            border-color: Colors.accent;

                            VerticalLayout {
                                padding: 6px;
                                spacing: 4px;

                                composer-input := TextInput {
                                    text <=> root.note-draft;
                                    font-size: Typography.size-sm;
                                    color: Colors.text-primary;
                                    single-line: false;
                                    wrap: word-wrap;
                                    height: 70px;
                                    key-pressed(event) => {
                                        if (event.modifiers.control && event.text == Key.Return) {
                                            if (root.note-draft != "") {
                                                root.on-post-note(root.note-draft);
                                                root.note-draft = "";
                                                root.composer-expanded = false;
                                                popup-notes-focus.focus();
                                            }
                                            return accept;
                                        }
                                        if (event.text == Key.Escape) {
                                            root.composer-expanded = false;
                                            root.note-draft = "";
                                            popup-notes-focus.focus();
                                            return accept;
                                        }
                                        return reject;
                                    }
                                }

                                HorizontalLayout {
                                    alignment: end;
                                    spacing: 6px;
                                    Rectangle {
                                        width: 56px;
                                        height: 22px;
                                        border-radius: 4px;
                                        background: send-touch.has-hover ? Colors.accent-hover : Colors.accent;
                                        Text {
                                            text: "Send";
                                            font-size: Typography.size-xs;
                                            color: Colors.text-primary;
                                            horizontal-alignment: center;
                                            vertical-alignment: center;
                                        }
                                        send-touch := TouchArea {
                                            mouse-cursor: pointer;
                                            clicked => {
                                                if (root.note-draft != "") {
                                                    root.on-post-note(root.note-draft);
                                                    root.note-draft = "";
                                                    root.composer-expanded = false;
                                                    popup-notes-focus.focus();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Notes scroll area — clipped Rectangle with VerticalLayout (D-04: content-driven row heights)
                    // SLINT_TIPS.md: VerticalLayout inside clipped Rectangle (NOT Flickable) for top-aligned list
                    Rectangle {
                        vertical-stretch: 1;
                        clip: true;

                        if root.notes.length == 0 : Text {
                            x: 0px;
                            y: 10px;
                            width: parent.width;
                            text: "No notes yet";
                            font-size: Typography.size-sm;
                            color: Colors.text-dim;
                            horizontal-alignment: center;
                        }

                        VerticalLayout {
                            alignment: start;
                            spacing: 4px;
                            padding: 4px;

                            for note in root.notes : Rectangle {
                                // D-04: no fixed height — VerticalLayout measures preferred-height from content
                                border-radius: 4px;
                                background: Colors.surface;
                                border-width: 1px;
                                border-color: Colors.border-muted;

                                // D-05: hover-reveal absolute datetime
                                note-row-hover := TouchArea {
                                    mouse-cursor: default;
                                }

                                VerticalLayout {
                                    padding: 6px;
                                    spacing: 2px;
                                    Text {
                                        text: note.content;
                                        font-size: Typography.size-sm;
                                        color: Colors.text-primary;
                                        wrap: word-wrap;
                                        // height auto-grows from wrapped text
                                    }
                                    HorizontalLayout {
                                        spacing: 6px;
                                        alignment: start;
                                        Text {
                                            text: note.author-display;
                                            font-size: Typography.size-xs;
                                            color: Colors.text-muted;
                                        }
                                        Text {
                                            text: note.relative-time;
                                            font-size: Typography.size-xs;
                                            color: Colors.text-dim;
                                        }
                                        // D-05 hover-reveal: absolute datetime appears on hover
                                        Text {
                                            text: note.date;
                                            font-size: Typography.size-xs;
                                            color: Colors.text-dim;
                                            opacity: note-row-hover.has-hover ? 1.0 : 0.0;
                                            horizontal-alignment: left;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}
