"use client";

/**
 * /no-access — landing page for authenticated users who don't have
 * access to any brands yet.
 *
 * Triggered by the AppShell when /api/brands returns an empty list
 * for a signed-in user. Three real cases land here:
 *   1. Brand-new signup before they've created an org or been invited.
 *   2. Invited member whose admin hasn't assigned any BrandMemberships.
 *   3. A user who got removed from every brand they had access to.
 *
 * Sidebar + topnav are deliberately suppressed (this route lives in
 * STANDALONE_PREFIXES) so users can't navigate elsewhere and hit
 * confusing 403s from API routes.
 */

import Link from "next/link";
import { useRouter } from "next/navigation";
import { ShieldOff, Mail, Building2, ArrowRight, RefreshCw } from "lucide-react";
import { useClerk, useUser } from "@clerk/nextjs";
import { useState, useEffect } from "react";

export default function NoAccessPage() {
  const { signOut } = useClerk();
  const { user } = useUser();
  const router = useRouter();
  const email = user?.primaryEmailAddress?.emailAddress ?? null;
  const [retrying, setRetrying] = useState(false);

  // Auto-retry on mount — the self-healing in /api/me may have
  // repaired the membership. Give it one shot before showing the
  // lockout screen.
  useEffect(() => {
    let cancelled = false;
    const timer = setTimeout(async () => {
      try {
        const res = await fetch("/api/me");
        if (!res.ok || cancelled) return;
        const data = await res.json();
        if (data?.organizations?.[0]?.id && !cancelled) {
          router.replace("/dashboard");
        }
      } catch { /* stay on /no-access */ }
    }, 1500);
    return () => { cancelled = true; clearTimeout(timer); };
  }, [router]);

  async function handleRetry() {
    setRetrying(true);
    try {
      await fetch("/api/me");
      const res = await fetch("/api/me");
      if (res.ok) {
        const data = await res.json();
        if (data?.organizations?.[0]?.id) {
          router.replace("/dashboard");
          return;
        }
      }
    } catch { /* stay */ }
    setRetrying(false);
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 px-6">
      <div className="w-full max-w-lg text-center">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src="/meseo-logo-dark.png" alt="meSEO" className="h-9 w-auto mx-auto mb-6 object-contain" />

        <div className="bg-white rounded-2xl border border-slate-200 shadow-lg p-8">
          <div className="w-14 h-14 rounded-2xl bg-slate-900 flex items-center justify-center mx-auto mb-5">
            <ShieldOff className="w-7 h-7 text-white" />
          </div>
          <h1 className="text-xl font-bold text-slate-900 mb-2">
            You don&apos;t have access to any brands yet
          </h1>
          <p className="text-sm text-slate-500 leading-relaxed mb-6">
            Your account is set up, but no one has assigned you a brand to work with.
            Reach out to your workspace administrator and ask them to add you to a brand
            from <span className="font-semibold text-slate-700">Settings → Team</span>.
          </p>

          {email && (
            <div className="rounded-lg border border-slate-200 bg-slate-50 px-4 py-3 mb-6 text-left">
              <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-0.5">
                Signed in as
              </p>
              <p className="text-sm text-slate-700 flex items-center gap-1.5">
                <Mail className="w-3.5 h-3.5 text-slate-400" />
                {email}
              </p>
            </div>
          )}

          <div className="space-y-2">
            <button
              onClick={handleRetry}
              disabled={retrying}
              className="w-full inline-flex items-center justify-center gap-1.5 px-5 py-2.5 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 shadow-sm disabled:opacity-60"
            >
              <RefreshCw className={`w-4 h-4 ${retrying ? "animate-spin" : ""}`} />
              {retrying ? "Checking access..." : "Retry access check"}
            </button>
            <Link
              href="/website-upload"
              className="w-full inline-flex items-center justify-center gap-1.5 px-5 py-2.5 border border-slate-200 text-slate-700 text-sm font-semibold rounded-xl hover:bg-slate-50"
            >
              <Building2 className="w-4 h-4" /> Add my first brand
              <ArrowRight className="w-3 h-3" />
            </Link>
            <p className="text-[11px] text-slate-400">
              Or contact <a href="mailto:support@meseoapp.com" className="text-brand-600 font-semibold hover:underline">support@meseoapp.com</a> if this looks wrong.
            </p>
          </div>
        </div>

        <button
          onClick={() => signOut({ redirectUrl: "/sign-in" })}
          className="mt-6 text-xs text-slate-500 hover:text-slate-700 underline underline-offset-2"
        >
          Sign out
        </button>
      </div>
    </div>
  );
}
