// The visible dock bar: the rounded translucent pill, its items, and the
// tooltip that floats above it.
//
// Kept separate from Dock.qml so it can be dropped straight into a
// FloatingWindow for testing — PanelWindow cannot map without layer shell.

import Quickshell
import Quickshell.Hyprland
import QtQuick
import qs.config
import qs.widgets

Rectangle {
    id: root

    // ── Model ───────────────────────────────────────────────────────────────
    // One pass over the live toplevel list produces the whole dock: pinned
    // apps first in Settings order, then anything else that is running.
    // Entries are plain JS objects: { entry, windows, appId, pinned }.
    //
    // `pinned` is carried rather than inferred later. Two things need it — the
    // context menu, which cannot otherwise tell "Pin" from "Unpin", and the
    // drag, which must refuse to reorder an icon that is only there because the
    // app happens to be running.
    readonly property var items: {
        // DesktopEntries is scanned asynchronously at startup, and byId() is a
        // plain method call that creates no binding dependency. Reading the
        // model here is what makes the dock fill in once the scan lands.
        if (DesktopEntries.applications.values.length === 0)
            return [];

        const groups = {};   // appId -> [HyprlandToplevel]
        const order = [];    // appIds in first-seen order

        const toplevels = Hyprland.toplevels.values;
        for (let i = 0; i < toplevels.length; i++) {
            const t = toplevels[i];
            // `wayland` is null until Hyprland reports the address, and it is
            // the only live source of an app id — there is no `class` property.
            const appId = t.wayland ? t.wayland.appId : "";
            if (!appId)
                continue;
            if (!groups[appId]) {
                groups[appId] = [];
                order.push(appId);
            }
            groups[appId].push(t);
        }

        const out = [];
        const claimed = {};

        const pinned = Settings.dockPinned;
        for (let i = 0; i < pinned.length; i++) {
            const entry = DesktopEntries.byId(pinned[i]);
            // A pin that no longer resolves is dropped rather than drawn as a
            // broken icon.
            if (!entry)
                continue;

            let windows = [];
            for (let j = 0; j < order.length; j++) {
                if (!claimed[order[j]] && root.matches(order[j], entry, pinned[i])) {
                    claimed[order[j]] = true;
                    windows = windows.concat(groups[order[j]]);
                }
            }
            out.push({
                entry: entry,
                windows: windows,
                appId: pinned[i],
                pinned: true
            });
        }

        for (let i = 0; i < order.length; i++) {
            const appId = order[i];
            if (claimed[appId])
                continue;
            out.push({
                entry: DesktopEntries.heuristicLookup(appId),
                windows: groups[appId],
                appId: appId,
                pinned: false
            });
        }

        return out;
    }

    // Wayland app ids and desktop entry ids agree often but not always
    // (`org.gnome.Nautilus` vs `nautilus`, `Steam` vs `steam`), so compare the
    // usual candidates case-insensitively and fall back to the last
    // reverse-DNS segment.
    function matches(appId: string, entry: var, pinId: string): bool {
        const a = appId.toLowerCase();
        if (a === pinId.toLowerCase())
            return true;
        if (entry.id && a === entry.id.toLowerCase())
            return true;
        if (entry.startupClass && a === entry.startupClass.toLowerCase())
            return true;

        const tail = a.split(".").pop();
        return tail === pinId.toLowerCase().split(".").pop();
    }

    // ── Appearance ──────────────────────────────────────────────────────────
    radius: Theme.dockRadius
    color: Theme.alpha(Theme.bgPanel, Theme.dockAlpha)
    border.width: 0 // QTBUG-137166: rounded translucent rects lose their corners

    // The prism edge — see widgets/PrismEdge.qml.
    PrismEdge {
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right: parent.right
        inset: parent.radius
    }

    implicitWidth: strip.implicitWidth + Theme.dockPadding * 2
    implicitHeight: strip.implicitHeight + Theme.dockPadding * 2

    // The item the tooltip is currently describing, or null.
    property Item hoveredItem: null

    // The whole app object travels, not just its desktop entry: the menu has to
    // be able to list the app's windows and tell a pin from something that is
    // merely running, and neither fact survives being narrowed to an entry.
    signal contextMenuRequested(Item anchorItem, var app)

    // Set by the Dock. A side dock runs the same strip down the screen instead
    // of across it.
    property bool vertical: false

    // Which way a tooltip points on a side dock: away from the screen edge, so
    // it never opens off-screen.
    property bool leftSide: true

    // ── Reordering ──────────────────────────────────────────────────────────
    // Dragging an icon along the dock moves its pin. Nothing is written while
    // the gesture runs: the dragged icon is translated under the pointer, the
    // icons it passes are translated the other way by exactly one slot, and the
    // spliced list is committed once on release. Committing per slot crossed
    // would rewrite settings.json a dozen times for one gesture, and every
    // rewrite re-evaluates `items` underneath the drag.
    //
    // Translation rather than assigned x/y because a Grid owns its children's
    // positions; a transform is a purely visual offset the positioner ignores.
    property int dragIndex: -1
    property string dragId: ""
    property real dragTravel: 0

    readonly property bool dragging: root.dragIndex >= 0

    // One cell plus the gap after it: the distance the strip moves things by.
    // Reported by the item that started the drag rather than recomputed here --
    // a DockItem is taller than it is wide, so a slot down a side dock is not
    // the same distance as a slot across a bottom one. The initial value only
    // has to be non-zero; the first drag replaces it with the measured pitch.
    property real dragStep: Theme.dockIconSize + Theme.dockGap

    // How many pins are on the dock. Resolved pins are always the leading run
    // of `items`, so this doubles as the last index a drag may land on.
    readonly property int pinnedCount: {
        let count = 0;
        for (let i = 0; i < root.items.length; i++) {
            if (!root.items[i].pinned)
                break;
            count++;
        }
        return count;
    }

    readonly property int dropIndex: {
        if (root.dragIndex < 0)
            return -1;
        const slots = Math.round(root.dragTravel / root.dragStep);
        return Math.max(0, Math.min(root.pinnedCount - 1, root.dragIndex + slots));
    }

    // Where item `index` sits while a drag is in flight, relative to the slot
    // the Grid put it in.
    function dragShiftFor(index: int): real {
        if (root.dragIndex < 0)
            return 0;
        if (index === root.dragIndex)
            return root.dragTravel;
        if (root.dropIndex > root.dragIndex && index > root.dragIndex && index <= root.dropIndex)
            return -root.dragStep;
        if (root.dropIndex < root.dragIndex && index >= root.dropIndex && index < root.dragIndex)
            return root.dragStep;
        return 0;
    }

    function beginDrag(index: int, pitch: real): void {
        if (index < 0 || index >= root.pinnedCount)
            return;
        // A preview anchored to an icon that is about to move under the pointer
        // is a surface pointing at nothing.
        root.dismissPreview();
        if (pitch > 0)
            root.dragStep = pitch;
        root.dragIndex = index;
        root.dragId = root.items[index].appId;
        root.dragTravel = 0;
    }

    function moveDrag(travel: real): void {
        if (root.dragIndex < 0)
            return;
        root.dragTravel = travel;
    }

    // Resolved by pin id rather than by index. `items` drops a pin that no
    // longer resolves, so an index into the dock is not an index into the
    // stored list, and a window opening mid-drag can shift both.
    function endDrag(): void {
        const target = root.dropIndex;
        const from = root.dragId;
        const to = target >= 0 && target < root.items.length ? root.items[target].appId : "";
        root.dragIndex = -1;
        root.dragId = "";
        root.dragTravel = 0;

        if (!from || !to || from === to)
            return;

        const stored = Settings.dockPinned.slice();
        const fromAt = stored.indexOf(from);
        const toAt = stored.indexOf(to);
        if (fromAt < 0 || toAt < 0)
            return;
        stored.splice(toAt, 0, stored.splice(fromAt, 1)[0]);
        DesktopPreferences.set("dockPinned", stored);
    }

    function cancelDrag(): void {
        root.dragIndex = -1;
        root.dragId = "";
        root.dragTravel = 0;
    }

    // ── Window previews ─────────────────────────────────────────────────────
    // Hovering an icon long enough shows its windows. The dwell exists so that
    // sweeping the pointer across the dock on the way somewhere else never
    // opens anything, and the grace on the way out exists because the previews
    // are their own surface: leaving the icon to reach them would otherwise
    // close the thing being reached for.
    property Item previewAnchor: null
    property var previewApp: null

    // Written by the Dock from the preview popup's own hover.
    property bool previewHovered: false

    onHoveredItemChanged: root.reconsiderPreview()
    onPreviewHoveredChanged: root.reconsiderPreview()

    function reconsiderPreview(): void {
        const item = root.hoveredItem;
        const eligible = item && item.app && item.app.windows && item.app.windows.length > 0;

        if (eligible && item !== root.previewAnchor) {
            previewGrace.stop();
            previewDwell.restart();
            return;
        }

        previewDwell.stop();
        if (root.previewAnchor && !eligible && !root.previewHovered)
            previewGrace.restart();
        else if (eligible || root.previewHovered)
            previewGrace.stop();
    }

    function dismissPreview(): void {
        previewDwell.stop();
        previewGrace.stop();
        root.previewAnchor = null;
        root.previewApp = null;
        root.previewHovered = false;
    }

    Timer {
        id: previewDwell
        interval: 400
        onTriggered: {
            const item = root.hoveredItem;
            if (!item || !item.app || !item.app.windows || item.app.windows.length === 0)
                return;
            root.previewAnchor = item;
            root.previewApp = item.app;
        }
    }

    Timer {
        id: previewGrace
        interval: 220
        onTriggered: {
            if (!root.previewHovered)
                root.dismissPreview();
        }
    }

    // Explicit rather than left to Grid's wrapping. This is always one line, so
    // saying how many cells it holds is both simpler to read and immune to
    // Grid's default column count quietly wrapping a long dock.
    readonly property int cellCount: 2 + (root.items ? root.items.length : 0)

    // A Grid rather than a Row so one declaration serves both orientations.
    // Row and Column would each need their own children, and the cross-axis
    // anchors that centre items in a Row (verticalCenter) are the wrong axis in
    // a Column -- Grid centres through its own alignment properties instead,
    // which is the same result without the anchors positioners disallow.
    Grid {
        id: strip
        anchors.centerIn: parent
        spacing: Theme.dockGap
        rows: root.vertical ? root.cellCount : 1
        columns: root.vertical ? 1 : root.cellCount
        horizontalItemAlignment: Grid.AlignHCenter
        verticalItemAlignment: Grid.AlignVCenter

        ShowAppsButton {
            id: showApps
            onEntered: root.hoveredItem = showApps
            onExited: if (root.hoveredItem === showApps)
                root.hoveredItem = null
        }

        // Separator between the launcher and the apps, as in GNOME's dash. It
        // turns with the dock: a hairline across a column, down a row.
        Rectangle {
            width: root.vertical ? Theme.dockIconSize * 0.7 : 1
            height: root.vertical ? 1 : Theme.dockIconSize * 0.7
            border.width: 0
            color: Theme.alpha(Theme.fg, 0.14)
        }

        Repeater {
            // `items` is a fresh array of fresh objects on every change -- a
            // window opening or closing anywhere rebuilds all of it. Handing
            // that straight to Repeater resets the model and rebuilds every
            // delegate, which throws away hover state, restarts the grow
            // animation on icons nothing happened to, and would drop the
            // delegate out from under a drag in progress. ScriptModel keyed on
            // appId turns the same rebuild into "these rows changed", so an
            // icon whose window count went up keeps its delegate.
            model: ScriptModel {
                values: root.items
                objectProp: "appId"
                comparisonMode: ObjectComparison.Structure
            }

            DockItem {
                id: dockItem
                required property var modelData
                required property int index

                app: modelData
                vertical: root.vertical

                // Only a pin can be reordered. An icon that is on the dock
                // because its app happens to be running has no place in the
                // stored list to move to.
                draggable: modelData.pinned === true
                dragShift: root.dragShiftFor(dockItem.index)
                dragging: root.dragIndex === dockItem.index

                onEntered: root.hoveredItem = dockItem
                onExited: if (root.hoveredItem === dockItem)
                    root.hoveredItem = null
                onContextMenuRequested: root.contextMenuRequested(dockItem, dockItem.app)
                onDragStarted: pitch => root.beginDrag(dockItem.index, pitch)
                onDragMoved: travel => root.moveDrag(travel)
                onDragEnded: root.endDrag()
                onDragCancelled: root.cancelDrag()
            }
        }
    }

    // ── Tooltip ─────────────────────────────────────────────────────────────
    // Styled like widgets/Popover.qml. Deliberately outside the dock's bounds
    // (negative y): it renders fine there, and the dock's input mask does not
    // cover it, so it can never swallow a click.
    Rectangle {
        id: tooltip

        readonly property string text: root.hoveredItem ? root.hoveredItem.label : ""

        visible: opacity > 0
        // Yields to the window previews, which name the same app and more
        // besides -- both at once is the same label twice.
        opacity: root.hoveredItem && tipLabel.text && root.previewAnchor !== root.hoveredItem ? 1 : 0

        Behavior on opacity {
            NumberAnimation {
                duration: Theme.durFast
            }
        }

        // Centred on the hovered item along the dock's own axis, and placed just
        // outside the edge it lives on. Reads the item's position directly
        // (rather than mapToItem) so the binding re-evaluates when the strip
        // reflows.
        x: {
            if (!root.hoveredItem)
                return 0;
            if (root.vertical)
                return root.leftSide ? root.width + 8 : -width - 8;
            const centre = strip.x + root.hoveredItem.x + root.hoveredItem.width / 2;
            return Math.max(4, Math.min(root.width - width - 4, centre - width / 2));
        }
        y: {
            if (!root.hoveredItem)
                return -height - 8;
            if (!root.vertical)
                return -height - 8;
            const centre = strip.y + root.hoveredItem.y + root.hoveredItem.height / 2;
            return Math.max(4, Math.min(root.height - height - 4, centre - height / 2));
        }

        width: tipLabel.implicitWidth + Theme.popoverPadding * 2
        height: tipLabel.implicitHeight + 8

        radius: Theme.popoverRadius
        color: Theme.alpha(Theme.bgPopover, Theme.popoverAlpha)
        border.width: 1
        border.color: Theme.alpha(Theme.fg, 0.08)

        Text {
            id: tipLabel
            anchors.centerIn: parent
            text: tooltip.text
            color: Theme.fg
            font.family: Theme.fontFamily
            font.pixelSize: Theme.fontSize
        }
    }
}
