"use client";

import { useCallback, useLayoutEffect, useRef, useState } from "react";
import { ChevronLeft, ChevronRight, MousePointerClick, X } from "lucide-react";
import { cn } from "@/shared/lib/utils";
import { useT } from "@/shared/i18n/client";
import { AnnouncementIcon } from "@/presentation/components/announcements/announcement-badges";
import { RichTextView } from "@/presentation/components/announcements/form-controls";
import { chipOnBackground, isMenuGroup, textOnBackground } from "@/shared/lib/announcements";
import type {
  AnnouncementAnchor,
  AnnouncementCatalogs,
  AnnouncementInput,
  AnnouncementPlacement,
  LocalizedText,
} from "@/domain/entities/announcement";

type Lang = "fr" | "en";
interface Box { top: number; left: number; width: number; height: number }

const TIP_W = 210;

/**
 * Approximate rendering of the announcement in a miniature Fleet screen (spec §7.1). It uses
 * the real catalogs (menu entries, the page's elements) so tours and badges point at the element
 * chosen in the editor. The real rendering is the Fleet preview.
 */
export function AnnouncementSimulation({
  input,
  catalogs,
  stepIndex: controlledStep,
  onStepIndexChange,
  onPickAnchor,
}: {
  input: AnnouncementInput;
  catalogs: AnnouncementCatalogs;
  /** The step shown, when the editor drives it (the step being edited). */
  stepIndex?: number;
  onStepIndexChange?: (index: number) => void;
  /** Click an element of the preview to attach the shown step to it. */
  onPickAnchor?: (anchorKey: string) => void;
}) {
  const t = useT();
  const sim = t.announcements.simulation;
  const [lang, setLang] = useState<Lang>("fr");
  const [localStep, setLocalStep] = useState(0);
  const stepIndex = controlledStep ?? localStep;
  const setStepIndex = (i: number) => (onStepIndexChange ? onStepIndexChange(i) : setLocalStep(i));
  // Closed for this placement only: changing the format or the element shows it again.
  const [dismissedFor, setDismissedFor] = useState<string | null>(null);
  const frameRef = useRef<HTMLDivElement>(null);
  const anchors = useRef(new Map<string, HTMLElement>());
  const [geo, setGeo] = useState<{ box: Box | null; w: number; h: number }>({ box: null, w: 0, h: 0 });

  const steps = input.steps;
  const index = Math.min(stepIndex, Math.max(0, steps.length - 1));
  const step = steps[index];
  const placementKey = `${input.format}|${input.anchor_key}|${input.page_key}`;
  const dismissed = dismissedFor === placementKey;
  const setDismissed = (value: boolean) => setDismissedFor(value ? placementKey : null);
  const usesSteps = input.format === "page_widget" || input.format === "tour";
  const picking = !!onPickAnchor && usesSteps && steps.length > 0;
  /** Props that make an element of the preview clickable to attach the shown step to it. */
  const pickable = (key: string, label: string) =>
    picking
      ? {
          role: "button" as const,
          tabIndex: 0,
          title: sim.pickTitle(label, index + 1),
          onClick: () => onPickAnchor!(key),
          onKeyDown: (ev: React.KeyboardEvent) => {
            if (ev.key === "Enter" || ev.key === " ") {
              ev.preventDefault();
              onPickAnchor!(key);
            }
          },
        }
      : {};
  const targetKey = usesSteps ? step?.anchor_key ?? null : input.format === "badge" || input.format === "sidebar_spotlight" ? input.anchor_key : null;

  const pageKey =
    input.page_key ??
    catalogs.anchors.find((a) => a.key === input.anchor_key)?.page_key ??
    (input.format === "banner" || input.format === "modal" ? null : "dashboard");
  const page = catalogs.pages.find((p) => p.key === pageKey);
  // The first ones of a list, plus the one pointed at when it comes later (a menu group, a tab
  // further down): the element of the shown step is always drawn.
  const withTarget = (list: AnnouncementAnchor[], max: number, pool: AnnouncementAnchor[]) => {
    const shown = list.slice(0, max);
    const target = pool.find((a) => a.key === targetKey);
    return target && !shown.includes(target) ? [...shown, target] : shown;
  };
  const pageAnchors = pageKey ? catalogs.anchors.filter((a) => a.page_key === pageKey) : [];
  const pageElements = withTarget(pageAnchors, 12, pageAnchors);
  const menuAnchors = catalogs.anchors.filter((a) => a.page_key === null);
  const menu = withTarget(menuAnchors.filter((a) => !isMenuGroup(a.key)), 8, menuAnchors);

  const text = (v: LocalizedText) => (v[lang]?.trim() ? v[lang] : v.fr);
  const title = text(input.title) || sim.placeholderTitle;

  const register = useCallback((key: string) => (el: HTMLElement | null) => {
    if (el) anchors.current.set(key, el);
    else anchors.current.delete(key);
  }, []);

  // Measure the targeted element relative to the frame.
  useLayoutEffect(() => {
    const measure = () => {
      const frame = frameRef.current;
      if (!frame) return;
      const el = targetKey ? anchors.current.get(targetKey) : undefined;
      const f = frame.getBoundingClientRect();
      const r = el?.getBoundingClientRect();
      setGeo({
        box: r ? { top: r.top - f.top, left: r.left - f.left, width: r.width, height: r.height } : null,
        w: frame.clientWidth,
        h: frame.clientHeight,
      });
    };
    measure();
    const ro = new ResizeObserver(measure);
    if (frameRef.current) ro.observe(frameRef.current);
    return () => ro.disconnect();
  }, [targetKey, pageKey, input.format, index, lang]);

  const isTarget = (key: string) => key === targetKey;
  const showOverlay = !dismissed;

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between gap-2">
        <p className="text-[11px] text-muted-foreground">{t.announcements.panel.approx}</p>
        <div className="inline-flex rounded-md border p-0.5" role="group" aria-label={t.announcements.panel.lang}>
          {(["fr", "en"] as const).map((l) => (
            <button
              key={l}
              type="button"
              aria-pressed={lang === l}
              onClick={() => setLang(l)}
              className={cn("rounded px-2 py-0.5 text-[11px] font-semibold", lang === l ? "bg-blue-600 text-white" : "text-muted-foreground")}
            >
              {l.toUpperCase()}
            </button>
          ))}
        </div>
      </div>

      {picking && (
        <p className="flex items-center gap-1.5 rounded-md bg-blue-50 px-2 py-1.5 text-[11px] text-blue-900">
          <MousePointerClick className="h-3.5 w-3.5 shrink-0" />
          {sim.pickHint(index + 1)}
        </p>
      )}
      <div ref={frameRef} className="relative h-[440px] overflow-hidden rounded-xl border bg-slate-50 text-[11px] shadow-inner select-none">
        <div className="absolute inset-y-0 left-0 w-[30%] space-y-0.5 bg-[#0f2a5c] p-2 text-white/80">
          <div className="mb-2 flex items-center gap-1.5 px-1 py-1 text-[11px] font-bold text-white">
            <span className="h-4 w-4 rounded bg-blue-500" />
            Dadycar Fleet
          </div>
          {menu.map((m) => (
            <div
              key={m.key}
              ref={register(m.key)}
              {...pickable(m.key, m.label)}
              className={cn(
                "relative truncate rounded px-1.5 py-1",
                picking && "cursor-pointer outline-none hover:bg-white/10 hover:ring-2 hover:ring-blue-300 focus-visible:ring-2 focus-visible:ring-blue-300",
                m.key === `sidebar.${pageKey}` && "bg-white/15 text-white",
                isTarget(m.key) && showOverlay && "ring-2 ring-amber-400",
                isTarget(m.key) && showOverlay && input.format === "badge" && "pr-12",
              )}
            >
              {m.label}
              {input.format === "badge" && isTarget(m.key) && showOverlay && <BadgeDot inline label={text(input.badge_text) || "Nouveau"} />}
            </div>
          ))}
        </div>

        <div className="absolute inset-y-0 left-[30%] right-0 flex flex-col">
          {input.format === "banner" && showOverlay && (
            <div
              className="flex items-start gap-2 border-b border-teal-200 bg-teal-50 px-3 py-2 text-teal-900"
              style={input.background_color ? { backgroundColor: input.background_color, borderColor: input.background_color, color: textOnBackground(input.background_color) } : undefined}
            >
              <AnnouncementIcon name={input.icon} className="mt-0.5 h-3.5 w-3.5 shrink-0" />
              <div className="min-w-0 flex-1 leading-snug">
                {text(input.badge_text) && <span className="mr-1.5 rounded bg-teal-600 px-1 py-px text-[9px] font-bold text-white" style={chipOnBackground(input.background_color)}>{text(input.badge_text)}</span>}
                <b>{title}</b>{" "}
                <RichTextView html={text(input.body) || sim.placeholderBody} />
                {text(input.cta_label) && <span className="ml-1.5 font-semibold underline">{text(input.cta_label)}</span>}
              </div>
              {input.rules.dismissible && <CloseButton onClick={() => setDismissed(true)} label={sim.close} />}
            </div>
          )}
          <div className="border-b bg-white px-3 py-2">
            <div className="text-[12px] font-semibold text-slate-800">{page?.label ?? sim.allPages}</div>
          </div>
          <div className="flex-1 space-y-2 p-3">
            <div className="flex flex-wrap gap-1.5">
              {pageElements.map((el) => (
                <div
                  key={el.key}
                  ref={register(el.key)}
                  {...pickable(el.key, el.label)}
                  className={cn(
                    "relative rounded-md border bg-white px-2 py-1.5 text-slate-600 shadow-xs",
                    picking && "cursor-pointer outline-none hover:border-blue-400 hover:ring-2 hover:ring-blue-300 focus-visible:ring-2 focus-visible:ring-blue-300",
                    isTarget(el.key) && showOverlay && "border-amber-400 ring-2 ring-amber-400",
                  )}
                >
                  {el.label}
                  {input.format === "badge" && isTarget(el.key) && showOverlay && <BadgeDot label={text(input.badge_text) || "Nouveau"} />}
                </div>
              ))}
            </div>
            <div className="grid grid-cols-3 gap-2">
              {[0, 1, 2].map((i) => (
                <div key={i} className="h-12 rounded-md border bg-white" />
              ))}
            </div>
            <div className="space-y-1.5 rounded-md border bg-white p-2">
              {[0, 1, 2, 3].map((i) => (
                <div key={i} className="h-3 rounded bg-slate-100" style={{ width: `${90 - i * 12}%` }} />
              ))}
            </div>
          </div>
        </div>

        {/* Popover next to an element: menu spotlight, tour step. */}
        {showOverlay && (input.format === "sidebar_spotlight" || (input.format === "tour" && step)) && (
          <Tooltip
            box={geo.box}
            frameWidth={geo.w}
            frameHeight={geo.h}
            placement={input.format === "tour" ? step?.placement ?? "auto" : input.placement}
            icon={input.format === "tour" ? step?.icon ?? input.icon : input.icon}
            title={input.format === "tour" && step ? text(step.title) || title : title}
            body={input.format === "tour" && step ? text(step.body) : text(input.body)}
            cta={input.format === "tour" && step ? text(step.cta_label) : text(input.cta_label)}
            onClose={() => setDismissed(true)}
            closeLabel={sim.close}
            nav={
              input.format === "tour" && steps.length > 1 ? (
                <StepNav index={index} count={steps.length} onChange={setStepIndex} onDone={() => setDismissed(true)} />
              ) : null
            }
          />
        )}

        {/* Step card in a corner. */}
        {showOverlay && input.format === "page_widget" && step && (
          <div
            className={cn(
              "absolute bottom-3 w-[230px] rounded-xl border bg-white p-3 shadow-xl",
              input.widget_corner === "bottom_left" ? "left-[calc(30%+12px)]" : "right-3",
            )}
          >
            <div className="mb-1 flex items-center justify-between">
              <span className="text-[10px] font-semibold text-orange-600">{sim.stepOf(index + 1, steps.length)}</span>
              <CloseButton onClick={() => setDismissed(true)} label={sim.close} />
            </div>
            {step.media_url && (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={step.media_url} alt={text(step.media_alt)} className="mb-1.5 h-16 w-full rounded object-cover" />
            )}
            <div className="flex items-center gap-1.5 text-[12px] font-semibold text-slate-900">
              <AnnouncementIcon name={step.icon ?? input.icon} className="h-3.5 w-3.5 text-orange-500" />
              {text(step.title) || title}
            </div>
            {text(step.subtitle) && <div className="text-[10px] text-slate-500">{text(step.subtitle)}</div>}
            <p className="mt-1 leading-snug text-slate-600"><RichTextView html={text(step.body) || sim.placeholderBody} /></p>
            {text(step.cta_label) && <div className="mt-1.5 text-[10px] font-semibold text-blue-600 underline">{text(step.cta_label)}</div>}
            <StepNav index={index} count={steps.length} onChange={setStepIndex} onDone={() => setDismissed(true)} />
          </div>
        )}

        {/* Modal. */}
        {showOverlay && input.format === "modal" && (
          <div className="absolute inset-0 flex items-center justify-center bg-slate-900/40 p-6">
            <div className="relative w-[78%] max-w-[300px] overflow-hidden rounded-xl bg-white shadow-2xl">
              <div className="absolute right-2 top-2 z-10 rounded-full bg-white/80">
                <CloseButton onClick={() => setDismissed(true)} label={sim.close} />
              </div>
              {input.media_url && (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={input.media_url} alt={text(input.media_alt)} className="h-28 w-full object-cover" />
              )}
              <div className="space-y-1.5 p-3">
                <div className="flex items-center gap-1.5">
                  <AnnouncementIcon name={input.icon} className="h-4 w-4 text-rose-500" />
                  {text(input.badge_text) && <span className="rounded bg-rose-500 px-1 py-px text-[9px] font-bold text-white">{text(input.badge_text)}</span>}
                </div>
                <div className="text-[13px] font-bold text-slate-900">{title}</div>
                <p className="leading-snug text-slate-600"><RichTextView html={text(input.body) || sim.placeholderBody} /></p>
                {text(input.cta_label) && (
                  <div className="mt-1 inline-block rounded-md bg-blue-600 px-2.5 py-1 text-[11px] font-semibold text-white">{text(input.cta_label)}</div>
                )}
              </div>
            </div>
          </div>
        )}

        {dismissed && (
          <button
            type="button"
            onClick={() => {
              setDismissed(false);
              setStepIndex(0);
            }}
            className="absolute bottom-2 left-1/2 -translate-x-1/2 rounded-full border bg-white px-3 py-1 text-[11px] font-medium shadow hover:bg-slate-50"
          >
            ↺ {sim.replay}
          </button>
        )}
      </div>
    </div>
  );
}

/** The "new" mark: inside a menu row (whose overflow is hidden), or on the corner of an element. */
function BadgeDot({ label, inline }: { label: string; inline?: boolean }) {
  return (
    <span
      className={cn(
        "absolute rounded-full bg-violet-600 px-1.5 py-px text-[8px] font-bold uppercase tracking-wide text-white shadow",
        inline ? "right-1 top-1/2 -translate-y-1/2" : "-right-1.5 -top-1.5",
      )}
    >
      {label}
    </span>
  );
}

function CloseButton({ onClick, label }: { onClick: () => void; label: string }) {
  return (
    <button type="button" onClick={onClick} className="rounded p-0.5 text-slate-400 hover:text-slate-700" aria-label={label}>
      <X className="h-3 w-3" />
    </button>
  );
}

function StepNav({ index, count, onChange, onDone }: { index: number; count: number; onChange: (i: number) => void; onDone: () => void }) {
  const t = useT();
  const sim = t.announcements.simulation;
  const last = index >= count - 1;
  return (
    <div className="mt-2 flex items-center justify-between">
      <div className="flex gap-1">
        {Array.from({ length: count }, (_, i) => (
          <span key={i} className={cn("h-1.5 w-1.5 rounded-full", i === index ? "bg-blue-600" : "bg-slate-300")} />
        ))}
      </div>
      <div className="flex items-center gap-1">
        {index > 0 && (
          <button type="button" onClick={() => onChange(index - 1)} className="flex items-center rounded px-1.5 py-0.5 text-[10px] text-slate-500 hover:bg-slate-100">
            <ChevronLeft className="h-3 w-3" />
            {sim.previous}
          </button>
        )}
        <button
          type="button"
          onClick={() => (last ? onDone() : onChange(index + 1))}
          className="flex items-center rounded bg-blue-600 px-1.5 py-0.5 text-[10px] font-semibold text-white"
        >
          {last ? sim.done : sim.next}
          {!last && <ChevronRight className="h-3 w-3" />}
        </button>
      </div>
    </div>
  );
}

function Tooltip({
  box,
  frameWidth: W,
  frameHeight: H,
  placement,
  icon,
  title,
  body,
  cta,
  onClose,
  closeLabel,
  nav,
}: {
  box: Box | null;
  frameWidth: number;
  frameHeight: number;
  placement: AnnouncementPlacement;
  icon: string | null;
  title: string;
  body: string;
  cta: string;
  onClose: () => void;
  closeLabel: string;
  nav: React.ReactNode;
}) {
  const t = useT();
  const sim = t.announcements.simulation;
  if (!box || !W) {
    return (
      <div className="pointer-events-none absolute bottom-3 left-[34%] w-[210px] rounded-lg border border-dashed border-amber-400 bg-amber-50 p-2 text-amber-800">
        {sim.elementHere} ?
      </div>
    );
  }
  const side: Exclude<AnnouncementPlacement, "auto"> =
    placement !== "auto" ? placement : box.left + box.width + TIP_W + 12 < W ? "right" : "bottom";
  const gap = 10;
  let top = 0;
  let left = 0;
  if (side === "right") { left = box.left + box.width + gap; top = box.top - 4; }
  if (side === "left") { left = box.left - TIP_W - gap; top = box.top - 4; }
  if (side === "bottom") { left = box.left; top = box.top + box.height + gap; }
  if (side === "top") { left = box.left; top = box.top - gap - 120; }
  left = Math.max(6, Math.min(left, W - TIP_W - 6));
  top = Math.max(6, Math.min(top, H - 140));

  const arrow: Record<typeof side, string> = {
    right: "-left-1 top-3",
    left: "-right-1 top-3",
    bottom: "-top-1 left-4",
    top: "-bottom-1 left-4",
  };

  return (
    <div className="absolute z-10 rounded-lg bg-slate-900 p-2.5 text-white shadow-xl" style={{ top, left, width: TIP_W }} role="dialog" aria-label={title}>
      <span className={cn("absolute h-2 w-2 rotate-45 bg-slate-900", arrow[side])} />
      <div className="flex items-start justify-between gap-2">
        <div className="flex items-center gap-1.5 text-[12px] font-semibold">
          <AnnouncementIcon name={icon} className="h-3.5 w-3.5 text-amber-300" />
          {title}
        </div>
        <button type="button" onClick={onClose} className="text-white/60 hover:text-white" aria-label={closeLabel}>
          <X className="h-3 w-3" />
        </button>
      </div>
      {body && <p className="mt-1 leading-snug text-white/80"><RichTextView html={body} /></p>}
      {cta && <div className="mt-1.5 text-[10px] font-semibold text-amber-300 underline">{cta}</div>}
      {nav && <div className="[&_span.bg-slate-300]:bg-white/30">{nav}</div>}
    </div>
  );
}
