"use client";

import { useEffect, useState } from "react";

const KEY = "mxerp-consent-v1";

export default function ConsentBanner() {
  // Start hidden on both server and first client render to avoid
  // hydration mismatch, then sync with localStorage in an effect.
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    let stored: string | null = null;
    try {
      stored = localStorage.getItem(KEY);
    } catch {
      stored = null;
    }
    if (!stored) {
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setVisible(true);
    }
  }, []);

  if (!visible) return null;

  const choose = (value: string) => {
    try {
      localStorage.setItem(KEY, value);
    } catch {
      /* ignore */
    }
    setVisible(false);
  };

  return (
    <div
      role="dialog"
      aria-live="polite"
      aria-label="Cookie consent"
      className="fixed inset-x-0 bottom-0 z-[60] border-t border-line bg-white/95 p-4 shadow-card backdrop-blur"
      style={{ paddingBottom: "calc(16px + env(safe-area-inset-bottom, 0px))" }}
    >
      <div className="mx-container flex flex-wrap items-center gap-3">
        <p className="min-w-[220px] flex-1 text-[13px] text-muted">
          We use essential cookies to run MxERP. Analytics cookies load only if
          you accept. See <a href="/privacy-policy" className="font-medium text-brand hover:underline">Privacy policy</a> for details.
        </p>
        <div className="flex gap-2.5">
          <button
            type="button"
            onClick={() => choose("rejected")}
            className="inline-flex min-h-[44px] items-center rounded-lg border border-line px-5 text-sm font-semibold"
          >
            Reject
          </button>
          <button
            type="button"
            onClick={() => choose("accepted")}
            className="inline-flex min-h-[44px] items-center rounded-lg bg-navy px-5 text-sm font-semibold text-white"
          >
            Accept
          </button>
        </div>
      </div>
    </div>
  );
}
