"use client"

import { useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import {
  CalendarClock,
  CheckCircle2,
  MessageCircle,
  Sparkles,
  Timer,
  Zap,
} from "lucide-react"
import { hasCaptchaPassed } from "@/lib/captcha-gate"
import { OFFLINE_COOKIE } from "@/lib/portal-access"
import { buildOfflineCopy, type SiteStatus } from "@/lib/site-status"
import { trackVisitorStep } from "@/lib/visitor-journey"
import { AGENT } from "@/lib/agent-brand"
import { CalendarMessageChat } from "@/components/calendar-message-chat"
import { ProfileAvatar } from "@/components/profile-avatar"

function syncOfflineCookie(offline: boolean) {
  try {
    if (offline) {
      document.cookie = `${OFFLINE_COOKIE}=1; Path=/; SameSite=Lax; Max-Age=86400`
    } else {
      document.cookie = `${OFFLINE_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax`
    }
  } catch {
    /* ignore */
  }
}

function getClientTimeZone(): string {
  try {
    return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"
  } catch {
    return "UTC"
  }
}

function formatInTimeZone(iso: string, timeZone: string): string {
  try {
    return new Date(iso).toLocaleString(undefined, {
      timeZone,
      weekday: "long",
      day: "numeric",
      month: "long",
      hour: "2-digit",
      minute: "2-digit",
    })
  } catch {
    return new Date(iso).toLocaleString()
  }
}

type CountdownParts = {
  days: number
  hours: number
  minutes: number
  seconds: number
  totalMs: number
}

function getCountdown(untilIso: string | null | undefined, now: number): CountdownParts | null {
  if (!untilIso) return null
  const target = new Date(untilIso).getTime()
  if (Number.isNaN(target)) return null
  const totalMs = Math.max(0, target - now)
  const totalSec = Math.floor(totalMs / 1000)
  return {
    days: Math.floor(totalSec / 86400),
    hours: Math.floor((totalSec % 86400) / 3600),
    minutes: Math.floor((totalSec % 3600) / 60),
    seconds: totalSec % 60,
    totalMs,
  }
}

function getWaitProgress(
  untilIso: string | null | undefined,
  startedIso: string | null | undefined,
  now: number
): number {
  if (!untilIso || !startedIso) return 0
  const end = new Date(untilIso).getTime()
  const start = new Date(startedIso).getTime()
  if (Number.isNaN(end) || Number.isNaN(start) || end <= start) return 0
  return Math.min(100, Math.max(0, ((now - start) / (end - start)) * 100))
}

function pad2(n: number) {
  return String(n).padStart(2, "0")
}

function CountdownDigit({ value, label }: { value: number; label: string }) {
  return (
    <div className="flex flex-col items-center">
      <div className="offline-glass relative flex h-[4.5rem] w-[4.5rem] items-center justify-center rounded-2xl sm:h-[5.25rem] sm:w-[5.25rem]">
        <span
          key={value}
          className="offline-countdown-digit text-3xl font-bold tabular-nums tracking-tight text-white sm:text-4xl"
        >
          {pad2(value)}
        </span>
        <div className="pointer-events-none absolute inset-0 rounded-2xl ring-1 ring-inset ring-white/10" />
      </div>
      <span className="mt-2.5 text-[10px] font-semibold uppercase tracking-[0.2em] text-white/45">
        {label}
      </span>
    </div>
  )
}

function ProgressRing({ progress, size = 280 }: { progress: number; size?: number }) {
  const stroke = 6
  const r = (size - stroke * 2) / 2
  const c = 2 * Math.PI * r
  const offset = c * (1 - progress / 100)

  return (
    <svg
      width={size}
      height={size}
      className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 -rotate-90"
      aria-hidden
    >
      <circle
        cx={size / 2}
        cy={size / 2}
        r={r}
        fill="none"
        stroke="rgba(255,255,255,0.08)"
        strokeWidth={stroke}
      />
      <circle
        cx={size / 2}
        cy={size / 2}
        r={r}
        fill="none"
        stroke="url(#offlineProgressGrad)"
        strokeWidth={stroke}
        strokeLinecap="round"
        strokeDasharray={c}
        strokeDashoffset={offset}
        className="transition-[stroke-dashoffset] duration-1000 ease-out"
      />
      <defs>
        <linearGradient id="offlineProgressGrad" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="#067ab4" />
          <stop offset="50%" stopColor="#34A853" />
          <stop offset="100%" stopColor="#FBBC05" />
        </linearGradient>
      </defs>
    </svg>
  )
}

const TIMELINE = [
  {
    step: "01",
    title: "Quick update",
    body: "We're polishing the calendar so your booking goes smoothly.",
    icon: Zap,
  },
  {
    step: "02",
    title: "Countdown running",
    body: "Stay on this page — we'll open scheduling the moment we're ready.",
    icon: Timer,
  },
  {
    step: "03",
    title: "You're in",
    body: "Pick a time as soon as the timer hits zero.",
    icon: CheckCircle2,
  },
] as const

export default function OfflinePage({
  embedded = false,
  onNeedCaptcha,
  onBackOnline,
}: {
  embedded?: boolean
  onNeedCaptcha?: () => void
  onBackOnline?: () => void
} = {}) {
  const router = useRouter()
  const [status, setStatus] = useState<SiteStatus | null>(null)
  const [ready, setReady] = useState(false)
  const [timeZone, setTimeZone] = useState("UTC")
  const [now, setNow] = useState(() => Date.now())

  useEffect(() => {
    setTimeZone(getClientTimeZone())
  }, [])

  useEffect(() => {
    const id = window.setInterval(() => setNow(Date.now()), 1000)
    return () => window.clearInterval(id)
  }, [])

  useEffect(() => {
    if (!hasCaptchaPassed()) {
      if (embedded && onNeedCaptcha) {
        onNeedCaptcha()
      } else {
        router.replace("/")
      }
      return
    }

    let cancelled = false
    const load = async () => {
      try {
        const res = await fetch("/api/site-status", { cache: "no-store" })
        const data = (await res.json()) as SiteStatus
        if (cancelled) return
        syncOfflineCookie(Boolean(data.offline))
        if (!data.offline) {
          if (embedded && onBackOnline) onBackOnline()
          else router.replace("/schedule-call")
          return
        }
        setStatus(data)
        setReady(true)
      } catch {
        if (!cancelled) {
          syncOfflineCookie(true)
          setStatus({
            offline: true,
            offlineUntil: null,
            offlineMessage: null,
            updatedAt: new Date().toISOString(),
          })
          setReady(true)
        }
      }
    }

    void trackVisitorStep({ id: "home.offline", label: "Sent to offline page" })
    void load()
    const id = window.setInterval(load, 15_000)
    return () => {
      cancelled = true
      window.clearInterval(id)
    }
  }, [router, embedded, onNeedCaptcha, onBackOnline])

  const countdown = useMemo(
    () => getCountdown(status?.offlineUntil, now),
    [status?.offlineUntil, now]
  )

  const progress = useMemo(
    () => getWaitProgress(status?.offlineUntil, status?.updatedAt, now),
    [status?.offlineUntil, status?.updatedAt, now]
  )

  useEffect(() => {
    if (countdown?.totalMs === 0 && status?.offlineUntil) {
      void fetch("/api/site-status", { cache: "no-store" }).then(async (res) => {
        const data = (await res.json()) as SiteStatus
        if (!data.offline) {
          if (embedded && onBackOnline) onBackOnline()
          else router.replace("/schedule-call")
        }
      })
    }
  }, [countdown?.totalMs, status?.offlineUntil, router, embedded, onBackOnline])

  const copy = status
    ? buildOfflineCopy(status)
    : { title: "Calendar is taking a short break", body: "We'll be ready for you very soon." }

  const reopening = countdown ? countdown.totalMs <= 0 : false

  if (!ready) {
    return (
      <div className="offline-page-bg flex min-h-screen flex-col items-center justify-center gap-4 px-4">
        <div className="relative">
          <div className="h-14 w-14 animate-spin rounded-full border-[3px] border-white/10 border-t-[#067ab4]" />
          <div className="absolute inset-0 animate-ping rounded-full border border-[#067ab4]/30" />
        </div>
        <p className="text-sm text-white/60">Preparing your calendar…</p>
      </div>
    )
  }

  return (
    <div className="offline-page-bg relative min-h-screen overflow-x-hidden text-white">
      {/* Ambient orbs */}
      <div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden>
        <div className="offline-orb absolute -left-24 top-20 h-72 w-72 rounded-full bg-[#067ab4]/20 blur-3xl" />
        <div
          className="offline-orb absolute -right-16 top-1/3 h-96 w-96 rounded-full bg-[#34A853]/10 blur-3xl"
          style={{ animationDelay: "-4s" }}
        />
        <div
          className="offline-orb absolute bottom-0 left-1/3 h-80 w-80 rounded-full bg-indigo-500/15 blur-3xl"
          style={{ animationDelay: "-8s" }}
        />
      </div>

      <div className="relative z-10 mx-auto max-w-6xl px-4 pb-16 pt-6 sm:px-6 sm:pt-10">
        {/* Header */}
        <header className="offline-fade-up mb-10 flex flex-wrap items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-gradient-to-br from-[#067ab4] to-[#067ab4] text-sm font-bold shadow-lg shadow-[#067ab4]/30">
              {AGENT.firstName.charAt(0)}
              {AGENT.name.split(" ")[1]?.charAt(0) ?? ""}
            </div>
            <div>
              <p className="text-sm font-semibold text-white">{AGENT.calendarName}</p>
              <p className="text-xs text-white/50">{AGENT.tagline}</p>
            </div>
          </div>
          <span className="inline-flex items-center gap-2 rounded-full border border-amber-400/30 bg-amber-400/10 px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.12em] text-amber-200 backdrop-blur-sm">
            <span className="relative flex h-2 w-2">
              <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-60" />
              <span className="relative inline-flex h-2 w-2 rounded-full bg-amber-400" />
            </span>
            Be back soon
          </span>
        </header>

        {/* Hero */}
        <section
          className="offline-fade-up mx-auto mb-10 max-w-3xl text-center"
          style={{ animationDelay: "0.1s" }}
        >
          <div className="mb-6 inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-4 py-1.5 text-[11px] font-medium uppercase tracking-[0.18em] text-white/70">
            <Sparkles className="h-3.5 w-3.5 text-[#FBBC05]" />
            Worth the wait
          </div>
          <h1 className="offline-shimmer-text text-balance text-3xl font-bold leading-tight tracking-tight sm:text-4xl md:text-5xl">
            {reopening ? "Opening your calendar…" : copy.title}
          </h1>
          <p className="mx-auto mt-5 max-w-xl text-base leading-relaxed text-white/65 sm:text-lg">
            {reopening
              ? "Hang tight — you'll be redirected to schedule in just a moment."
              : copy.body}
          </p>
        </section>

        {/* Countdown centerpiece */}
        <section
          className="offline-fade-up mx-auto mb-12 max-w-2xl"
          style={{ animationDelay: "0.2s" }}
        >
          <div className="offline-glass overflow-hidden p-6 sm:p-10">
            <div className="mb-8 flex flex-col items-center text-center">
              <ProfileAvatar compact />
              <p className="mt-4 text-lg font-semibold text-white">{AGENT.name}</p>
              <p className="text-sm text-white/50">{AGENT.title}</p>
            </div>

            {status?.offlineUntil && countdown ? (
              <>
                <div className="relative mx-auto mb-8 flex h-[17rem] w-full max-w-[18rem] items-center justify-center sm:h-[19rem] sm:max-w-[20rem]">
                  <ProgressRing progress={progress} size={300} />
                  <div
                    className="absolute inset-0 rounded-full opacity-30"
                    style={{ animation: "offline-pulse-ring 3s ease-in-out infinite" }}
                  />
                  <div className="relative z-10 text-center">
                    <p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-white/45">
                      {reopening ? "Ready" : "Opens in"}
                    </p>
                    <p className="mt-2 text-4xl font-bold tabular-nums text-white sm:text-5xl">
                      {reopening
                        ? "0:00"
                        : countdown.days > 0
                          ? `${countdown.days}d ${pad2(countdown.hours)}h`
                          : `${pad2(countdown.hours)}:${pad2(countdown.minutes)}`}
                    </p>
                    {!reopening && countdown.days === 0 ? (
                      <p className="mt-1 text-sm tabular-nums text-white/50">
                        {pad2(countdown.seconds)} sec
                      </p>
                    ) : null}
                  </div>
                </div>

                <div className="flex justify-center gap-3 sm:gap-4">
                  <CountdownDigit value={countdown.days} label="Days" />
                  <CountdownDigit value={countdown.hours} label="Hours" />
                  <CountdownDigit value={countdown.minutes} label="Min" />
                  <CountdownDigit value={countdown.seconds} label="Sec" />
                </div>

                <div className="mt-8 rounded-2xl border border-white/10 bg-white/5 px-4 py-4 text-center sm:px-6">
                  <p className="flex items-center justify-center gap-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/45">
                    <CalendarClock className="h-3.5 w-3.5" />
                    Back online
                  </p>
                  <p className="mt-2 text-sm font-medium text-white sm:text-base">
                    {formatInTimeZone(status.offlineUntil, timeZone)}
                  </p>
                  <p className="mt-1 text-xs text-white/40">{timeZone}</p>
                  <div className="mx-auto mt-4 h-1.5 max-w-xs overflow-hidden rounded-full bg-white/10">
                    <div
                      className="h-full rounded-full bg-gradient-to-r from-[#067ab4] via-[#34A853] to-[#FBBC05] transition-all duration-1000"
                      style={{ width: `${Math.max(progress, 2)}%` }}
                    />
                  </div>
                  <p className="mt-2 text-[11px] text-white/40">
                    {Math.round(progress)}% of the wait complete · auto-redirect when ready
                  </p>
                </div>
              </>
            ) : (
              <div className="py-8 text-center">
                <Timer className="mx-auto h-12 w-12 text-[#067ab4]" />
                <p className="mt-4 text-lg font-semibold">Maintenance in progress</p>
                <p className="mt-2 text-sm text-white/55">
                  Scheduling reopens shortly. Leave a message below if you need help.
                </p>
              </div>
            )}
          </div>
        </section>

        {/* Timeline */}
        <section
          className="offline-fade-up mb-12 grid gap-4 sm:grid-cols-3 sm:gap-5"
          style={{ animationDelay: "0.3s" }}
        >
          {TIMELINE.map(({ step, title, body, icon: Icon }, i) => (
            <div
              key={step}
              className="offline-glass group relative overflow-hidden p-5 transition hover:border-white/20 sm:p-6"
            >
              <div className="absolute -right-4 -top-4 text-6xl font-black text-white/[0.04]">
                {step}
              </div>
              <span className="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-[#067ab4]/30 to-[#067ab4]/10 text-[#f5a8bc] ring-1 ring-white/10">
                <Icon className="h-5 w-5" />
              </span>
              <h3 className="mt-4 text-sm font-semibold text-white">{title}</h3>
              <p className="mt-2 text-sm leading-relaxed text-white/55">{body}</p>
              {i < TIMELINE.length - 1 ? (
                <div className="absolute -right-2 top-1/2 hidden h-px w-4 bg-gradient-to-r from-white/20 to-transparent sm:block lg:w-6" />
              ) : null}
            </div>
          ))}
        </section>

        {/* Message */}
        <section className="offline-fade-up grid gap-6 lg:grid-cols-5 lg:gap-8" style={{ animationDelay: "0.4s" }}>
          <div className="offline-glass flex flex-col justify-center p-6 lg:col-span-2 lg:p-8">
            <span className="inline-flex w-fit items-center gap-2 rounded-full bg-[#067ab4]/20 px-3 py-1 text-[11px] font-semibold uppercase tracking-wider text-[#f5a8bc]">
              <MessageCircle className="h-3.5 w-3.5" />
              While you wait
            </span>
            <h2 className="mt-4 text-xl font-bold text-white sm:text-2xl">
              Message {AGENT.firstName} directly
            </h2>
            <p className="mt-3 text-sm leading-relaxed text-white/55">
              Questions about your interview or scheduling? Send a note — you&apos;ll get a reply
              right here without leaving the page.
            </p>
            <ul className="mt-6 space-y-3 text-sm text-white/50">
              <li className="flex items-center gap-2">
                <CheckCircle2 className="h-4 w-4 shrink-0 text-[#34A853]" />
                Replies appear in your thread below
              </li>
              <li className="flex items-center gap-2">
                <CheckCircle2 className="h-4 w-4 shrink-0 text-[#34A853]" />
                No need to email separately
              </li>
              <li className="flex items-center gap-2">
                <CheckCircle2 className="h-4 w-4 shrink-0 text-[#34A853]" />
                Calendar opens automatically when ready
              </li>
            </ul>
          </div>

          <div className="lg:col-span-3">
            <div className="offline-glass-light overflow-hidden">
              <CalendarMessageChat theme="light" />
            </div>
          </div>
        </section>

        <p className="offline-fade-up mt-10 text-center text-xs text-white/35" style={{ animationDelay: "0.5s" }}>
          {AGENT.calendarShort} · AT&T Company Careers scheduling · This page refreshes automatically
        </p>
      </div>
    </div>
  )
}
