import { WeekCalendar } from "@/components/WeekCalendar";
import { MobileCardList } from "@/components/MobileCardList";
import { WeekNav } from "@/components/WeekNav";
import { Legend } from "@/components/Legend";
import { EmptyState } from "@/components/EmptyState";
import { PARKS, groupByRegion } from "@/lib/parks";
import { openDb, getDateRange } from "@/lib/db";

interface PageProps {
  searchParams: Promise<{ week?: string }>;
}

function getWeekStart(param: string | undefined): string {
  if (param && /^\d{4}-\d{2}-\d{2}$/.test(param)) {
    const d = new Date(param + "T00:00:00");
    if (!isNaN(d.getTime())) {
      d.setDate(d.getDate() - d.getDay());
      return d.toISOString().slice(0, 10);
    }
  }
  const today = new Date();
  today.setDate(today.getDate() - today.getDay());
  return today.toISOString().slice(0, 10);
}

function getWeekDates(sundayIso: string): string[] {
  return Array.from({ length: 7 }, (_, i) => {
    const d = new Date(sundayIso + "T00:00:00");
    d.setDate(d.getDate() + i);
    return d.toISOString().slice(0, 10);
  });
}

function getCurrentWeekStart(): string {
  const today = new Date();
  today.setDate(today.getDate() - today.getDay());
  return today.toISOString().slice(0, 10);
}

export default async function HomePage({ searchParams }: PageProps) {
  const params = await searchParams;
  const weekStart = getWeekStart(params.week);
  const weekDates = getWeekDates(weekStart);
  const endDate = weekDates[6];
  const today = new Date().toISOString().slice(0, 10);
  const isCurrentWeek = weekStart === getCurrentWeekStart();

  const db = openDb();
  const data = getDateRange(db, weekStart, endDate);
  db.close();

  const scrapedCount = Object.values(data).reduce(
    (sum, parkData) => sum + Object.keys(parkData).length,
    0
  );

  const visibleParks = PARKS.filter((park) =>
    weekDates.some((date) => data[park.id]?.[date]?.isOpen)
  );

  const grouped = groupByRegion(visibleParks);

  return (
    <div style={{ minHeight: "100vh", background: "var(--color-bg)" }}>
      {/* ── Header ─────────────────────────────────────────────────────────── */}
      <header style={{
        position: "sticky",
        top: 0,
        zIndex: 20,
        background: "var(--color-bg)",
        borderBottom: "1px solid var(--color-border)",
      }}>
        {/* Row 1: Title + park count */}
        <div style={{
          padding: "12px 24px 10px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 12,
        }}>
          <span style={{
            fontSize: "1.1rem",
            fontWeight: 700,
            color: "var(--color-text)",
            letterSpacing: "-0.02em",
          }}>
            Thoosie Calendar
          </span>

          <span style={{
            background: "var(--color-surface)",
            border: "1px solid var(--color-border)",
            borderRadius: 20,
            padding: "3px 10px",
            fontSize: "0.7rem",
            color: "var(--color-text-muted)",
            fontWeight: 500,
          }}>
            {visibleParks.length} of {PARKS.length} parks open
          </span>
        </div>

        {/* Row 2: Week nav + legend */}
        <div style={{
          padding: "8px 24px 10px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 16,
          borderTop: "1px solid var(--color-border-subtle)",
        }}>
          <WeekNav
            weekStart={weekStart}
            weekDates={weekDates}
            isCurrentWeek={isCurrentWeek}
          />
          <Legend />
        </div>
      </header>

      {/* ── Main content ───────────────────────────────────────────────────── */}
      <main style={{ padding: "0 24px 48px" }}>
        {scrapedCount === 0 ? (
          <EmptyState />
        ) : (
          <>
            {/* Mobile: card list (hidden on lg+) */}
            <div className="lg:hidden">
              <MobileCardList
                grouped={grouped}
                weekDates={weekDates}
                data={data}
                today={today}
              />
            </div>

            {/* Desktop: week table (hidden below lg) */}
            <div className="hidden lg:block">
              <WeekCalendar
                parks={visibleParks}
                weekDates={weekDates}
                data={data}
                grouped={grouped}
              />
            </div>
          </>
        )}
      </main>
    </div>
  );
}
