"use client";

import Link from "next/link";
import { useLanguage } from "@/lib/language-context";

type GateType = "checkout" | "reserve";

interface GateModalProps {
  open: boolean;
  type: GateType;
  onClose: () => void;
  /** After login/signup, redirect here (e.g. "/checkout"). Only used when type is "checkout". */
  returnTo?: string;
}

export default function GateModal({
  open,
  type,
  onClose,
  returnTo,
}: GateModalProps) {
  const { t } = useLanguage();

  if (!open) return null;

  const isCheckout = type === "checkout";
  const title = isCheckout ? t.gate.checkoutTitle : t.gate.reserveTitle;
  const message = isCheckout ? t.gate.checkoutMessage : t.gate.reserveMessage;

  const redirectParam =
    isCheckout &&
    returnTo &&
    returnTo.startsWith("/") &&
    !returnTo.startsWith("//")
      ? `?redirect=${encodeURIComponent(returnTo)}`
      : "";
  const loginHref = `/login${redirectParam}`;
  const signupHref = `/signup${redirectParam}`;

  return (
    <div
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4 bg-black/60 backdrop-blur-sm"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <h2 className="text-base font-bold text-gray-900">{title}</h2>
          <button
            type="button"
            onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-full text-gray-400 hover:text-gray-700 hover:bg-gray-100 transition-colors"
          >
            <svg
              className="w-4 h-4"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>
        <div className="px-6 py-5">
          <p className="text-sm text-gray-600 mb-6">{message}</p>
          <div className="flex flex-col sm:flex-row gap-3">
            <Link
              href={loginHref}
              className="btn-primary flex-1 text-center py-3.5 rounded-xl text-sm font-bold"
              onClick={onClose}
            >
              {t.auth.login}
            </Link>
            <Link
              href={signupHref}
              className="btn-secondary flex-1 text-center py-3.5 rounded-xl text-sm font-bold"
              onClick={onClose}
            >
              {t.auth.signup}
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
