'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Modal } from '../elements/modal/modal';
import { LoginForm } from './LoginForm';
import { KeystoneLogoMinimal } from '../logo/keystone-logo-minimal';

const keystoneFooter = (
  <div className="px-6 py-4 bg-secondary flex flex-col items-center gap-1">
    <div className="flex items-center gap-1.5">
      <KeystoneLogoMinimal className="size-5 shrink-0" />
      <span className="text-sm font-medium text-primary">Keystone</span>
    </div>
    <p className="text-xs text-quaternary">Powered by Keystone Universal Login</p>
  </div>
);

/**
 * Renders a single login modal for the entire portal.
 * Any server-rendered element with `data-open-login-modal` will open it on click.
 * After successful auth the server component re-renders with the new cookie.
 */
export function LoginModalController() {
  const [open, setOpen] = useState(false);
  const [redirectUrl, setRedirectUrl] = useState<string | null>(null);
  const router = useRouter();

  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      const trigger = (e.target as HTMLElement).closest('[data-open-login-modal]');
      if (trigger) {
        e.preventDefault();
        setRedirectUrl(trigger.getAttribute('data-login-redirect'));
        setOpen(true);
      }
    };
    document.addEventListener('click', handleClick);
    return () => document.removeEventListener('click', handleClick);
  }, []);

  const handleSuccess = () => {
    setOpen(false);
    if (redirectUrl) {
      router.push(redirectUrl);
      setRedirectUrl(null);
    } else {
      router.refresh();
    }
  };

  return (
    <Modal
      isOpen={open}
      onClose={() => setOpen(false)}
      hideHeader
      ariaLabel="Sign in or create account"
      footer={keystoneFooter}
    >
      <LoginForm onSuccess={handleSuccess} onClose={() => setOpen(false)} />
    </Modal>
  );
}
