"use client";

import { useEffect, useState } from "react";
import { BellRing, ChartLine, CircleHelp, LayoutDashboard, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useT } from "@/i18n";

const STORAGE_KEY = "kapitano.dashboard.guide-dismissed";

function readDismissed(): boolean {
  try {
    return window.localStorage.getItem(STORAGE_KEY) === "1";
  } catch {
    return false;
  }
}

/**
 * Shown the first time someone opens the dashboard: four things worth knowing, then out of the way for good.
 * It can be brought back from the page header, so dismissing it is never a loss.
 */
export function DashboardGuide({ requestOpen, onClose }: { requestOpen: number; onClose: () => void }) {
  const t = useT();
  const [open, setOpen] = useState(false);

  // First visit opens it; the header button opens it again (requestOpen counts presses).
  useEffect(() => {
    const raf = requestAnimationFrame(() => setOpen(requestOpen > 0 || !readDismissed()));
    return () => cancelAnimationFrame(raf);
  }, [requestOpen]);

  if (!open) return null;

  function dismiss() {
    try {
      window.localStorage.setItem(STORAGE_KEY, "1");
    } catch {
      // Private mode: the tour simply shows again next time.
    }
    setOpen(false);
    onClose();
  }

  const steps = [
    { icon: BellRing, text: t("dashboard.guide.inbox") },
    { icon: ChartLine, text: t("dashboard.guide.charts") },
    { icon: CircleHelp, text: t("dashboard.guide.help") },
    { icon: LayoutDashboard, text: t("dashboard.guide.customize") },
  ];

  return (
    <section
      aria-label={t("dashboard.guide.title")}
      className="mb-6 rounded-xl border border-primary/25 bg-primary/5 p-5 sm:p-6"
    >
      <div className="flex items-start justify-between gap-3">
        <h2 className="text-base font-semibold text-foreground">{t("dashboard.guide.title")}</h2>
        <button
          type="button"
          onClick={dismiss}
          aria-label={t("dashboard.guide.dismiss")}
          className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
        >
          <X className="h-4 w-4" aria-hidden />
        </button>
      </div>
      <ul className="mt-4 grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {steps.map(({ icon: Icon, text }) => (
          <li key={text} className="flex items-start gap-3 text-sm leading-6 text-muted-foreground">
            <span className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary" aria-hidden>
              <Icon className="h-4 w-4" />
            </span>
            {text}
          </li>
        ))}
      </ul>
      <div className="mt-5">
        <Button size="sm" onClick={dismiss}>
          {t("dashboard.guide.dismiss")}
        </Button>
      </div>
    </section>
  );
}
