<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div>
                <p class="text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300">Trading Tools</p>
                <h2 class="text-2xl font-bold text-slate-950 dark:text-white">Forex Market Hours</h2>
            </div>
            <a href="{{ route('trading-tools.index') }}" class="rounded-lg border border-blue-100 bg-white px-4 py-2 text-sm font-bold text-blue-700 transition hover:-translate-y-0.5 hover:bg-blue-50 dark:border-blue-900 dark:bg-slate-900 dark:text-blue-300 dark:hover:bg-blue-950/60">
                Back to Tools
            </a>
        </div>
    </x-slot>

    <div x-data="marketHours()" x-init="start()" class="space-y-6">
        <section class="grid gap-6 lg:grid-cols-3">
            <div class="rounded-lg border border-blue-100 bg-white p-6 shadow-sm dark:border-blue-900/50 dark:bg-slate-900 lg:col-span-2">
                <p class="text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300">Live Clock</p>
                <h3 class="mt-2 text-3xl font-black text-slate-950 dark:text-white" x-text="localTime"></h3>
                <p class="mt-2 text-sm text-slate-600 dark:text-slate-300">
                    Your browser local time is shown above. Session calculations use UTC rules first, then convert display times into your local timezone.
                </p>
            </div>

            <div class="rounded-lg border border-blue-100 bg-white p-6 shadow-sm dark:border-blue-900/50 dark:bg-slate-900">
                <p class="text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300">UTC Time</p>
                <h3 class="mt-2 text-3xl font-black text-slate-950 dark:text-white" x-text="utcTime"></h3>
                <p class="mt-2 text-sm text-slate-600 dark:text-slate-300">UTC keeps session calculations consistent worldwide.</p>
            </div>
        </section>

        <section class="grid gap-6 md:grid-cols-2 xl:grid-cols-4">
            <template x-for="session in sessions" :key="session.name">
                <article class="rounded-lg border border-blue-100 bg-white p-6 shadow-sm transition duration-300 hover:-translate-y-1 hover:shadow-lg hover:shadow-blue-950/10 dark:border-blue-900/50 dark:bg-slate-900 dark:hover:shadow-black/30">
                    <div class="flex items-start justify-between gap-4">
                        <div>
                            <p class="text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300" x-text="session.region"></p>
                            <h3 class="mt-2 text-xl font-bold text-slate-950 dark:text-white" x-text="session.name"></h3>
                        </div>
                        <span
                            class="rounded-full px-3 py-1 text-xs font-bold"
                            :class="session.isOpen ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-200' : 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200'"
                            x-text="session.isOpen ? 'Open' : 'Closed'"
                        ></span>
                    </div>

                    <div class="mt-5 space-y-3">
                        <div class="rounded-lg bg-blue-50 p-4 dark:bg-blue-950/30">
                            <p class="text-xs font-bold uppercase tracking-wide text-blue-700 dark:text-blue-300">Local Session Time</p>
                            <p class="mt-1 text-sm font-semibold text-slate-950 dark:text-white" x-text="session.localWindow"></p>
                        </div>
                        <div>
                            <p class="text-sm font-semibold text-slate-500 dark:text-slate-400" x-text="session.isOpen ? 'Closes in' : 'Opens in'"></p>
                            <p class="mt-1 text-2xl font-black text-slate-950 dark:text-white" x-text="session.countdown"></p>
                        </div>
                    </div>
                </article>
            </template>
        </section>

        <section class="rounded-lg border border-blue-100 bg-white p-6 shadow-sm dark:border-blue-900/50 dark:bg-slate-900">
            <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300">Session Overlaps</p>
                    <h3 class="mt-2 text-xl font-bold text-slate-950 dark:text-white">Common high-liquidity windows</h3>
                </div>
                <div class="rounded-lg bg-blue-50 px-4 py-2 text-sm font-semibold text-blue-700 dark:bg-blue-950/40 dark:text-blue-200">
                    Displayed in your local time
                </div>
            </div>

            <div class="mt-6 grid gap-4 md:grid-cols-3">
                <template x-for="overlap in overlaps" :key="overlap.name">
                    <div class="rounded-lg border border-blue-100 p-4 dark:border-blue-900/50">
                        <p class="text-base font-bold text-slate-950 dark:text-white" x-text="overlap.name"></p>
                        <p class="mt-2 text-sm font-semibold text-blue-700 dark:text-blue-300" x-text="overlap.localWindow"></p>
                        <p class="mt-2 text-sm text-slate-600 dark:text-slate-300" x-text="overlap.note"></p>
                    </div>
                </template>
            </div>
        </section>

        <section class="rounded-lg border border-blue-100 bg-white p-6 shadow-sm dark:border-blue-900/50 dark:bg-slate-900">
            <h3 class="text-lg font-bold text-slate-950 dark:text-white">Timezone Handling</h3>
            <p class="mt-3 text-sm leading-6 text-slate-600 dark:text-slate-300">
                ViZuTrade stores each market session as a UTC open and close window. JavaScript reads your browser timezone automatically and converts the UTC session windows to local display times. These are schedule rules, not live market data. Holidays, broker maintenance, daylight saving changes, and unusual exchange closures may differ by broker.
            </p>
        </section>
    </div>

    <script>
        function marketHours() {
            return {
                localTime: '',
                utcTime: '',
                sessions: [
                    { name: 'Sydney', region: 'Australia', openHour: 21, closeHour: 6 },
                    { name: 'Tokyo', region: 'Asia', openHour: 0, closeHour: 9 },
                    { name: 'London', region: 'Europe', openHour: 8, closeHour: 17 },
                    { name: 'New York', region: 'United States', openHour: 13, closeHour: 22 },
                ],
                overlaps: [
                    { name: 'Sydney + Tokyo', startHour: 0, endHour: 6, note: 'Asia-Pacific activity is usually strongest during this overlap.' },
                    { name: 'Tokyo + London', startHour: 8, endHour: 9, note: 'A short transition window between Asia and Europe.' },
                    { name: 'London + New York', startHour: 13, endHour: 17, note: 'Often the most active major forex overlap.' },
                ],
                timer: null,
                start() {
                    this.tick();
                    this.timer = setInterval(() => this.tick(), 1000);
                },
                tick() {
                    const now = new Date();

                    this.localTime = new Intl.DateTimeFormat(undefined, {
                        weekday: 'short',
                        year: 'numeric',
                        month: 'short',
                        day: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit',
                    }).format(now);

                    this.utcTime = new Intl.DateTimeFormat(undefined, {
                        timeZone: 'UTC',
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit',
                    }).format(now);

                    this.sessions = this.sessions.map((session) => this.decorateSession(session, now));
                    this.overlaps = this.overlaps.map((overlap) => ({
                        ...overlap,
                        localWindow: this.localWindow(overlap.startHour, overlap.endHour),
                    }));
                },
                decorateSession(session, now) {
                    const weekOpen = this.isForexWeekOpen(now);
                    const currentUtcMinutes = now.getUTCHours() * 60 + now.getUTCMinutes();
                    const openMinutes = session.openHour * 60;
                    const closeMinutes = session.closeHour * 60;
                    const crossesMidnight = closeMinutes <= openMinutes;
                    const dailyWindowOpen = crossesMidnight
                        ? currentUtcMinutes >= openMinutes || currentUtcMinutes < closeMinutes
                        : currentUtcMinutes >= openMinutes && currentUtcMinutes < closeMinutes;
                    const isOpen = weekOpen && dailyWindowOpen;
                    const targetDate = isOpen
                        ? this.nextUtcBoundary(now, session.closeHour, false)
                        : this.nextSessionOpen(now, session.openHour);

                    return {
                        ...session,
                        isOpen,
                        localWindow: this.localWindow(session.openHour, session.closeHour),
                        countdown: this.formatDuration(targetDate.getTime() - now.getTime()),
                    };
                },
                isForexWeekOpen(now) {
                    const day = now.getUTCDay();
                    const hour = now.getUTCHours();

                    if (day === 6) {
                        return false;
                    }

                    if (day === 0 && hour < 21) {
                        return false;
                    }

                    if (day === 5 && hour >= 22) {
                        return false;
                    }

                    return true;
                },
                nextSessionOpen(now, openHour) {
                    const target = new Date(now);

                    target.setUTCHours(openHour, 0, 0, 0);

                    if (target <= now) {
                        target.setUTCDate(target.getUTCDate() + 1);
                    }

                    while (!this.isForexWeekOpen(target)) {
                        target.setUTCDate(target.getUTCDate() + 1);
                        target.setUTCHours(openHour, 0, 0, 0);
                    }

                    return target;
                },
                nextUtcBoundary(now, hour, opening) {
                    const target = new Date(now);

                    target.setUTCHours(hour, 0, 0, 0);

                    if (target <= now) {
                        target.setUTCDate(target.getUTCDate() + 1);
                    }

                    if (!opening && hour <= 6 && now.getUTCHours() >= 21) {
                        target.setUTCDate(now.getUTCDate() + 1);
                    }

                    return target;
                },
                localWindow(startHour, endHour) {
                    return `${this.localTimeForUtcHour(startHour)} - ${this.localTimeForUtcHour(endHour)} local`;
                },
                localTimeForUtcHour(hour) {
                    const date = new Date();

                    date.setUTCHours(hour, 0, 0, 0);

                    return new Intl.DateTimeFormat(undefined, {
                        hour: '2-digit',
                        minute: '2-digit',
                    }).format(date);
                },
                formatDuration(milliseconds) {
                    const totalSeconds = Math.max(0, Math.floor(milliseconds / 1000));
                    const hours = Math.floor(totalSeconds / 3600);
                    const minutes = Math.floor((totalSeconds % 3600) / 60);
                    const seconds = totalSeconds % 60;

                    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
                },
            };
        }
    </script>
</x-app-layout>
