"use client";

import React, { useEffect, useState, useCallback } from "react";
import Image from "next/image";
import { onboardingService, OnboardingSlide } from "@/services/onboardingService";

const STORAGE_KEY = "doliplay_onboarded";

export default function OnboardingScreen() {
  const [seen, setSeen] = useState<boolean | null>(null);
  const [slides, setSlides] = useState<OnboardingSlide[]>([]);
  const [current, setCurrent] = useState(0);
  const [leaving, setLeaving] = useState(false);
  const [visible, setVisible] = useState(false);

  /* Check localStorage once on mount (client only) */
  useEffect(() => {
    const alreadySeen = localStorage.getItem(STORAGE_KEY) === "1";
    setSeen(alreadySeen);
  }, []);

  /* Fetch slides only when we know user hasn't seen onboarding */
  useEffect(() => {
    if (seen !== false) return;

    onboardingService.getSlides().then((data) => {
      if (!data || data.length === 0) {
        localStorage.setItem(STORAGE_KEY, "1");
        setSeen(true);
        return;
      }
      setSlides(data);
      setVisible(true);
    });
  }, [seen]);

  const finish = useCallback(() => {
    setLeaving(true);
    localStorage.setItem(STORAGE_KEY, "1");
    setTimeout(() => {
      setSeen(true);
      setVisible(false);
    }, 400);
  }, []);

  const next = useCallback(() => {
    if (current < slides.length - 1) {
      setCurrent((c) => c + 1);
    } else {
      finish();
    }
  }, [current, slides.length, finish]);

  /* Not yet determined or already seen */
  if (seen !== false || !visible || slides.length === 0) return null;

  const slide = slides[current];
  const isLast = current === slides.length - 1;

  return (
    <>
      <style>{`
        @keyframes onboarding-fade-in {
          from { opacity: 0; }
          to   { opacity: 1; }
        }
        @keyframes onboarding-slide-up {
          from { opacity: 0; transform: translateY(32px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        .ob-overlay {
          animation: onboarding-fade-in 350ms ease both;
        }
        .ob-overlay.leaving {
          animation: onboarding-fade-in 400ms ease reverse both;
        }
        .ob-content {
          animation: onboarding-slide-up 450ms cubic-bezier(0.22,1,0.36,1) both;
        }
      `}</style>

      <div
        className={`ob-overlay${leaving ? " leaving" : ""}`}
        style={{
          position: "fixed",
          inset: 0,
          zIndex: 9999,
          background: "rgba(0,0,0,0.93)",
          backdropFilter: "blur(12px)",
          WebkitBackdropFilter: "blur(12px)",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          overflowY: "auto",
        }}
      >
        {/* Skip button */}
        <button
          type="button"
          onClick={finish}
          style={{
            position: "absolute",
            top: 20,
            right: 20,
            padding: "6px 14px",
            borderRadius: 99,
            border: "1px solid rgba(255,255,255,0.18)",
            background: "rgba(255,255,255,0.08)",
            color: "rgba(255,255,255,0.7)",
            fontSize: 12,
            fontWeight: 600,
            letterSpacing: "0.05em",
            cursor: "pointer",
            zIndex: 10,
            backdropFilter: "blur(6px)",
          }}
        >
          Skip
        </button>

        {/* Slide container */}
        <div
          key={current}
          className="ob-content"
          style={{
            width: "100%",
            maxWidth: 480,
            padding: "0 24px 40px",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            gap: 0,
          }}
        >
          {/* Image */}
          <div
            style={{
              width: "100%",
              aspectRatio: "4/3",
              borderRadius: 24,
              overflow: "hidden",
              position: "relative",
              marginBottom: 36,
              boxShadow: "0 24px 60px rgba(0,0,0,0.6)",
            }}
          >
            {slide.image ? (
              <Image
                src={slide.image}
                alt={slide.title}
                fill
                className="object-cover"
                unoptimized
                priority
                sizes="480px"
              />
            ) : (
              <div
                style={{
                  position: "absolute",
                  inset: 0,
                  background: "linear-gradient(135deg, rgba(var(--accent-rgb),0.3) 0%, rgba(0,0,0,0.6) 100%)",
                }}
              />
            )}
            {/* Gradient overlay at bottom of image */}
            <div
              style={{
                position: "absolute",
                bottom: 0,
                left: 0,
                right: 0,
                height: "50%",
                background: "linear-gradient(to top, rgba(0,0,0,0.7) 0%, transparent 100%)",
              }}
            />
          </div>

          {/* Text content */}
          <h2
            style={{
              fontSize: 28,
              fontWeight: 900,
              color: "#fff",
              textAlign: "center",
              letterSpacing: "-0.03em",
              lineHeight: 1.2,
              marginBottom: 12,
            }}
          >
            {slide.title}
          </h2>
          <p
            style={{
              fontSize: 15,
              color: "rgba(255,255,255,0.6)",
              textAlign: "center",
              lineHeight: 1.65,
              maxWidth: 360,
              marginBottom: 40,
            }}
          >
            {slide.description}
          </p>

          {/* Dots indicator */}
          <div
            style={{
              display: "flex",
              gap: 8,
              alignItems: "center",
              marginBottom: 32,
            }}
          >
            {slides.map((_, i) => (
              <button
                key={i}
                type="button"
                onClick={() => setCurrent(i)}
                style={{
                  width: i === current ? 24 : 8,
                  height: 8,
                  borderRadius: 99,
                  background:
                    i === current
                      ? "var(--accent, #f5943a)"
                      : "rgba(255,255,255,0.25)",
                  border: "none",
                  padding: 0,
                  cursor: "pointer",
                  transition: "all 300ms cubic-bezier(0.4,0,0.2,1)",
                }}
                aria-label={`Go to slide ${i + 1}`}
              />
            ))}
          </div>

          {/* CTA button */}
          <button
            type="button"
            onClick={next}
            style={{
              width: "100%",
              maxWidth: 320,
              padding: "15px 32px",
              borderRadius: 14,
              border: "none",
              background:
                "linear-gradient(90deg, #c25e10, var(--accent, #f5943a), #f5943a)",
              color: "#fff",
              fontSize: 15,
              fontWeight: 800,
              letterSpacing: "0.04em",
              cursor: "pointer",
              boxShadow: "0 8px 28px rgba(var(--accent-rgb, 245,148,58),0.35)",
              transition: "transform 150ms ease, box-shadow 150ms ease",
            }}
            onMouseDown={(e) =>
              ((e.currentTarget as HTMLButtonElement).style.transform = "scale(0.97)")
            }
            onMouseUp={(e) =>
              ((e.currentTarget as HTMLButtonElement).style.transform = "scale(1)")
            }
          >
            {isLast ? "Get Started" : "Next"}
          </button>
        </div>
      </div>
    </>
  );
}
