import { prisma } from '@/lib/prisma';
import LoginForm from './LoginForm';

/**
 * Server component wrapper. Reads admin count BEFORE rendering so that
 * a fresh install (no admin yet) shows a clear "needs setup" panel
 * instead of a login form that will reject every attempt with no
 * explanation.
 *
 * The "no admin" state is the explicit shipped default as of v1.0.0:4
 * — a fresh install ships with zero users, the operator must run the
 * StartOS Action "Set admin credentials" before anyone can sign in.
 */
export const dynamic = 'force-dynamic';

export default async function LoginPage() {
  const adminCount = await prisma.user.count({ where: { isAdmin: true } });
  const needsSetup = adminCount === 0;

  return (
    <div className="min-h-screen bg-[#0A0A0A] flex items-center justify-center px-4">
      <div className="w-full max-w-md">
        <div className="bg-zinc-900 rounded border border-zinc-800 shadow-2xl">
          <div className="flex flex-col space-y-2 p-8 text-center">
            <h1 className="text-3xl font-bold leading-none tracking-tight text-white">
              Proof of Work
            </h1>
            <p className="text-xs text-zinc-500 mt-2 uppercase tracking-widest">
              {needsSetup ? 'Initial setup required' : 'Track. Lift. Dominate.'}
            </p>
          </div>

          <div className="p-8 pt-6">
            {needsSetup ? <NeedsSetupPanel /> : <LoginForm />}

            {!needsSetup && (
              <p className="text-center text-xs text-zinc-500 mt-6">
                Don&apos;t have an account?{' '}
                <a
                  href="/auth/signup"
                  className="text-white underline hover:text-zinc-300"
                >
                  Sign up
                </a>
              </p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function NeedsSetupPanel() {
  return (
    <div className="space-y-4 text-sm text-zinc-300">
      <p>
        This Proof of Work instance has no admin yet. Logging in or
        signing up isn&apos;t possible until the operator creates one.
      </p>
      <ol className="list-decimal list-inside space-y-2 text-zinc-400">
        <li>Open the StartOS UI for this service.</li>
        <li>
          Make sure the service is{' '}
          <span className="text-white font-semibold">stopped</span>.
        </li>
        <li>
          Go to{' '}
          <span className="text-white font-semibold">
            Actions → Set admin credentials
          </span>
          .
        </li>
        <li>Enter the admin email + password and submit.</li>
        <li>Start the service and reload this page.</li>
      </ol>
      <p className="text-xs text-zinc-500 pt-2 border-t border-zinc-800">
        This is intentional — the package ships with no default account
        so a forgotten password rotation can&apos;t leave you with
        public-default credentials.
      </p>
    </div>
  );
}
