"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import Icon from "@/components/ui/Icon";
import Photo from "@/components/ui/Photo";
import Reveal from "@/components/ui/Reveal";
import { useHomeDestinations } from "@/store/home";
import { useAuth } from "@/store/auth";
import { useRouter } from "next/navigation";

export default function Destinations() {
  const { items, status, load } = useHomeDestinations();
  useEffect(() => {
    if (status === "idle") void load();
  }, [status, load]);

  const pending = status === "idle" || status === "loading";
  const destinations = items.map((d) => ({ id: String(d.id), name: d.name, region: d.city?.name ?? "", photo: d.name, desc: d.description ?? "", src: d.cover?.url ?? null, href: `/explore/place?kind=destination&id=${d.id}`, rid: d.reviewable_id ?? null }));
  const rail = useRef<HTMLDivElement>(null);
  const router = useRouter();
  const authStatus = useAuth((s) => s.status);
  const favorites = useAuth((s) => s.favorites);
  const toggleFavorite = useAuth((s) => s.toggleFavorite);
  // Signed-out visitors are sent to login and land back on this section.
  const save = (rid: number) => (authStatus === "user" ? void toggleFavorite(rid) : router.push("/login?next=%2F%23destinations"));
  const [edge, setEdge] = useState({ start: true, end: false });

  const measure = useCallback(() => {
    const el = rail.current;
    if (!el) return;
    setEdge({ start: el.scrollLeft < 8, end: el.scrollLeft + el.clientWidth >= el.scrollWidth - 8 });
  }, []);

  useEffect(() => {
    measure();
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, [measure]);

  const step = (dir: 1 | -1) => {
    const el = rail.current;
    if (!el) return;
    const card = el.querySelector<HTMLElement>(".dcard");
    el.scrollBy({ left: dir * ((card?.offsetWidth ?? 320) + 24), behavior: "smooth" });
  };

  if (!pending && destinations.length === 0) return null;

  return (
    <section className="dest" id="destinations">
      <div className="wrap">
        <div className="dest-head">
          <Reveal>
            <span className="eyebrow">Destinations</span>
            <h2 className="h2">Places worth experiencing</h2>
          </Reveal>
          <div className="rail-ctrl">
            <button className="btn btn-icon" aria-label="Previous destinations" onClick={() => step(-1)} disabled={edge.start}>
              <Icon name="arrow_back" />
            </button>
            <button className="btn btn-icon" aria-label="Next destinations" onClick={() => step(1)} disabled={edge.end}>
              <Icon name="arrow_forward" />
            </button>
          </div>
        </div>
      </div>

      <div className="rail" ref={rail} onScroll={measure} tabIndex={0} aria-label="Destinations">
        {pending && [0, 1, 2].map((i) => (
          <article className="dcard" key={i} aria-hidden="true">
            <div className="dcard-img"><span className="skel skel-fill" /></div>
            <div className="dcard-body">
              <span className="skel skel-line w-40" />
              <span className="skel skel-line w-70" />
              <span className="skel skel-line" />
            </div>
          </article>
        ))}
        {destinations.map((d, i) => (
          <Reveal as="article" className="dcard" key={d.id} delay={i * 0.07}>
            <div className="dcard-img">
              <Photo src={d.src} label={d.photo} alt={d.name} />
              {d.rid !== null && (
                <button
                  type="button"
                  className="save"
                  aria-label={favorites.has(d.rid) ? `Remove ${d.name} from saved` : `Save ${d.name}`}
                  aria-pressed={favorites.has(d.rid)}
                  disabled={authStatus === "unknown"}
                  onClick={() => save(d.rid as number)}
                >
                  <Icon name="favorite" filled={favorites.has(d.rid)} />
                </button>
              )}
            </div>
            <div className="dcard-body">
              <span className="eyebrow">{d.region}</span>
              <h3>{d.name}</h3>
              <p>{d.desc}</p>
              <a className="link-arrow" href={d.href}>
                Explore <Icon name="arrow_forward" />
              </a>
            </div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}
