<template>
    <section class="container py-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h1 class="card-title text-primary mb-3">🌅 Good Morning Collin!</h1>
                <p class="lead mb-4">Here’s everything you need to know today:</p>
                <div class="mb-4 p-3 bg-white rounded shadow-sm">
                    <h2 class="h6 fw-semibold mb-2">📅 Today's Date</h2>
                    <p>{{ currentTime }}</p>
                </div>
                <div class="mb-4 p-3 bg-white rounded shadow-sm">
                    <h2 class="h6 fw-semibold mb-3">✅ Tasks</h2>
                    <div class="row">
                        <div class="col-auto text-end pe-3">
                            <p v-for="task in tasks" :key="task.id" class="mb-1 text-muted small monospace">
                                {{ formatTime(task) }}
                            </p>
                        </div>
                        <div class="col">
                            <p v-for="task in tasks" :key="task.id" class="mb-1">
                                {{ task.content }}
                            </p>
                        </div>
                    </div>
                </div>
                <div class="mb-4 p-3 bg-white rounded shadow-sm">
                    <h2 class="h6 fw-semibold mb-2">🌤 Weather</h2>
                    <p>{{ weatherSummary }}</p>
                </div>
                <div class="p-3 bg-white rounded shadow-sm">
                    <h2 class="h6 fw-semibold mb-2">🧥 Dressing Advice</h2>
                    <p>{{ dressingAdvice }}</p>
                </div>
            </div>
        </div>
        <EiraBubble :audioUrl="audioUrl" class="mt-4" />
    </section>
</template>
<script>
import EiraBubble from "@/components/EiraBubble.vue";

export default {
    name: "MorningBriefingView",
    components: { EiraBubble },
    data() {
        return {
            audioUrl: null,
            isPlaying: false,
            progress: 0,
            audio: null,
            currentTime: "Monday, June 9, 2025",
            tasks: [],
            weatherSummary: "Loading weather...",
            dressingAdvice: "Loading advice...",
        };
    },
    mounted() {
        this.loadAudio();
        this.updateCurrentTime();
        this.fetchTasks();
        this.fetchWeather();
        this.fetchDressingAdvice();
    },
    methods: {
        async loadAudio() {
            try {
                const response = await fetch(
                    "https://192.168.70.11:8000/audio/morning_briefing.wav/get", { method: "POST" }
                );

                if (!response.ok) throw new Error("Audio fetch failed");

                const blob = await response.blob();
                this.audioUrl = URL.createObjectURL(blob);

                this.audio = new Audio(this.audioUrl);
                this.audio.addEventListener("ended", () => {
                    this.isPlaying = false;
                    this.progress = 0;
                });
                this.audio.addEventListener("timeupdate", () => {
                    if (this.audio && this.audio.duration > 0) {
                        this.progress = (this.audio.currentTime / this.audio.duration) * 100;
                    }
                });
            } catch (error) {
                console.error("Error loading audio:", error);
            }
        },
        updateCurrentTime() {
            const now = new Date();
            const options = {
                weekday: "long",
                month: "long",
                day: "numeric",
                year: "numeric",
            };
            this.currentTime = now.toLocaleDateString(undefined, options);
        },
        async fetchTasks() {
            try {
                const response = await fetch("https://192.168.70.11:8000/todo/today");
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const result = await response.json();
                this.tasks = result.data || [];
            } catch (error) {
                console.error("Failed to fetch tasks:", error);
                this.tasks = [];
            }
        },
        async fetchWeather() {
            try {
                const response = await fetch("https://192.168.70.11:8000/weather/daily");
                if (!response.ok)
                    throw new Error(`HTTP error! status: ${response.status}`);

                const json = await response.json();
                const forecast = json.data;

                if (forecast && forecast.Temperature && forecast.Day && forecast.Night) {
                    const minTemp = Math.round(forecast.Temperature.Minimum.Value);
                    const maxTemp = Math.round(forecast.Temperature.Maximum.Value);
                    const dayPhrase = forecast.Day.IconPhrase || "Unknown";
                    const nightPhrase = forecast.Night.IconPhrase || "Unknown";

                    this.weatherSummary = `Today’s forecast: ${dayPhrase} during the day, ${nightPhrase} at night. ${minTemp}°C - ${maxTemp}°C.`;
                } else {
                    this.weatherSummary = "Weather data not available.";
                }
            } catch (error) {
                this.weatherSummary = "Failed to load weather.";
                console.error("Weather fetch error:", error);
            }
        },
        async fetchDressingAdvice() {
            try {
                const response = await fetch("https://192.168.70.11:8000/advice/dressing");
                if (!response.ok)
                    throw new Error(`HTTP error! status: ${response.status}`);
                const json = await response.json();

                const advice = json.data;

                if (advice) {
                    this.dressingAdvice = advice;
                } else {
                    this.dressingAdvice = "Dressing advice data not available.";
                }
            } catch (error) {
                this.dressingAdvice = "Failed to load dressing advice.";
                console.error("Dressing advice fetch error:", error);
            }
        },
        formatTime(task) {
            if (task.due && task.due.datetime) {
                const date = new Date(task.due.datetime);
                return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
            }
            return "";
        },
    },
};
</script>
<style scoped>
.monospace {
    font-family: monospace, monospace;
}

.text-primary {
    color: #6f42c1 !important;
}
</style>