"use client";

import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import Title from "@/components/shared/Title";
import { HomepageBannerClient } from "@/features/home";
import { formatSingleDate } from "@/lib/helpers";
import { contactWhatsAppHref } from "@/lib/whatsapp";
import AssetIcon from "@/components/ui/AssetIcon";
import { NAV_STATE_KEYS } from "@/lib/navigationState";
import { useLanguageStore } from "@/store/languageStore";
import { useNavState } from "@/hooks/useNavState";

export interface OpportunityThankyouDetails {
  title_ar?: string;
  title_en?: string;
  start_date?: string;
  isInPerson?: boolean;
  islearnserve?: boolean;
  whatsapp_link?: string | null;
}

export default function RegisterNow() {
  const { t } = useTranslation();
  const language = useLanguageStore((s) => s.language);
  const contentRef = useRef<HTMLDivElement>(null);
  /* `?? {}` keeps the pre-read value exactly as it was before this used the
     shared hook: an empty object, not null, so the reads below stay direct. */
  const details =
    useNavState<OpportunityThankyouDetails>(
      NAV_STATE_KEYS.opportunityThankyou,
    ) ?? {};

  useEffect(() => {
    const timer = setTimeout(() => {
      if (contentRef.current) {
        const offset = 300; // Adjust based on your header height
        const elementPosition =
          contentRef.current.getBoundingClientRect().top + window.scrollY;
        window.scrollTo({ top: elementPosition - offset, behavior: "smooth" });
      }
    }, 100); // Small delay for content rendering

    return () => clearTimeout(timer);
  }, []);

  const { start_date, isInPerson = false, islearnserve = false } = details;
  // BA §25 — free registration is confirmed in-app: «تم تسجيلك» with a way to
  // reach the organizer on WhatsApp. Only http(s) links, since this value came
  // through sessionStorage. A link saved without its scheme gains `https://`.
  const whatsAppHref = contactWhatsAppHref(details.whatsapp_link);
  const safeWhatsAppHref = /^https:\/\//i.test(whatsAppHref) ? whatsAppHref : null;

  return (
    <>
      <HomepageBannerClient />
      <div>
        <div className="2xl:w-[880px] laptopmain:w-[1300px] laptop:w-[1359px] lg:w-[90%] 2xl:pb-[70px] pb-[40px] w-[90%] mx-auto pt-0">
          <h2
            ref={contentRef}
            className="flex justify-center mobilescreen:justify-center"
          >
            <Title text={t("COMMON.YOU_ARE_REGISTERED")} variant="default" />
          </h2>
          <div className="text-start">
            <p className="text-primary-5 text-lg mobilescreen:text-base 2xl:pb-7 pb-4">
              {t("COMMON.THANKYOU.DETAIL1")}{" "}
              {start_date ? formatSingleDate(start_date, language, t) : " "}
            </p>
            {islearnserve && !isInPerson && (
              <p className="text-primary-5 text-lg mobilescreen:text-base 2xl:pb-7 pb-4">
                {t("COMMON.THANKYOU.DETAIL4")}
              </p>
            )}
            {/* No "WhatsApp link by email" line: free registration sends no email
                (PDF p.28), so the button below is the only way the link arrives. */}
            {safeWhatsAppHref && (
              <a
                href={safeWhatsAppHref}
                target="_blank"
                rel="noopener noreferrer"
                className="mb-4 flex w-fit items-center gap-2 rounded-[20px] bg-[#25D366] px-5 py-2.5 text-sm font-bold text-white transition hover:brightness-95"
              >
                <AssetIcon src="/assets/profile/whatsapp.svg" className="h-5 w-5 brightness-0 invert" size={20} />
                {t("COMMON.CONTACT_ORGANIZER_VIA_WHATSAPP")}
              </a>
            )}
          </div>

          <div className="font-bold text-primary-5 text-[25px] 2xl:pt-8 pt-4 mobilescreen:pt-6">
            {t("COMMON.FORSA_TEAM")}
          </div>
        </div>
      </div>
    </>
  );
}
