import Quickshell.Services.UPower
import QtQuick
import QtQuick.Layouts
import ZShell.Config
import qs.Modules.Bar.Components.Common
import qs.Components
import qs.Helpers

Item {
	id: root

	readonly property Item currentItem: batteryIconLoader?.item ?? peripheralIconLoader?.item ?? upowerIconLoader.item

	implicitHeight: currentItem?.implicitHeight ?? 0
	implicitWidth: currentItem?.implicitWidth ?? 0

	Behavior on Layout.preferredHeight {
		Anim {
		}
	}
	Behavior on Layout.preferredWidth {
		Anim {
		}
	}
	Behavior on opacity {
		Anim {
		}
	}
	Behavior on scale {
		Anim {
		}
	}

	Component.onCompleted: Battery.startDaemon()

	Loader {
		id: batteryIconLoader

		active: Battery.isLaptop
		anchors.centerIn: parent

		sourceComponent: BatteryIcon {
			devState: Battery.deviceStateString
			percentage: Battery.currentPerc
		}
	}

	Loader {
		id: peripheralIconLoader

		active: (Battery.lowestPeripheral?.isPresent ?? false) && !batteryIconLoader.active
		anchors.centerIn: parent

		sourceComponent: BatteryIcon {
			devState: Battery.lowestPeripheral?.state ?? ""
			percentage: Battery.lowestPeripheral?.percentage ?? 0
		}
	}

	Loader {
		id: upowerIconLoader

		active: !batteryIconLoader.active && !peripheralIconLoader.active
		anchors.centerIn: parent

		sourceComponent: MaterialIcon {
			Layout.alignment: Qt.AlignVCenter
			animate: true
			fill: 1
			font.pointSize: Tokens.font.size.larger
			text: {
				if (PowerProfiles.profile === PowerProfile.PowerSaver)
					return "energy_savings_leaf";
				if (PowerProfiles.profile === PowerProfile.Performance)
					return "bolt";
				return "balance";
			}
		}
	}
}
