"use client";

/**
 * Visitor notification settings (Feature #4).
 * - Push obaveštenja: deli isti PushNotificationsCard kao profil.
 * - Email obaveštenja: globalni prekidač (localStorage hint koji
 *   SaveSearchButton čita pri kreiranju nove pretrage).
 * - Podrazumevana učestalost digest-a za nove sačuvane pretrage.
 */

import { useEffect, useState } from "react";

import { PushNotificationsCard } from "@/components/public/profile/PushNotificationsCard";

const EMAIL_KEY = "bp.notify.email";
const FREQ_KEY = "bp.notify.frequency";

type Frequency = "INSTANT" | "DAILY" | "WEEKLY";

const FREQ_OPTIONS: Array<{ value: Frequency; label: string }> = [
  { value: "INSTANT", label: "Odmah (čim se pojavi)" },
  { value: "DAILY", label: "Dnevni pregled" },
  { value: "WEEKLY", label: "Nedeljni pregled" },
];

export function VisitorSettingsForm({
  email,
  vapidPublicKey,
}: {
  email: string;
  vapidPublicKey: string | null;
}) {
  const [emailOn, setEmailOn] = useState(true);
  const [frequency, setFrequency] = useState<Frequency>("DAILY");
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    const frame = window.requestAnimationFrame(() => {
      const e = window.localStorage.getItem(EMAIL_KEY);
      const f = window.localStorage.getItem(FREQ_KEY) as Frequency | null;
      if (e !== null) setEmailOn(e === "1");
      if (f) setFrequency(f);
    });
    return () => window.cancelAnimationFrame(frame);
  }, []);

  function persist(nextEmail: boolean, nextFreq: Frequency) {
    window.localStorage.setItem(EMAIL_KEY, nextEmail ? "1" : "0");
    window.localStorage.setItem(FREQ_KEY, nextFreq);
    setSaved(true);
    window.setTimeout(() => setSaved(false), 2000);
  }

  return (
    <div className="space-y-5">
      {/* Email */}
      <div className="rounded-2xl border border-[#ede8e3] bg-white p-5">
        <div className="flex items-start justify-between gap-4">
          <div>
            <h2 className="font-display text-lg font-bold text-[#0c1828]">
              E-mail obaveštenja
            </h2>
            <p className="mt-1 text-sm text-[#6b7280]">
              Šaljemo na <span className="font-semibold">{email}</span> kada se
              pojave novi rezultati za tvoje sačuvane pretrage.
            </p>
          </div>
          <button
            type="button"
            role="switch"
            aria-checked={emailOn}
            onClick={() => {
              const next = !emailOn;
              setEmailOn(next);
              persist(next, frequency);
            }}
            className={`relative h-7 w-12 shrink-0 rounded-full transition ${
              emailOn ? "bg-[#c2410c]" : "bg-[#d1d5db]"
            }`}
          >
            <span
              className={`absolute top-0.5 h-6 w-6 rounded-full bg-white shadow transition ${
                emailOn ? "left-[1.45rem]" : "left-0.5"
              }`}
            />
          </button>
        </div>

        <div className="mt-5 border-t border-[#f0ece7] pt-4">
          <label className="text-sm font-semibold text-[#0c1828]">
            Podrazumevana učestalost za nove pretrage
          </label>
          <div className="mt-2 grid gap-2 sm:grid-cols-3">
            {FREQ_OPTIONS.map((opt) => (
              <button
                key={opt.value}
                type="button"
                onClick={() => {
                  setFrequency(opt.value);
                  persist(emailOn, opt.value);
                }}
                className={`rounded-xl border px-3 py-2.5 text-sm font-medium transition ${
                  frequency === opt.value
                    ? "border-[#c2410c] bg-[#fff4f0] text-[#c2410c]"
                    : "border-[#ede8e3] bg-white text-[#374151] hover:border-[#c2410c]/40"
                }`}
              >
                {opt.label}
              </button>
            ))}
          </div>
          {saved && (
            <p className="mt-3 text-xs font-semibold text-emerald-600">
              ✓ Sačuvano
            </p>
          )}
        </div>
      </div>

      {/* Push */}
      <PushNotificationsCard publicKey={vapidPublicKey} />
    </div>
  );
}
