// ───────────────────────────────────────────────
// Join (Invite) Page (/join/[token])
// ───────────────────────────────────────────────
// Route: /join/:token
// Purpose: Server component that validates an
//   invite token. If the token is a UUID (room
//   ID), it redirects directly to /call/:token.
//   Otherwise it queries the DB for an SMS-style
//   invite and shows a "You're Invited!" landing
//   page with the caller's phone number.
// Layout: Centered card with invite details and
//   a "Create Account" CTA.
// Error states: invalid token, expired token.
// ───────────────────────────────────────────────

import { query } from "@/lib/db"
import { redirect } from "next/navigation"

interface Props {
  params: Promise<{ token: string }>
}

/**
 * ErrorPage
 * ─────────
 * Shared inline component for rendering error
 * states (invalid / expired) with the same
 * card styling.
 *
 * @param message - The error message to display.
 * @returns A centered error card.
 */
function ErrorPage({ message }: { message: string }) {
  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-[#C84B4B]/10 to-[#C84B4B]/10 p-4">
      <div className="bg-white dark:bg-[#141414] rounded-2xl p-8 w-full max-w-md border border-[#D4D8CC] dark:border-[#CC0000]/20 shadow-lg text-center">
        <h1 className="text-2xl font-bold text-[#2D3020] dark:text-white mb-3">
          {message}
        </h1>
      </div>
    </div>
  )
}

/**
 * JoinPage
 * ────────
 * Validates an invite token. UUID tokens redirect
 * directly into a call room. DB-backed tokens
 * (from SMS invites) show a landing page with
 * the inviter's contact info and a register CTA.
 *
 * @param params - Route params containing the token.
 * @returns An error page, redirect, or invite page.
 */
export default async function JoinPage({ params }: Props) {
  const { token } = await params

  // ── UUID tokens → direct call room redirect ──
  const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i

  if (UUID_REGEX.test(token)) {
    redirect(`/call/${token}`)
  }

  // ── Look up SMS invite token in DB ──
  const result = await query(
    `SELECT phone, created_at, expires_at FROM invites WHERE token = $1 LIMIT 1`,
    [token],
  )

  if (result.rows.length === 0) {
    return <ErrorPage message="This call link is invalid." />
  }

  const invite = result.rows[0]

  // ── Check expiration ──
  if (new Date(invite.expires_at) <= new Date()) {
    return <ErrorPage message="This call has expired." />
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-[#C84B4B]/10 to-[#C84B4B]/10 p-4">
      <div className="bg-white dark:bg-[#141414] rounded-2xl p-8 w-full max-w-md border border-[#D4D8CC] dark:border-[#CC0000]/20 shadow-lg text-center">
        <h1 className="text-2xl font-bold text-[#2D3020] dark:text-white mb-3">
          You&apos;re Invited!
        </h1>
        <p className="text-[#8A9078] text-sm mb-6">
          Someone wants to connect with you on our platform.
        </p>
        {/* ── Inviter's contact number ── */}
        <div className="bg-[#FAFAF6] dark:bg-[#1A1A1A] rounded-xl p-4 mb-6 text-left">
          <p className="text-xs text-[#8A9078] mb-1">Contact Number</p>
          <p className="text-sm font-medium text-[#2D3020] dark:text-white">{invite.phone}</p>
        </div>
        <p className="text-xs text-[#8A9078] mb-6">
          Create an account to start making free voice calls to this person and others on the platform.
        </p>
        {/* ── Registration CTA ── */}
        <a
          href="/register"
          className="block w-full bg-[#C84B4B] hover:bg-[#C84B4B]/80 dark:bg-[#FF1111] dark:hover:bg-[#CC0000] text-white font-semibold text-sm rounded-xl py-3 transition-all duration-200"
        >
          Create Account
        </a>
      </div>
    </div>
  )
}
