"use client";

import { useEffect, useState } from "react";
import { ArrowUpRight, ChevronLeft, ChevronRight, Play, Quote } from "lucide-react";
import { AiImage } from "@/components/AiImage";
import { useHomeSettings } from "@/components/HomeProvider";
import { homeImageUrl, tikTokEmbedSrc } from "@/lib/home-api";
import { aiImage } from "@/lib/pollinations";

function openContact() {
  window.dispatchEvent(new CustomEvent("vnsails:open-contact"));
}

export function Specialists() {
  const { home } = useHomeSettings();
  const section = home.sections.specialists || {};
  const specialists = home.specialists?.length ? home.specialists : [];
  const [active, setActive] = useState(0);
  const [playing, setPlaying] = useState(false);
  const person = specialists[active] ?? specialists[0];

  useEffect(() => {
    setPlaying(false);
  }, [active]);

  if (!person) return null;

  const prev = () => setActive((i) => (i - 1 + specialists.length) % specialists.length);
  const next = () => setActive((i) => (i + 1) % specialists.length);

  const portrait = (name: string, image: string | null, seed: number) => {
    if (image) return homeImageUrl(image);
    return aiImage(
      `professional Vietnamese travel consultant portrait ${name} warm smile white outfit studio teal background`,
      { width: 640, height: 800, seed },
    );
  };

  const tiktokUrl = (person.tiktok_url || "").trim();
  const embedSrc = tiktokUrl ? tikTokEmbedSrc(tiktokUrl) : null;
  const showVideo = playing && Boolean(tiktokUrl);

  const onPlay = () => {
    if (!tiktokUrl) {
      openContact();
      return;
    }
    setPlaying(true);
  };

  return (
    <section id="about" className="pt-6 pb-14 sm:pt-8 sm:pb-16">
      <div className="container-page">
        <div className="relative overflow-hidden rounded-[28px] bg-[#d9ecec]">
          <div className="pointer-events-none absolute inset-0">
            <AiImage
              src={aiImage(
                "soft aerial Ha Long Bay emerald water limestone islands misty atmospheric background no text",
                { width: 1600, height: 700, seed: 777 },
              )}
              alt=""
              className="h-full w-full opacity-45"
            />
            <div className="absolute inset-0 bg-[linear-gradient(105deg,rgba(126,200,196,0.88)_0%,rgba(126,200,196,0.55)_38%,rgba(255,255,255,0.15)_72%,rgba(255,255,255,0.05)_100%)]" />
          </div>

          <div className="relative grid gap-8 px-5 py-8 sm:px-8 sm:py-10 lg:grid-cols-[0.85fr_1.35fr] lg:items-center lg:gap-10 lg:px-12 lg:py-12">
            <div className="max-w-md">
              <h2 className="font-[family-name:var(--font-display)] text-[1.75rem] leading-tight font-bold text-[#1c2b33] sm:text-3xl lg:text-[2.1rem]">
                {section.title || "Our Local Travel Specialists"}
              </h2>
              {section.description ? (
                <p className="mt-3 text-sm leading-relaxed text-[#1c2b33]/80 sm:text-[15px]">
                  {section.description}
                </p>
              ) : null}
              <button
                type="button"
                onClick={openContact}
                className="mt-6 inline-flex items-center gap-2 rounded-xl bg-white px-5 py-3 text-sm font-bold text-accent shadow-[0_8px_24px_rgba(13,58,77,0.08)] transition hover:bg-[#f7fbfb]"
              >
                {section.cta || "Contact Now"}
                <ArrowUpRight className="h-4 w-4" strokeWidth={2.4} />
              </button>
            </div>

            <div className="flex flex-col gap-3 sm:flex-row sm:items-stretch">
              <article className="flex min-w-0 flex-1 overflow-hidden rounded-[22px] bg-white shadow-[0_16px_40px_rgba(13,58,77,0.12)]">
                <div className="flex min-w-0 flex-1 flex-col justify-between gap-5 p-4 sm:p-5 lg:p-6">
                  <div>
                    <Quote
                      className="h-8 w-8 text-[#7ec8c4]/80"
                      fill="currentColor"
                      strokeWidth={0}
                    />
                    <p className="mt-3 text-sm leading-relaxed text-[#1c2b33]/85 sm:text-[15px]">
                      {person.quote}
                    </p>
                    <div className="mt-5">
                      <h3 className="text-base font-bold text-[#1c2b33]">{person.name}</h3>
                      <p className="text-sm text-muted">{person.role}</p>
                    </div>
                  </div>

                  <div className="flex flex-wrap items-center gap-3">
                    <button
                      type="button"
                      onClick={openContact}
                      className="inline-flex items-center gap-2 rounded-xl bg-accent px-4 py-2.5 text-sm font-bold text-white transition hover:bg-accent-hover"
                    >
                      Chat With Us
                      <ArrowUpRight className="h-4 w-4" strokeWidth={2.4} />
                    </button>
                    <div className="flex items-center gap-2">
                      <button
                        type="button"
                        onClick={prev}
                        aria-label="Previous specialist"
                        className="grid h-9 w-9 place-items-center rounded-full border border-[var(--line)] text-brand-deep transition hover:border-accent hover:text-accent"
                      >
                        <ChevronLeft className="h-4 w-4" />
                      </button>
                      <button
                        type="button"
                        onClick={next}
                        aria-label="Next specialist"
                        className="grid h-9 w-9 place-items-center rounded-full border border-[var(--line)] text-brand-deep transition hover:border-accent hover:text-accent"
                      >
                        <ChevronRight className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                </div>

                <div className="relative hidden w-[42%] shrink-0 overflow-hidden bg-black sm:block">
                  {showVideo ? (
                    embedSrc ? (
                      <iframe
                        key={`${person.name}-${embedSrc}`}
                        src={`${embedSrc}?lang=en`}
                        title={`TikTok — ${person.name}`}
                        className="absolute inset-0 h-full min-h-[280px] w-full bg-black"
                        allow="encrypted-media; fullscreen; accelerometer; autoplay; clipboard-write; gyroscope; picture-in-picture"
                        allowFullScreen
                      />
                    ) : (
                      <div className="absolute inset-0 flex min-h-[280px] flex-col items-center justify-center gap-3 bg-[#111] px-4 text-center">
                        <p className="text-xs text-white/80">Cannot embed this TikTok link.</p>
                        <a
                          href={tiktokUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex h-9 items-center justify-center rounded-full bg-accent px-4 text-xs font-semibold text-white"
                        >
                          Open on TikTok
                        </a>
                      </div>
                    )
                  ) : (
                    <>
                      <AiImage
                        src={portrait(person.name, person.image, 601 + active)}
                        alt={person.name}
                        className="h-full min-h-[280px] w-full"
                      />
                      <button
                        type="button"
                        onClick={onPlay}
                        aria-label={
                          tiktokUrl
                            ? `Play TikTok intro from ${person.name}`
                            : `Watch intro from ${person.name}`
                        }
                        className="absolute right-3 bottom-3 grid h-11 w-11 place-items-center rounded-full bg-accent text-white shadow-lg transition hover:bg-accent-hover"
                      >
                        <Play className="h-4 w-4 fill-current" strokeWidth={0} />
                      </button>
                    </>
                  )}
                </div>
              </article>

              <div className="flex gap-2 overflow-x-auto sm:w-[88px] sm:shrink-0 sm:flex-col sm:overflow-visible">
                {specialists.map((item, index) => {
                  const selected = index === active;
                  return (
                    <button
                      key={`${item.name}-${index}`}
                      type="button"
                      onClick={() => setActive(index)}
                      aria-label={`View ${item.name}`}
                      aria-pressed={selected}
                      className={`relative h-[72px] w-[72px] shrink-0 overflow-hidden rounded-2xl bg-[#7ec8c4] transition sm:h-[78px] sm:w-full ${
                        selected
                          ? "ring-2 ring-accent ring-offset-2"
                          : "opacity-90 hover:opacity-100"
                      }`}
                    >
                      <AiImage
                        src={portrait(item.name, item.image, 601 + index)}
                        alt={item.name}
                        className="h-full w-full"
                      />
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
