import { ExploreRow } from "widgets/rich-model.slint";
import { RichList } from "widgets/rich-list.slint";
import { ViewSwitch } from "widgets/view-switch.slint";
import { ListView } from "std-widgets.slint";
import { Nine, Label, Theme } from "widgets/base.slint";
import { Pieces } from "widgets/pieces.slint";
import { ListFrame, SubheaderFrame } from "widgets/frame.slint";
import { LeftPane } from "widgets/left-pane.slint";
import { DetailsPane } from "widgets/details-pane.slint";
import { PortalDetail } from "widgets/description.slint";
import { InfoRow } from "widgets/info-table.slint";
import { FilterHeading, FilterRow } from "widgets/filter.slint";
import { ExploreResultRow } from "widgets/explore-row.slint";
import { Dropdown } from "widgets/dropdown.slint";
import { ToolButton } from "widgets/tool-button.slint";
import { Button } from "widgets/button.slint";
import { TextField } from "widgets/text-field.slint";
import { Scrollbar } from "widgets/scrollbar.slint";
import { LoadingOverlay } from "widgets/loading.slint";
import { ErrorBanner } from "widgets/banner.slint";
import { Tabs } from "widgets/tabs.slint";
import { GameTooltip, SearchTooltip } from "widgets/tooltip.slint";

export struct PageButton { text: string, page: int, current: bool }
export struct FilterItem { id: string, label: string, description: string, group: int, count: int, included: bool, excluded: bool }

// The tab strip the app lays over Manage once a catalogue is loaded, so the Updates badge follows the real count.
export component CatalogueTabStrip {
    in property <bool> compact;
    in property <int> current;
    in property <int> update-count;
    callback selected(int);
    Tabs {
        width: parent.width; height: 40px; current: root.current; compact: root.compact;
        items: [{text: "Manage", badge: false, enabled: true}, {text: "Explore", badge: false, enabled: true}, {text: "Updates", badge: root.update-count > 0, enabled: true}];
        selected(i) => { root.selected(i); }
    }
}

export component Explore {
    in-out property <int> view-mode: 1;
    in property <bool> batch-busy;
    in property <string> download-name;
    in property <float> download-fraction;
    in property <string> download-label;
    callback mod-action(string, bool);
    callback download-cancel(string);
    in property <[ExploreRow]> rows;
    in property <[FilterItem]> filters;
    in property <ExploreRow> detail;
    in property <PortalDetail> portal-detail;
    in property <bool> detail-loading;
    in-out property <int> detail-gallery: -1;
    in-out property <length> detail-scroll;
    callback dependency-activated(string);
    callback manage-focus(string);
    callback detail-open-url(string);
    callback detail-zoom-image(image);
    callback detail-open-changelog();
    in property <string> search-text;
    in property <int> sort;
    in property <[string]> sort-names;
    in property <[string]> group-names;
    in property <string> sort-label;
    in property <string> exclude-tip;
    in property <string> error;
    in property <string> found;
    in property <string> notice;
    // A page, search, sort or refresh is on its way: the old rows stay and are covered by the overlay.
    in property <bool> loading;
    // Bumped when new results arrive; the list then returns to the top.
    in property <int> scroll-tick;
    in property <[PageButton]> pages;
    in property <int> page-number: 1;
    property <[PageButton]> shown-pages: root.mid-width < 360px && root.pages.length > 0 ? [root.pages[0], {text: "" + root.page-number, page: root.page-number, current: true}, root.pages[root.pages.length - 1]] : root.pages;
    callback page-changed(int);
    callback refresh();
    callback viewport(int, int);
    callback open-changelog();
    in property <int> update-count;
    // Capture hooks: show the description / exclude tooltip of this filter index without a pointer.
    in property <int> force-filter-tip: -1;
    in property <int> force-exclude-tip: -1;
    in property <bool> force-search-tip;
    in property <bool> force-filter-end;
    init => { if (root.force-filter-end) { root.filter-y = -root.filter-scroll-range; } if (root.view-mode != 2) { root.viewport(0, ceil(root.rows-height / 64px)); } }
    in property <bool> force-dropdown-open;
    in property <int> force-dropdown-hover: -1;
    in property <int> force-dropdown-pressed: -1;
    // Ctrl+F (open and focus) / Escape (close), bumped by the window.
    in property <int> search-tick;
    in property <int> search-close-tick;
    callback tab(int);
    callback search(string);
    callback sort-changed(int);
    callback filter(string, bool);
    callback selected(string);
    property <bool> dropdown-open;
    // Starts open when a query is already set (capture), then follows the button.
    property <bool> search-open: root.search-text != "";
    property <bool> search-hover;
    property <string> action-tip;
    property <int> action-tip-index;
    changed search-tick => { root.search-open = true; }
    changed scroll-tick => { root.list-y = 0px; }
    changed search-close-tick => { root.close-search(); }
    function close-search() {
        if (root.search-open) {
            root.search("");
            root.dropdown-open = false;
            root.search-open = false;
        }
    }
    property <int> hover-filter: -1;
    property <int> hover-exclude: -1;
    property <int> tip-filter: root.force-filter-tip >= 0 ? root.force-filter-tip : root.hover-filter;
    property <int> tip-exclude: root.force-exclude-tip >= 0 ? root.force-exclude-tip : root.hover-exclude;
    // Row top inside the filter list: 30 px for the first heading, 24 px per later heading, 24 px per row.
    pure function filter-top(i: int) -> length { return 24px * i + 30px + 24px * root.filters[i].group; }
    pure function filter-row-y(i: int) -> length { return root.filter-top(i) + root.filter-y; }
    // The list is a plain Flickable, not a ListView: its rows have mixed heights, and a ListView only estimates the
    // height of the rows it has not instantiated yet, so the estimate (and with it the scrollbar) changed while scrolling.
    property <length> filter-content: 24px * root.filters.length + 30px + (root.filters.length > 0 ? 24px * root.filters[root.filters.length - 1].group : 0px);
    property <length> filter-scroll-range: max(0px, root.filter-content - root.pane-height);
    changed pane-height => { root.filter-y = clamp(root.filter-y, -root.filter-scroll-range, 0px); }
    property <length> list-y;
    changed list-y => { if (root.view-mode != 2) { root.viewport(max(0, floor(-root.list-y / 64px)), ceil(root.rows-height / 64px) + 1); } }
    changed rows-height => { if (root.view-mode != 2) { root.viewport(max(0, floor(-root.list-y / 64px)), ceil(root.rows-height / 64px) + 1); } }
    property <length> filter-y;
    // At the window's 1000 px minimum (968 px here), leave 300 px for results and 432 px for details.
    property <length> details-width: min(600px, root.width - 536px);
    property <length> left-width: root.width - root.details-width - 12px;
    property <length> pane-height: root.height - 72px;
    property <length> mid-width: root.left-width - 224px;
    // 36 px sub-header on top, 36 px footer strip below.
    property <length> rows-height: root.pane-height - 72px - (root.notice == "" ? 0px : 26px);
    property <bool> rows-scroll: root.rows.length * 64px > root.rows-height;
    property <bool> compact: root.mid-width < 400px;
    property <[InfoRow]> detail-info: [
        {key: "Version", value: root.detail.version, link: false, dependency: false},
        {key: "Author", value: root.detail.owner, link: false, dependency: false},
        {key: "Downloads", value: root.detail.downloads-count, link: false, dependency: false},
        {key: "Category", value: root.detail.category-label, link: false, dependency: false},
        {key: "Last updated", value: root.detail.updated, link: false, dependency: false},
        {key: "Status", value: root.detail.installed ? "Installed" : "Not installed", link: false, dependency: false},
    ];

    LeftPane {
        x: 0px; y: 0px; width: root.left-width; height: root.height; current: 1; badge: root.update-count > 0 || root.error != "";
        tab(i) => { root.tab(i); }

        // Filter column.
        ListFrame {
            x: 12px; y: 60px; width: 188px; height: root.pane-height; inner-shadow: false;
            filter-list := Flickable {
                x: 0px; y: 0px; width: 176px; height: parent.height;
                interactive: false;
                content-y <=> root.filter-y; content-width: 176px; content-height: root.filter-content;
                for item[i] in root.filters: Rectangle {
                    if i == 0 || item.group != root.filters[i - 1].group: FilterHeading { x: 8px; y: root.filter-top(i) - 22px; text: root.group-names[item.group]; }
                    FilterRow {
                        x: 8px; y: root.filter-top(i); width: 160px; height: 24px;
                        text: item.label; count: item.count < 0 ? "" : "" + item.count; checked: item.included; excluded: item.excluded; expansion: item.group == 0;
                        label-hover(h) => { root.hover-filter = h ? i : (root.hover-filter == i ? -1 : root.hover-filter); }
                        ban-hover(h) => { root.hover-exclude = h ? i : (root.hover-exclude == i ? -1 : root.hover-exclude); }
                        toggled => { root.filter(item.id, false); }
                        excluded-changed => { root.filter(item.id, true); }
                    }
                }
            }
            // Always drawn, like the game's (its Filters section continues below the list we draw).
            Scrollbar {
                x: parent.width - 12px; y: 0px; width: 12px; height: parent.height;
                thumb-height: min(self.height, max(24px, self.height * self.height / max(1px, root.filter-content)));
                thumb-position: root.filter-scroll-range <= 0px ? 0px : -root.filter-y / root.filter-scroll-range * (self.height - self.thumb-height);
                scroll(delta) => { root.filter-y = clamp(root.filter-y + delta, -root.filter-scroll-range, 0px); }
                moved(y) => { root.filter-y = -clamp((y - self.thumb-height / 2) / max(1px, self.height - self.thumb-height), 0, 1) * root.filter-scroll-range; }
            }
            Nine { x: 0px; y: 0px; width: parent.width; height: parent.height; source: Pieces.inside-deep-frame-default-shadow; }
        }

        // Results.
        ListFrame {
            x: 212px; y: 60px; width: root.mid-width; height: root.pane-height; inner-shadow: false;
            Rectangle {
                x: 0px; y: (root.notice == "" ? 36px : 62px); width: parent.width; height: root.rows-height; clip: true;
                if root.view-mode != 2: list := ListView {
                    x: 0px; y: 0px; width: parent.width - (root.rows-scroll ? 12px : 0px); height: parent.height;
                    content-y <=> root.list-y;
                    mouse-drag-pan-enabled: false;
                    horizontal-scrollbar-policy: always-off; vertical-scrollbar-policy: always-off;
                    for row[i] in root.rows: ExploreResultRow {
                        action: row.action; busy: root.batch-busy;
                        downloading: row.downloading || row.name == root.download-name; fraction: row.downloading ? row.fraction : root.download-fraction; progress-label: root.download-label;
                        activate(remove) => { root.mod-action(row.name, remove); }
                        cancel => { root.download-cancel(row.name); }
                        action-tooltip(text) => { root.action-tip = text; root.action-tip-index = i; }
                        width: list.visible-width; height: 64px;
                        title: row.title; owner: row.owner; summary: row.summary; downloads: row.downloads-count;
                        version: row.version; installed: row.installed; selected: row.selected;
                        thumbnail: row.thumbnail; missing: row.missing; update-badge: row.update-badge;
                        clicked => { root.selected(row.name); }
                    }
                }
                if root.view-mode != 2 && root.rows-scroll: Scrollbar {
                    x: parent.width - 12px; y: 0px; width: 12px; height: parent.height;
                    // Every row is 64 px. Avoid ListView's changing estimate after model updates.
                    thumb-height: min(self.height, max(24px, self.height * self.height / max(1px, root.rows.length * 64px)));
                    thumb-position: -root.list-y / max(1px, root.rows.length * 64px - root.rows-height) * (self.height - self.thumb-height);
                    scroll(delta) => { root.list-y = clamp(root.list-y + delta, -max(0px, root.rows.length * 64px - root.rows-height), 0px); }
                    moved(y) => { root.list-y = -clamp((y - self.thumb-height / 2) / max(1px, self.height - self.thumb-height), 0, 1) * max(0px, root.rows.length * 64px - root.rows-height); }
                }
            }
            if root.view-mode == 2: RichList {
                x: 0px; y: root.notice == "" ? 36px : 62px; width: parent.width; height: root.rows-height;
                rows: root.rows; grid: true; busy: root.batch-busy; reset-tick: root.scroll-tick; tall-thumbnails: true;
                selected(name) => { root.selected(name); } activate(name, remove) => { root.mod-action(name, remove); } cancel(name) => { root.download-cancel(name); }
                viewport(first, count) => { root.viewport(first, count); }
            }
            if root.error != "": ErrorBanner { x: 0px; y: 36px; width: parent.width; height: 60px; text: root.error; }

            // Footer strip: the game's list ends in a 2 px light rule over a flat #242324 band (measured, game-explore-100.png).
            Rectangle { x: 0px; y: parent.height - 39px; width: parent.width; height: 1px; background: #222122; }
            Rectangle { x: 0px; y: parent.height - 38px; width: parent.width; height: 1px; background: #201f20; }
            Rectangle { x: 0px; y: parent.height - 37px; width: parent.width; height: 1px; background: #1c1c1c; }
            Rectangle { x: 0px; y: parent.height - 36px; width: parent.width; height: 1px; background: #5e5b5a; }
            Rectangle { x: 0px; y: parent.height - 35px; width: parent.width; height: 1px; background: #3e3b3a; }
            Rectangle { x: 0px; y: parent.height - 34px; width: parent.width; height: 1px; background: #242222; }
            Label { x: 12px; y: parent.height - 34px; width: max(0px, parent.width - 24px - page-buttons.preferred-width); height: 34px; vertical-alignment: center; text: root.found; overflow: elide; }
            // Buttons grow with their text ("484"); the row hangs off the right edge.
            page-buttons := HorizontalLayout {
                x: parent.width - 8px - self.preferred-width; y: parent.height - 31px; width: self.preferred-width; height: 26px; spacing: 2px;
                for item in root.shown-pages: Button {
                    min-width: 26px; min-height: 0px; text: item.text; state: item.current ? "hovered" : "auto"; enabled: item.page > 0 && !item.current;
                    clicked => { root.page-changed(item.page); }
                }
            }
            if root.notice != "": Rectangle { x: 0px; y: 36px; width: parent.width; height: 26px; background: Theme.list-bg;
                Label { x: 8px; width: parent.width - 16px; height: 26px; text: root.notice; color: Theme.caption; overflow: elide; vertical-alignment: center; }
            }
            Nine { x: 0px; y: 0px; width: parent.width; height: parent.height; source: Pieces.scroll-pane-default-shadow; }
            if root.dropdown-open: TouchArea { x: 0px; y: 0px; width: parent.width; height: parent.height; clicked => { root.dropdown-open = false; } }
            SubheaderFrame { x: 0px; y: 0px; width: parent.width; height: 36px;
                // Narrow list: the search field takes the dropdown's place and the label gives way to a shorter dropdown.
                if !(root.compact && root.search-open) && parent.width >= 220px: Label { x: 12px; y: 1px; height: 34px; vertical-alignment: center; text: root.sort-label + ":"; font-weight: 700; color: Theme.caption; }
                if root.search-open: TextField { x: root.compact ? 4px : max(232px, parent.width - 264px); y: 3px; width: max(40px, parent.width - 66px - self.x); height: 28px; search: true; autofocus: true; focus-tick: root.search-tick; text: root.search-text; edited(text) => { root.search(text); } }
                ToolButton { x: parent.width - 62px; y: 3px; width: 28px; height: 28px; state: root.search-open ? "clicked" : "auto"; hover-changed(h) => { root.search-hover = h; } clicked => {
                    if (root.search-open) { root.close-search(); } else { root.dropdown-open = false; root.search-open = true; }
                } }
                ToolButton { x: parent.width - 32px; y: 3px; width: 28px; height: 28px; icon: "refresh"; clicked => { root.refresh(); } }
                if !(root.compact && root.search-open): Dropdown { x: parent.width >= 220px ? 69px : 4px; y: 3px; width: min(150px, parent.width - 64px - self.x); height: 28px; shorten: root.compact; items: root.sort-names; current: root.sort; open: root.dropdown-open; force-open: root.force-dropdown-open; force-hover: root.force-dropdown-hover; force-pressed: root.force-dropdown-pressed;
                    toggled => { root.dropdown-open = !root.dropdown-open; }
                    selected(i) => { root.dropdown-open = false; root.sort-changed(i); }
                }
            }
            LoadingOverlay { x: 0px; y: 36px; width: parent.width; height: root.rows-height + (root.notice == "" ? 0px : 26px); active: root.loading; }
        }
    }

    DetailsPane {
        installed: root.detail.installed;
        manage-focus(name) => { root.manage-focus(name); }
        action: root.detail.action; busy: root.batch-busy; downloading: root.detail.name != "" && root.detail.name == root.download-name;
        fraction: root.download-fraction; progress-label: root.download-label;
        activate(remove) => { root.mod-action(root.detail.name, remove); }
        cancel => { root.download-cancel(root.detail.name); }
        portal: root.portal-detail; loading: root.detail-loading;
        gallery-open <=> root.detail-gallery; scroll-y <=> root.detail-scroll;
        dependency-activated(name) => { root.dependency-activated(name); }
        open-url(url) => { root.detail-open-url(url); }
        zoom-image(image) => { root.detail-zoom-image(image); }
        x: root.left-width + 12px; y: 0px; width: root.details-width; height: root.height;
        title: root.detail.title; description: root.detail.description;
        tags: root.detail.tags;
        thumbnail: root.detail.thumbnail; missing: root.detail.missing; has-changelog: root.detail.has-changelog;
        open-changelog => { root.open-changelog(); }
        info: root.detail.name == "" ? [] : root.detail-info;
    }

    ViewSwitch { x: root.left-width - 76px; y: 12px; table: false; mode <=> root.view-mode; }
    // Last, so they paint over the list frames and the details pane. The game anchors them at the cursor; these sit under the row.
    if root.tip-exclude >= 0 && root.tip-exclude < root.filters.length && root.exclude-tip != "": GameTooltip {
        x: 12px + 8px + 160px - 16px; y: 60px + root.filter-row-y(root.tip-exclude) + 26px; text: root.exclude-tip;
    }
    if root.tip-exclude < 0 && root.tip-filter >= 0 && root.tip-filter < root.filters.length && root.filters[root.tip-filter].description != "": GameTooltip {
        x: 12px + 8px + 22px; y: 60px + root.filter-row-y(root.tip-filter) + 26px; wrap-width: 360px; text: root.filters[root.tip-filter].description;
    }
    if root.search-hover || root.force-search-tip: SearchTooltip { x: 212px + root.mid-width - 4px - self.width; y: 95px; }
    if root.action-tip != "": GameTooltip { text: root.action-tip; x: 212px + root.mid-width - self.width - 12px; y: clamp(96px + root.action-tip-index * 64px + root.list-y + 32px, 96px, root.height - self.height); }
}
