'use client';

import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';

/** Shared bits of the forecast page and the forecast type drawer (design forecast.js). */

export function InfoSvg() {
  return (
    <svg className="fc-ico" viewBox="0 0 24 24" aria-hidden>
      <circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" strokeWidth="2" />
      <path d="M12 11v6M12 7.5v.01" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}

export function ExtSvg() {
  return (
    <svg className="fc-ext" viewBox="0 0 24 24" aria-hidden>
      <path
        d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
      />
    </svg>
  );
}

export function SearchSvg() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden>
      <circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" strokeWidth="2" />
      <path d="m20 20-4-4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}

export function UserSvg() {
  return (
    <svg className="fc-ico" style={{ width: 18, height: 18 }} viewBox="0 0 24 24" aria-hidden>
      <circle cx="12" cy="8" r="3.5" fill="none" stroke="currentColor" strokeWidth="2" />
      <path
        d="M5 20c0-4 3-6 7-6s7 2 7 6"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
      />
    </svg>
  );
}

export function TeamSvg() {
  return (
    <svg className="fc-ico" style={{ width: 18, height: 18 }} viewBox="0 0 24 24" aria-hidden>
      <rect
        x="5"
        y="4"
        width="14"
        height="16"
        rx="2"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
      />
      <path d="M9 9h6M9 13h6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}

export function CalSvg() {
  return (
    <svg className="fc-ico fc-cal" viewBox="0 0 24 24" aria-hidden>
      <rect
        x="4"
        y="5"
        width="16"
        height="15"
        rx="2"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
      />
      <path d="M4 10h16M8 3v4M16 3v4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}

export function EyeSvg() {
  return (
    <svg className="fc-ico" viewBox="0 0 24 24" aria-hidden>
      <path
        d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
      />
      <circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" strokeWidth="2" />
    </svg>
  );
}

export const Caret = () => <span className="fc-caret" />;

/**
 * What a tooltip shows besides its text (design forecast.js `info(tip, learn, html)`): a
 * "Learn more." link, the Weighted pipeline header's "How it's calculated", or the goal link.
 */
export type TipKind = 'learn' | 'weighted' | 'goal';

/** The design's `info(tip)`: an (i) whose tooltip the page shows on hover and focus. */
export function Info({ tip, kind }: { tip: string; kind?: TipKind }) {
  return (
    <span
      className="fc-tipi"
      tabIndex={0}
      role="img"
      aria-label={tip}
      data-fc-tip={tip}
      data-fc-tipkind={kind}
    >
      <InfoSvg />
    </span>
  );
}

/**
 * The design's tooltip (`.fc-tip`, `tipShow` / `tipHide`): one per page, fixed 10px under the
 * hovered or focused `[data-fc-tip]`, centred on it within the window. It stays while the
 * pointer is on it (hidden 150ms after leaving), so its links can be clicked; scrolling the page
 * body hides it. Render it once inside the element that holds the (i) icons.
 */
export function TipLayer({
  root,
  onLearn,
  onGoal,
}: {
  root: React.RefObject<HTMLElement | null>;
  onLearn: () => void;
  onGoal: () => void;
}) {
  const [tip, setTip] = useState<{ text: string; kind: string; rect: DOMRect } | null>(null);
  const [pos, setPos] = useState<{ left: number; top: number; ax: number } | null>(null);
  const tipRef = useRef<HTMLDivElement>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => {
    const el = root.current;
    if (!el) return;
    const stop = () => {
      if (timer.current) clearTimeout(timer.current);
      timer.current = null;
    };
    const hideSoon = () => {
      stop();
      timer.current = setTimeout(() => setTip(null), 150);
    };
    const target = (e: Event) =>
      (e.target as HTMLElement | null)?.closest?.('[data-fc-tip]') as HTMLElement | null;
    const over = (e: Event) => {
      const t = target(e);
      if (t) {
        stop();
        setTip({
          text: t.dataset.fcTip ?? '',
          kind: t.dataset.fcTipkind ?? '',
          rect: t.getBoundingClientRect(),
        });
      } else if ((e.target as HTMLElement | null)?.closest?.('.fc-tip')) stop();
    };
    const out = (e: Event) => {
      const t = e.target as HTMLElement | null;
      if (t?.closest?.('[data-fc-tip]') || t?.closest?.('.fc-tip')) hideSoon();
    };
    const focusOut = (e: Event) => {
      if (target(e)) hideSoon();
    };
    const scroll = () => {
      stop();
      setTip(null);
    };
    el.addEventListener('mouseover', over);
    el.addEventListener('focusin', over);
    el.addEventListener('mouseout', out);
    el.addEventListener('focusout', focusOut);
    el.addEventListener('scroll', scroll, true);
    return () => {
      stop();
      el.removeEventListener('mouseover', over);
      el.removeEventListener('focusin', over);
      el.removeEventListener('mouseout', out);
      el.removeEventListener('focusout', focusOut);
      el.removeEventListener('scroll', scroll, true);
    };
  }, [root]);
  useLayoutEffect(() => {
    if (!tip) return setPos(null);
    const w = tipRef.current?.offsetWidth ?? 240;
    const r = tip.rect;
    const left = Math.max(8, Math.min(window.innerWidth - w - 8, r.left + r.width / 2 - w / 2));
    setPos({ left, top: r.bottom + 10, ax: r.left + r.width / 2 - left });
  }, [tip]);
  if (!tip) return null;
  const close = () => setTip(null);
  return (
    <div
      ref={tipRef}
      className="fc-tip"
      role="tooltip"
      style={{
        left: pos?.left ?? 0,
        top: pos?.top ?? 0,
        visibility: pos ? 'visible' : 'hidden',
        ['--fc-ax' as string]: `${pos?.ax ?? 0}px`,
      }}
    >
      {tip.kind === 'weighted' ? (
        <>
          <b>How it’s calculated</b>
          <br />
          Open and closed won deals
          <br />
          weighted by deal probability
        </>
      ) : tip.kind === 'goal' ? (
        <>
          Measure progress by{' '}
          <button
            type="button"
            className="fc-tip__l"
            onClick={() => {
              close();
              onGoal();
            }}
          >
            setting a forecastable revenue goal
          </button>
          .
        </>
      ) : (
        tip.text
      )}
      {tip.kind === 'learn' ? (
        <>
          <br />
          <button type="button" className="fc-tip__l" onClick={onLearn}>
            Learn more.
          </button>
        </>
      ) : null}
    </div>
  );
}

/**
 * A modal layer (`[data-fc-modal]`, design forecast.js `MODAL`): portalled to the body, locks the
 * page scroll (`fc-lock`), closes on Escape and returns focus to what opened it.
 */
export function FcLayer({
  onClose,
  children,
  focus,
}: {
  onClose: () => void;
  children: React.ReactNode;
  /** A selector inside the layer to focus first. */
  focus?: string;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const close = useRef(onClose);
  close.current = onClose;
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  useEffect(() => {
    if (!mounted) return;
    const last = document.activeElement as HTMLElement | null;
    const html = document.documentElement;
    html.classList.add('fc-lock');
    document.body.classList.add('fc-lock');
    const el = ref.current;
    const first =
      (focus && el?.querySelector<HTMLElement>(focus)) ||
      el?.querySelector<HTMLElement>('input, select, textarea, button');
    first?.focus();
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.stopPropagation();
        close.current();
      }
    };
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('keydown', onKey);
      html.classList.remove('fc-lock');
      document.body.classList.remove('fc-lock');
      if (last?.isConnected) last.focus();
    };
    // Focus once, when the layer opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mounted]);
  if (!mounted) return null;
  return createPortal(
    <div data-fc-modal="" ref={ref}>
      {children}
    </div>,
    document.body,
  );
}

/** Closes a menu when a press lands outside `selector` (the design's `.fc-pos` menus). */
export function useOutsideClose(active: boolean, selector: string, onClose: () => void) {
  const fn = useRef(onClose);
  fn.current = onClose;
  useEffect(() => {
    if (!active) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as HTMLElement | null;
      if (t?.closest?.(selector)) return;
      fn.current();
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') fn.current();
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [active, selector]);
}
