import QtQuick 2.15
import QtQuick.Controls.Fusion 2.15
import QtQuick.Layouts 1.15

import "../LtgWidgets"

Item {
    id: windowRoot
    width: 400
    height: 400

    readonly property real baseWidth: 400
    readonly property real baseHeight: 400
	
	// Signal to LoopToGo
    signal ltgExecute(ltgType: string, ltgAction: string, ltgParameters: string)

    Rectangle {
        anchors.fill: parent
        color: "#12181b"
    }

    Item {
        id: mainScaler
        width: baseWidth
        height: baseHeight
        anchors.centerIn: parent
        scale: Math.min(windowRoot.width / baseWidth, windowRoot.height / baseHeight)

        Item {
            id: root
            anchors.fill: parent
            property string selectedCurve: "RampUp"

            // Border and Background
            Rectangle {
                anchors.fill: parent
                color: "#12181b"
                border.color: "#00a8cc"
                border.width: 2
                Rectangle {
                    anchors.fill: parent; anchors.margins: 4
                    color: "transparent"; border.color: "#004455"; border.width: 1
                }
            }

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 25
                spacing: 15

                // Header
                ColumnLayout {
                    Layout.alignment: Qt.AlignHCenter
                    spacing: 2
                    Text {
                        text: "THE MODULATOR"; color: "#00e5ff"
                        font { pixelSize: 32; bold: true; family: "Courier"; letterSpacing: 2 }
                        Layout.alignment: Qt.AlignHCenter
                    }
                    Text {
                        text: "\"I'll be back!\""; color: "#00a8cc"
                        font { pixelSize: 14; italic: true; family: "Courier" }
                        Layout.alignment: Qt.AlignHCenter
                    }
                }

                // Curve Buttons
                GridLayout {
                    columns: 2
                    Layout.alignment: Qt.AlignHCenter
                    rowSpacing: 10; columnSpacing: 10
                    ButtonGroup { id: curveGroup }
                    Repeater {
                        model: ["RampUp", "RampDown", "Triangle", "Square", "Sin", "SampleAndHold"]
                        LtgButton {
                            id: curveBtn
							
							ltgType: "loadScript"
							ltgAction: "LoopToGo/createOrUpdateAutomationCurve.ltgs"
							ltgParameters: root.selectedCurve + " " + (minSpin.value / 100).toFixed(2) + " " + (maxSpin.value / 100).toFixed(2)
			
							
                            checkable: true
                            checked: index === 0
                            ButtonGroup.group: curveGroup
                            onCheckedChanged: if (checked) { root.selectedCurve = modelData;  }
                            background: Rectangle {
                                implicitWidth: 130; implicitHeight: 40
                                color: curveBtn.checked ? "#00e5ff" : "#1a252c"
                                border.color: "#00e5ff"; border.width: 2; radius: 4
                            }
                            contentItem: Canvas {
									id: canvas
									anchors.fill: parent
									anchors.margins: 8
									
									// 2. THE FIX: Bind a property to the checked state
									// and force the canvas to repaint itself whenever it changes.
									property bool isActive: curveBtn.checked
									onIsActiveChanged: requestPaint()
									onPaint: {
									var ctx = getContext("2d"); ctx.reset(); ctx.lineWidth = 3
									ctx.strokeStyle = curveBtn.checked ? "#12181b" : "#00e5ff"
									var w = width; var h = height; var pad = 5; ctx.beginPath()
									
									if (modelData === "RampUp") { 
										ctx.moveTo(pad, h - pad); ctx.lineTo(w - pad, pad) 
									}
									else if (modelData === "RampDown") { 
										ctx.moveTo(pad, pad); ctx.lineTo(w - pad, h - pad) 
									}
									else if (modelData === "Triangle") { 
										ctx.moveTo(pad, h - pad); ctx.lineTo(w / 2, pad); ctx.lineTo(w - pad, h - pad) 
									}
									else if (modelData === "Square") { 
										ctx.moveTo(pad, h - pad); ctx.lineTo(pad, pad); ctx.lineTo(w / 2, pad); 
										ctx.lineTo(w / 2, h - pad); ctx.lineTo(w - pad, h - pad) 
									}
									else if (modelData === "Sin") {
										// Draw a smooth Sine wave cycle
										for (var x = pad; x <= w - pad; x++) {
											var t = (x - pad) / (w - 2 * pad);
											var angle = t * Math.PI * 2;
											var y = (h / 2) - Math.sin(angle) * (h / 2 - pad);
											if (x === pad) ctx.moveTo(x, y);
											else ctx.lineTo(x, y);
										}
									}
									else if (modelData === "SampleAndHold") {
										// Draw 3 random-looking steps
										var steps = [0.7, 0.3, 0.8]; // Relative heights
										var stepW = (w - 2 * pad) / 3;
										ctx.moveTo(pad, h - (steps[0] * (h - 2 * pad) + pad));
										for (var i = 0; i < 3; i++) {
											var currX = pad + (i * stepW);
											var nextX = pad + ((i + 1) * stepW);
											var currY = h - (steps[i] * (h - 2 * pad) + pad);
											ctx.lineTo(nextX, currY);
											if (i < 2) { // Draw vertical jump to next level
												var nextY = h - (steps[i+1] * (h - 2 * pad) + pad);
												ctx.lineTo(nextX, nextY);
											}
										}
									}
									ctx.stroke()
                                }
                            }
                        }
                    }
                }

                // Min/Max Inputs
                RowLayout {
                    Layout.alignment: Qt.AlignHCenter
                    spacing: 20

                    ColumnLayout {
                        Text { text: "MIN"; color: "#00e5ff"; font.family: "Courier"; font.bold: true; Layout.alignment: Qt.AlignHCenter }
                        CustomSpinBox {
                            id: minSpin
                            value: 0
                            to: maxSpin.value // Bound: Min cannot be higher than Max
                        }
                    }

                    ColumnLayout {
                        Text { text: "MAX"; color: "#00e5ff"; font.family: "Courier"; font.bold: true; Layout.alignment: Qt.AlignHCenter }
                        CustomSpinBox {
                            id: maxSpin
                            value: 100
                            from: minSpin.value // Bound: Max cannot be lower than Min
                        }
                    }
                }

                Item { Layout.fillHeight: true }
				Text {
                        text: "To be Used with Automation Loop"; color: "#00a8cc"
                        font { pixelSize: 14; italic: true; family: "Courier" }
                        Layout.alignment: Qt.AlignHCenter
                    }
                Item { Layout.fillHeight: true }

                
            }
        }
    }

    // --- REUSABLE CUSTOM SPINBOX ---
    component CustomSpinBox : SpinBox {
        id: control
        from: 0
        to: 100
        stepSize: 1 
        editable: true
        
        // Ensure the text area doesn't cover the buttons
        leftPadding: 35
        rightPadding: 35

        textFromValue: function(value, locale) {
            return (value / 100).toFixed(2);
        }

        valueFromText: function(text, locale) {
            return Math.round(parseFloat(text) * 100);
        }

        validator: DoubleValidator {
            bottom: 0.0
            top: 1.0
            decimals: 2
        }

        contentItem: TextInput {
            text: control.textFromValue(control.value, control.locale)
            font: control.font
            color: "#00e5ff"
            selectionColor: "#004455"
            selectedTextColor: "white"
            horizontalAlignment: Qt.AlignHCenter
            verticalAlignment: Qt.AlignVCenter
            readOnly: !control.editable
            validator: control.validator
            inputMethodHints: Qt.ImhFormattedNumbersOnly
        }

        up.indicator: Rectangle {
            x: control.width - width
            height: parent.height
            width: 35
            color: control.up.pressed ? "#00e5ff" : "#1a252c"
            border.color: "#00e5ff"
            Text {
                text: "+"; anchors.centerIn: parent
                color: control.up.pressed ? "#12181b" : "#00e5ff"; font.bold: true
            }
            // Explicitly handle the click
            MouseArea {
                anchors.fill: parent
                onClicked: control.increase()
            }
        }

        down.indicator: Rectangle {
            x: 0
            height: parent.height
            width: 35
            color: control.down.pressed ? "#00e5ff" : "#1a252c"
            border.color: "#00e5ff"
            Text {
                text: "-"; anchors.centerIn: parent
                color: control.down.pressed ? "#12181b" : "#00e5ff"; font.bold: true
            }
            // Explicitly handle the click
            MouseArea {
                anchors.fill: parent
                onClicked: control.decrease()
            }
        }

        background: Rectangle {
            implicitWidth: 150
            implicitHeight: 40
            color: "#12181b"
            border.color: control.activeFocus ? "#00e5ff" : "#004455"
        }
    }
}