import { useEffect } from "react";
import { useSearchParams } from "react-router-dom";

const COOKIE_NAME = "chatsku_partner_code";
const MAX_AGE = 365 * 24 * 60 * 60; // 1 year

export function getPartnerCode(): string | null {
  const match = document.cookie
    .split("; ")
    .find((c) => c.startsWith(`${COOKIE_NAME}=`));
  return match ? decodeURIComponent(match.split("=")[1]) : null;
}

function setPartnerCookie(value: string) {
  document.cookie = `${COOKIE_NAME}=${encodeURIComponent(value)}; max-age=${MAX_AGE}; path=/; SameSite=Lax`;
}

/** Call once inside BrowserRouter to capture ?partnerCode=XXX from any landing page. */
export function usePartnerCode() {
  const [searchParams] = useSearchParams();

  useEffect(() => {
    const code = searchParams.get("partnerCode");
    if (code && code.trim()) {
      setPartnerCookie(code.trim());
    }
  }, [searchParams]);
}
