"use client";

import { useEffect, useState } from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { Chip } from "@/components/life/Controls";
import { LifeNotice } from "@/components/life/LifeStatus";
import Photo from "@/components/ui/Photo";
import type { Season } from "@/lib/api/climate";
import { useSeasonsStore } from "@/store/climate";

export const month = (m: number) => new Date(2000, m - 1, 1).toLocaleString("en", { month: "long" });

/** True when month m falls in the season, including seasons that wrap the year (December to February). */
export const covers = (s: Season, m: number) => (s.start_month <= s.end_month ? m >= s.start_month && m <= s.end_month : m >= s.start_month || m <= s.end_month);

/** Season picker that opens on the current season. Switching crossfades the panel so the change reads as one state swap. */
export default function SeasonGuide() {
  const reduce = useReducedMotion();
  const store = useSeasonsStore();
  const [picked, setPicked] = useState<number | null>(null);

  useEffect(() => {
    if (store.status === "idle") void store.load();
  }, [store.status, store.load]);

  const now = new Date().getMonth() + 1;
  const season = store.items.find((s) => s.id === picked) ?? store.items.find((s) => covers(s, now)) ?? store.items[0];
  const loading = store.status === "idle" || store.status === "loading";

  return (
    <div className="lf">
      <LifeNotice status={store.status} error={store.error} hasFallback={false} onRetry={() => void store.load()} />

      {loading && store.items.length === 0 ? (
        <div className="cl-season" aria-busy="true" aria-label="Loading">
          <div className="lf-skel" />
        </div>
      ) : (
        season && (
          <>
            <div className="lf-group sv-tools" role="group" aria-label="Season">
              {store.items.map((s) => (
                <Chip key={s.id} pressed={s.id === season.id} onClick={() => setPicked(s.id)}>
                  {s.name}
                  {covers(s, now) && <span className="sr-only"> (now)</span>}
                </Chip>
              ))}
            </div>
            <AnimatePresence mode="wait" initial={false}>
              <motion.article
                key={season.id}
                className="cl-season"
                initial={reduce ? false : { opacity: 0, y: 8 }}
                animate={{ opacity: 1, y: 0 }}
                exit={reduce ? undefined : { opacity: 0, transition: { duration: 0.12 } }}
                transition={{ duration: 0.22, ease: [0.2, 0.7, 0.2, 1] }}
              >
                <div className="cl-img">
                  <Photo src={season.cover?.url ?? null} label={season.name} alt={season.cover?.alt ?? season.name} />
                </div>
                <div className="cl-body">
                  <p className="cl-months">
                    {month(season.start_month)} to {month(season.end_month)}
                    {covers(season, now) && <span className="cl-now">Now</span>}
                  </p>
                  <h3 className="cl-h3">{season.name}</h3>
                  {season.description && <p className="cl-desc">{season.description}</p>}
                  {season.weather_tips.length > 0 && (
                    <ul className="cl-tips">
                      {season.weather_tips.map((t) => (
                        <li key={t.id}>
                          <strong>{t.title}</strong>
                          <span>{t.body}</span>
                        </li>
                      ))}
                    </ul>
                  )}
                </div>
              </motion.article>
            </AnimatePresence>
          </>
        )
      )}
    </div>
  );
}
