//
//  ReflectIconWidget.swift
//  ReflectWidget
//
//  Custom icon widget (small only)
//

import WidgetKit
import SwiftUI
import Intents

// MARK: - Widget Configuration

struct ReflectIconWidget: Widget {
    let kind: String = "ReflectIconWidget"

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind,
                            intent: ConfigurationIntent.self,
                            provider: Provider()) { entry in
            ReflectIconWidgetEntryView(entry: entry)
        }
                            .configurationDisplayName("Reflect Icon")
                            .description("")
                            .supportedFamilies([.systemSmall])
                            .contentMarginsDisabled()
    }
}

// MARK: - Entry View

struct ReflectIconWidgetEntryView: View {
    @Environment(\.sizeCategory) var sizeCategory
    @Environment(\.widgetFamily) var family

    var entry: Provider.Entry

    @ViewBuilder
    var body: some View {
        SmallIconView(entry: entry)
    }
}

// MARK: - Small Icon View

struct SmallIconView: View {
    var entry: Provider.Entry

    private var customWidget: CustomWidgetModel {
        UserDefaultsStore.getCustomWidgets().first(where: { $0.inUse == true })
            ?? CustomWidgetModel.randomWidget
    }

    var body: some View {
        CustomWidgetView(customWidgetModel: customWidget)
            .ignoresSafeArea()
            .containerBackground(for: .widget) {
                customWidget.bgColor
            }
    }
}

// MARK: - Preview

#Preview("Custom Icon", as: .systemSmall) {
    ReflectIconWidget()
} timeline: {
    SimpleEntry(
        date: Date(),
        configuration: ConfigurationIntent(),
        timeLineViews: nil,
        hasSubscription: true,
        hasVotedToday: true,
        promptText: ""
    )
}
