"use client";

import { useEffect, useId, useRef, useState } from "react";
import Link from "next/link";
import { SectionIcon } from "./icons";
import type { HeroVideoData } from "./HeroVideo.schema";

interface FieldState {
  value: string;
  label: string;
}

interface HeroVideoProps {
  data: HeroVideoData;
  /** Active locale, injected by the server shim so SSR renders with the right
   *  arrow direction and internal-link prefixes from first paint. */
  locale?: "ar" | "en";
}

export function HeroVideo({ data, locale = "ar" }: HeroVideoProps) {
  const formId = useId();
  const [openField, setOpenField] = useState<string | null>(null);
  const [selections, setSelections] = useState<Record<string, FieldState>>({});
  const formRef = useRef<HTMLFormElement | null>(null);

  const forwardArrow: "arrow-left" | "arrow-right" = locale === "en" ? "arrow-right" : "arrow-left";

  const localizeIfInternal = (href: string): string => {
    if (locale !== "en") return href;
    if (!href.startsWith("/") || href.startsWith("//")) return href;
    return `/en${href === "/" ? "" : href}`;
  };

  useEffect(() => {
    const onClick = (event: MouseEvent) => {
      if (!formRef.current?.contains(event.target as Node)) setOpenField(null);
    };
    window.addEventListener("click", onClick);
    return () => window.removeEventListener("click", onClick);
  }, []);

  const stripFields = data.search_strip?.enabled ? data.search_strip.fields : [];

  return (
    <section className="hero-video" data-screen-label="01 Hero Video">
      {data.video_url ? (
        <video autoPlay muted loop playsInline preload="metadata">
          <source src={data.video_url} type="video/mp4" />
        </video>
      ) : null}
      <div className="video-fallback" aria-hidden="true" />
      <div className="ovl ovl-dark" />
      <div className="ovl ovl-brand" />
      <div className="ovl ovl-grain" />
      <div className="ovl ovl-bottom" />

      <div className="hero-content">
        {(data.kicker_en_brand || data.kicker_en_tagline) && (
          <span className="hero-eyebrow anim-up">
            <span className="pip" />
            <span className="en">
              {data.kicker_en_brand}
              {data.kicker_en_brand.endsWith(".") ? null : <span>.</span>}
            </span>
            {data.kicker_en_tagline ? <span>{data.kicker_en_tagline}</span> : null}
          </span>
        )}
        {(data.title_line_1 || data.title_line_2_accent) && (
          <h1 className="hero-title anim-up d1">
            {data.title_line_1}
            {data.title_line_2_accent ? (
              <>
                <br />
                <span className="accent">{data.title_line_2_accent}</span>
              </>
            ) : null}
          </h1>
        )}
        {data.subtitle ? <p className="hero-sub anim-up d2">{data.subtitle}</p> : null}

        <div className="hero-ctas anim-up d3">
          {data.primary_cta?.label ? (
            <a href={localizeIfInternal(data.primary_cta.href)} className="btn btn-primary btn-lg">
              {data.primary_cta.label}
              {data.primary_cta.icon === "arrow-left" || data.primary_cta.icon === "arrow-right" ? (
                <SectionIcon name={data.primary_cta.icon} size={18} />
              ) : null}
            </a>
          ) : null}
          {data.secondary_cta?.label ? (
            data.secondary_cta.href.startsWith("/") ? (
              <Link href={localizeIfInternal(data.secondary_cta.href)} className="btn btn-glass btn-lg">
                {data.secondary_cta.label}
              </Link>
            ) : (
              <a href={data.secondary_cta.href} className="btn btn-glass btn-lg">
                {data.secondary_cta.label}
              </a>
            )
          ) : null}
        </div>

        {data.badges.length > 0 ? (
          <div className="hero-badges anim-up d4">
            {data.badges.map((badge, i) => (
              <span key={i} className="b">
                <SectionIcon name={badge.icon} size={14} />
                {badge.label}
              </span>
            ))}
          </div>
        ) : null}
      </div>

      <div className="hero-scroll">
        <span>{data.scroll_label}</span>
        <span className="line" />
      </div>

      {data.search_strip?.enabled && stripFields.length > 0 ? (
        <div className="hero-strip-wrap">
          <form
            ref={formRef}
            className="hero-strip"
            id={formId}
            action={data.search_strip.submit_href}
            method="get"
          >
            {stripFields.map((field) => {
              const selected = selections[field.key];
              const isOpen = openField === field.key;
              return (
                <div
                  key={field.key}
                  className={`seg${isOpen ? " is-open" : ""}${selected ? " has-value" : ""}`}
                  data-field={field.key}
                  role="button"
                  tabIndex={0}
                  aria-haspopup="listbox"
                  aria-expanded={isOpen}
                  onClick={(e) => {
                    e.stopPropagation();
                    setOpenField((cur) => (cur === field.key ? null : field.key));
                  }}
                >
                  <span className="lab">{field.label}</span>
                  <div className="v">
                    <span className="txt">{selected?.label || field.placeholder}</span>
                    <svg className="chev" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="6 9 12 15 18 9" />
                    </svg>
                  </div>
                  <input type="hidden" name={field.key} value={selected?.value || ""} />
                  {isOpen ? (
                    <div className="hero-pop" role="listbox" aria-label={field.label}>
                      {field.options.map((opt) => (
                        <button
                          key={opt.value}
                          type="button"
                          data-val={opt.value}
                          data-label={opt.label}
                          onClick={(e) => {
                            e.stopPropagation();
                            setSelections((prev) => ({ ...prev, [field.key]: { value: opt.value, label: opt.label } }));
                            setOpenField(null);
                          }}
                        >
                          <SectionIcon name={opt.icon} size={18} />
                          <span>
                            {opt.label}
                            {opt.meta ? <span className="meta">{opt.meta}</span> : null}
                          </span>
                        </button>
                      ))}
                    </div>
                  ) : null}
                </div>
              );
            })}
            <button type="submit" className="go">
              {data.search_strip.submit_label}
              <SectionIcon name={forwardArrow} size={16} />
            </button>
          </form>
        </div>
      ) : null}
    </section>
  );
}

// Registration moved to HeroVideo.register.ts — see that file for why.
