"use client";

import { useEffect, useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { Link } from "@/i18n/navigation";
import { isAuthenticated } from "@/lib/cookies";
import { MOBILE_CTA_HEIGHT_VAR } from "@/constants/layout";

/** Fraction of the viewport the visitor must scroll before the bar appears. */
const REVEAL_THRESHOLD = 0.7;

/**
 * Sticky bottom bar for small screens only. Once the hero scrolls away there is
 * no other way to start a trial until the trial band, several screens down —
 * this catches the intent wherever it arrives. Hidden for signed-in users,
 * who already have a subscription or trial.
 */
export default function MobileCta() {
  const t = useTranslations("mobileCta");
  const barRef = useRef<HTMLDivElement>(null);
  const [isScrolledPastHero, setIsScrolledPastHero] = useState(false);

  useEffect(() => {
    // Auth lives in a client-only cookie, so this can only be checked after
    // mount — rendering nothing on the server avoids a hydration mismatch.
    if (isAuthenticated()) return;

    const handleScroll = () => {
      setIsScrolledPastHero(window.scrollY > window.innerHeight * REVEAL_THRESHOLD);
    };

    handleScroll();
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  useEffect(() => {
    // The cookie banner is also pinned to the bottom, at a higher z-index, and
    // would otherwise cover this bar on a phone. Publish our height so the
    // banner can sit above it — both stay usable, and a visitor who never
    // answers the banner still gets a way to start a trial.
    const root = document.documentElement;
    if (!isScrolledPastHero || !barRef.current) {
      root.style.removeProperty(MOBILE_CTA_HEIGHT_VAR);
      return;
    }
    root.style.setProperty(MOBILE_CTA_HEIGHT_VAR, `${barRef.current.offsetHeight}px`);
    return () => {
      root.style.removeProperty(MOBILE_CTA_HEIGHT_VAR);
    };
  }, [isScrolledPastHero]);

  if (!isScrolledPastHero) return null;

  return (
    <div
      ref={barRef}
      className="md:hidden fixed inset-x-0 bottom-0 z-40 border-t border-gray-200 bg-white/95 backdrop-blur-sm pb-[env(safe-area-inset-bottom)] shadow-[0_-2px_12px_rgba(0,0,0,0.08)]"
    >
      <div className="flex items-center justify-between gap-3 px-4 py-3">
        <p className="text-sm font-semibold text-gray-900">{t("price")}</p>
        <Link
          href="/signup"
          className="rounded-lg bg-[#3B9EC9] px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-[#2D8AB5] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#2E8EBE]"
        >
          {t("cta")}
        </Link>
      </div>
    </div>
  );
}
