"use client";

import Script from "next/script";
import { useEffect, useState } from "react";

const CONSENT_KEY =
  "shipflow-cookie-consent-v1";

type ConsentChoice =
  | "accepted"
  | "rejected"
  | null;

export default function ClarityConsent() {
  const [choice, setChoice] =
    useState<ConsentChoice>(null);

  const [isReady, setIsReady] =
    useState(false);

  const projectId =
    process.env.NEXT_PUBLIC_CLARITY_PROJECT_ID;

  useEffect(() => {
    const storedChoice =
      window.localStorage.getItem(
        CONSENT_KEY
      );

    if (
      storedChoice === "accepted" ||
      storedChoice === "rejected"
    ) {
      setChoice(storedChoice);
    }

    setIsReady(true);
  }, []);

  function saveChoice(
    selectedChoice:
      | "accepted"
      | "rejected"
  ) {
    window.localStorage.setItem(
      CONSENT_KEY,
      selectedChoice
    );

    setChoice(selectedChoice);
  }

  if (!isReady) {
    return null;
  }

  return (
    <>
      {projectId &&
        choice === "accepted" && (
          <Script
            id="shipflow-clarity"
            strategy="afterInteractive"
            dangerouslySetInnerHTML={{
              __html: `
                (function(c,l,a,r,i,t,y){
                  c[a] = c[a] || function(){
                    (c[a].q = c[a].q || []).push(arguments);
                  };

                  t = l.createElement(r);
                  t.async = 1;
                  t.src =
                    "https://www.clarity.ms/tag/" + i;

                  y = l.getElementsByTagName(r)[0];

                  y.parentNode.insertBefore(t,y);

                })(
                  window,
                  document,
                  "clarity",
                  "script",
                  "${projectId}"
                );

                window.clarity(
                  "consentv2",
                  {
                    ad_Storage: "denied",
                    analytics_Storage: "granted"
                  }
                );
              `
            }}
          />
        )}

      {choice === null && (
        <div
          className="cookie-banner"
          role="dialog"
          aria-live="polite"
          aria-label="Çerez tercihleri"
        >
          <div>
            <strong>
              Çerez tercihleri
            </strong>

            <p>
              Zorunlu teknolojiler sitenin
              çalışması için kullanılır.
              Microsoft Clarity yalnızca
              analitiğe izin verdiğinizde
              yüklenir. Reklam amaçlı
              depolama kullanmıyoruz.{" "}

              <a href="/cerez-politikasi">
                Çerez Politikası
              </a>
            </p>
          </div>

          <div className="cookie-actions">
            <button
              type="button"
              className="button secondary"
              onClick={() =>
                saveChoice("rejected")
              }
            >
              Yalnız zorunlu
            </button>

            <button
              type="button"
              className="button primary"
              onClick={() =>
                saveChoice("accepted")
              }
            >
              Analitiğe izin ver
            </button>
          </div>
        </div>
      )}
    </>
  );
}