import QtQuick
import QtQuick.Controls
import QtQuick.Controls.impl
import QtQuick.Layouts
import ISC
import ISC.Tabs.components
import ISC.Wafer

Item {
    id: root
    anchors.fill: parent

    // Wire streamController.trendDelta (Signal(str) carrying one new
    // [elapsed_s, value] pair per live frame) into the trend chart, which
    // accumulates its own bounded 60s window. trendReset clears it when a
    // new stream starts. Parsing happens on the Python TrendChartItem side
    // so malformed payloads are logged there instead of crashing the QML
    // binding.
    property string loadErrorMessage: ""
    Connections {
        target: streamController
        function onTrendDelta(deltaJson) {
            trendChart.appendDelta(deltaJson);
        }
        function onTrendReset() {
            trendChart.clearTrend();
        }
        function onLoadedFileChanged() {
            root.loadErrorMessage = "";
        }
        function onLoadFileError(message) {
            root.loadErrorMessage = message;
        }
    }

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 16
        spacing: 16

        // ── Toolbar ───────────────────────────────────────────────────────
        RowLayout {
            Layout.fillWidth: true
            spacing: 10

            Item {
                Layout.fillWidth: true
            }

            // SET badge + avg temp
            Rectangle {
                visible: streamController.state === "set"
                height: 22
                radius: Theme.radiusSm
                color: "transparent"
                border.color: Theme.liveColor
                border.width: 1
                implicitWidth: setLabel.implicitWidth + 16
                Label {
                    id: setLabel
                    anchors.centerIn: parent
                    text: "SET  " + (streamController.stats.avg !== undefined ? streamController.stats.avg + " avg" : "")
                    color: Theme.liveColor
                    font.pixelSize: Theme.fontXs
                    font.weight: Font.Medium
                    font.letterSpacing: 0.8
                }
            }

            // Record indicator
            RowLayout {
                spacing: 5
                visible: streamController.recording
                Rectangle {
                    width: 7
                    height: 7
                    radius: 4
                    color: Theme.recordColor
                    SequentialAnimation on opacity {
                        running: streamController.recording
                        loops: Animation.Infinite
                        NumberAnimation {
                            to: 0.2
                            duration: 600
                        }
                        NumberAnimation {
                            to: 1.0
                            duration: 600
                        }
                    }
                }
                Label {
                    text: "REC"
                    color: Theme.recordColor
                    font.pixelSize: Theme.fontXs
                    font.weight: Font.Medium
                    font.letterSpacing: 1.2
                }
            }
        }

        // ── Load error banner ───────────────────────────────────────────
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: errorRow.implicitHeight + 16
            visible: root.loadErrorMessage !== ""
            color: Theme.errorSurface
            border.color: Theme.statusErrorColor
            border.width: 1
            radius: Theme.radiusSm

            RowLayout {
                id: errorRow
                anchors.fill: parent
                anchors.margins: 8
                spacing: 8

                IconImage {
                    source: "icons/triangle-alert.svg"
                    width: 16; height: 16
                    sourceSize.width: 16
                    sourceSize.height: 16
                    color: Theme.errorTextSoft
                    Layout.alignment: Qt.AlignTop
                }

                Label {
                    text: root.loadErrorMessage
                    color: Theme.errorTextSoft
                    font.pixelSize: Theme.fontSm
                    wrapMode: Text.WordWrap
                    Layout.fillWidth: true
                }
            }
        }

        // ── Body: 2 columns (wafer + trend + transport | readout) ──────────
        RowLayout {
            Layout.fillWidth: true
            Layout.fillHeight: true
            spacing: 16


            ColumnLayout {
                Layout.fillWidth: true
                Layout.fillHeight: true
                spacing: 16

                WaferMapView {
                    id: waferView
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    Layout.preferredHeight: 400
                    Layout.minimumHeight: 280
                    blend: readoutPanel.heatmapBlend
                    showLabels: readoutPanel.showLabels
                    showExtremes: readoutPanel.showExtremes
                    showThickness: readoutPanel.showThickness
                }
                Rectangle {
                    id: trendPane
                    Layout.fillWidth: true
                    Layout.fillHeight: false
                    Layout.preferredHeight: 220
                    Layout.minimumHeight: 120
                    visible: trendChart.hasData && streamController.mode === "live"
                    color: Theme.cardBackground
                    border.color: Theme.cardBorder
                    border.width: 1
                    radius: Theme.radiusMd

                    ColumnLayout {
                        anchors.fill: parent
                        anchors.margins: 8
                        spacing: 10

                        TrendChartItem {
                            id: trendChart
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                        }
                    }
                }

                Item {
                    Layout.fillWidth: true
                    visible: transportBar.hasContent
                    implicitHeight: trendPane.visible ? 52 : 16
                }
                TransportBar {
                    id: transportBar
                    Layout.fillWidth: true
                }
            }

            // Readout panel — scrolls instead of clipping so no card is lost
            // if content outgrows the available height (e.g. once E-C delta
            // rows appear). Thresholds sits first so it's visible unscrolled.
            ScrollView {
                id: readoutScroll
                Layout.preferredWidth: Theme.rightRailWidth
                Layout.fillHeight: true
                clip: true
                ScrollBar.horizontal.policy: ScrollBar.AlwaysOff

                ScrollBar.vertical: ScrollBar {
                    parent: readoutScroll
                    anchors.top: readoutScroll.top
                    anchors.right: readoutScroll.right
                    anchors.bottom: readoutScroll.bottom
                    anchors.leftMargin: 6
                    policy: ScrollBar.AlwaysOn

                    contentItem: Rectangle {
                        implicitWidth: 8
                        implicitHeight: 8
                        radius: Theme.radiusSm
                        color: Theme.trackBackground
                    }

                    background: Rectangle {
                        implicitWidth: 8
                        color: "transparent"
                    }
                }

                ReadoutPanel {
                    id: readoutPanel
                    // Reserve a gap before the always-visible scrollbar so
                    // card content doesn't sit flush against it.
                    width: readoutScroll.availableWidth - 14
                    hasThicknessData: waferView.hasThickness
                    onExportRequested: function(filePath, extra) {
                        waferView.exportImage(filePath, extra);
                    }
                    onThicknessFileChosen: function(filePath) {
                        var err = waferView.loadThickness(filePath);
                        if (err !== "") {
                            root.loadErrorMessage = err;
                            readoutPanel.showThickness = false;
                        }
                    }
                }
            }
        }
    }
}
