'use client';

import { useEffect, useRef } from 'react';
import { GmWelcomeArt } from '@/features/meetings/ui/scheduler/gmParts';

/**
 * HUB-662 parts of the public booking page: the page's picture (Schedule › Image), the welcome
 * screen's, and the reCAPTCHA box of Form › CAPTCHA.
 */

const initialOf = (name: string) => name.trim().charAt(0).toUpperCase() || '?';

/**
 * The picture by the title: the organizer's photo or a custom image when there is one, else
 * the initial of the organizer (or, for "Company avatar", of the company: the CRM has no logo).
 */
export function BookAvatar({
  kind,
  url,
  name,
}: {
  kind: 'organizer' | 'company' | 'custom';
  url: string | null;
  name: string;
}) {
  return (
    <span className="crm-public-book__avatar" data-kind={kind} aria-hidden="true">
      {/* eslint-disable-next-line @next/next/no-img-element -- the page's own picture address */}
      {url ? <img src={url} alt="" /> : initialOf(name)}
    </span>
  );
}

/** The welcome screen's picture: the default illustration, the company's avatar or a custom one. */
export function WelcomeArt({
  kind,
  url,
  companyName,
}: {
  kind: 'default' | 'company' | 'custom';
  url: string | null;
  companyName: string;
}) {
  if (kind === 'company' || (kind === 'custom' && url)) {
    return <BookAvatar kind={kind} url={kind === 'custom' ? url : null} name={companyName} />;
  }
  // The design's default welcome picture (create-meeting.html #gm-welcome-illustration).
  return <GmWelcomeArt className="crm-public-book__welcome-art" />;
}

interface Grecaptcha {
  ready: (callback: () => void) => void;
  render: (
    element: HTMLElement,
    options: { sitekey: string; callback: (token: string) => void; 'expired-callback': () => void },
  ) => number;
}

declare global {
  interface Window {
    grecaptcha?: Grecaptcha;
  }
}

const SCRIPT_ID = 'crm-recaptcha';

/** Google reCAPTCHA v2 ("I'm not a robot"); `onToken(null)` when the answer expires. */
export function CaptchaBox({
  siteKey,
  onToken,
}: {
  siteKey: string;
  onToken: (token: string | null) => void;
}) {
  const box = useRef<HTMLDivElement>(null);
  useEffect(() => {
    let cancelled = false;
    const draw = () => {
      const el = box.current;
      if (cancelled || !el || el.childElementCount || !window.grecaptcha) return;
      window.grecaptcha.ready(() => {
        if (cancelled || el.childElementCount) return;
        window.grecaptcha?.render(el, {
          sitekey: siteKey,
          callback: (token) => onToken(token),
          'expired-callback': () => onToken(null),
        });
      });
    };
    if (window.grecaptcha) {
      draw();
    } else {
      let script = document.getElementById(SCRIPT_ID) as HTMLScriptElement | null;
      if (!script) {
        script = document.createElement('script');
        script.id = SCRIPT_ID;
        script.src = 'https://www.google.com/recaptcha/api.js?render=explicit';
        script.async = true;
        script.defer = true;
        document.head.appendChild(script);
      }
      script.addEventListener('load', draw);
    }
    return () => {
      cancelled = true;
    };
  }, [siteKey, onToken]);
  return <div className="crm-public-book__captcha" ref={box} />;
}
