'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { ThemeToggle } from '@/lib/theme';

const API = process.env.NEXT_PUBLIC_API_URL ?? '';

interface PublicBrand {
  id: number;
  name: string;
  app_name: string;
  has_logo: boolean;
  status: string;
}

function usePublicBrand(): PublicBrand | null {
  const [brand, setBrand] = useState<PublicBrand | null>(null);
  useEffect(() => {
    const slug = new URLSearchParams(window.location.search).get('org');
    if (!slug) return;
    fetch(`${API}/api/v1/branding?slug=${encodeURIComponent(slug)}`)
      .then((r) => (r.ok ? r.json() : null))
      .then((b) => { if (b) setBrand(b); })
      .catch(() => {});
  }, []);
  return brand;
}

export function AuthShell({ title, subtitle, children }: { title: string; subtitle: string; children: React.ReactNode }) {
  const brand = usePublicBrand();
  const appName = brand?.app_name ?? 'Qtrial';
  useEffect(() => {
    document.title = `${title} — ${appName}`;
  }, [title, appName]);
  return (
    <main className="min-h-screen grid place-items-center p-4 relative">
      <div className="absolute top-4 right-4">
        <ThemeToggle />
      </div>
      <div className="w-full max-w-sm">
        <div className="text-center mb-5">
          {brand?.has_logo ? (
            <img src={`${API}/api/v1/branding/logo/${brand.id}`} alt={`${appName} logo`}
              className="mx-auto mb-2 max-h-16 max-w-[220px] object-contain" />
          ) : (
            <p className="font-bold text-lg tracking-tight">
              <img src="/logo.svg" alt="Qtrial logo" className="mx-auto mb-1 h-12 object-contain" />
              {appName}
            </p>
          )}
          <p className="hint mt-1">{subtitle}</p>
          {brand?.status && brand.status !== 'active' && (
            <p role="status" className="alert-error mt-2 text-xs">This organisation is currently suspended. Contact support.</p>
          )}
        </div>
        <section aria-labelledby="auth-title" className="card space-y-4">
          <h1 id="auth-title" className="page-title">{title}</h1>
          {children}
        </section>
        <p className="hint text-center mt-4">© 2026 Soulitum Labs. All rights reserved.</p>
      </div>
    </main>
  );
}

export function AuthBack() {
  const [href, setHref] = useState('/login');
  useEffect(() => {
    const org = new URLSearchParams(window.location.search).get('org');
    if (org) setHref(`/login?org=${encodeURIComponent(org)}`);
  }, []);
  return (
    <Link href={href} className="link text-sm">← Back to login</Link>
  );
}
