'use client';

/**
 * Shared pieces of the Goals pages (13 Nov design, goals.js): icons, the single-select dropdown
 * (`.gx-dd`), labelled fields (`.gx-f`), notifications checklist, overlays (`.gl-ov`) and the
 * page toast (`.gl-toast`). Markup and class names follow the design.
 */
import { useCallback, useEffect, useRef, useState } from 'react';

// --- icons -------------------------------------------------------------------------------------

export function SearchIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <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 Caret() {
  return <span className="gl-caret" />;
}

export function EyeIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path
        d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12z"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
      />
      <circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" strokeWidth="1.8" />
    </svg>
  );
}

export function SortIcon({ up }: { up: boolean }) {
  return (
    <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true">
      <path
        d={up ? 'M12 19V5m0 0-5 5m5-5 5 5' : 'M12 5v14m0 0-5-5m5 5 5-5'}
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function CopyIcon() {
  return (
    <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true">
      <rect
        x="9"
        y="9"
        width="11"
        height="11"
        rx="1.5"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
      />
      <path
        d="M5 15V5.5A1.5 1.5 0 0 1 6.5 4H15"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
      />
    </svg>
  );
}

export function TrashIcon() {
  return (
    <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true">
      <path
        d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function InfoIcon() {
  return (
    <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true">
      <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>
  );
}

/** The design's `ic(path, size)`: a `.gx-i` stroke icon. */
export function Ic({ size = 16, children }: { size?: number; children: React.ReactNode }) {
  return (
    <svg
      className="gx-i"
      viewBox="0 0 24 24"
      width={size}
      height={size}
      aria-hidden="true"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      {children}
    </svg>
  );
}

export const IExt = () => (
  <Ic size={13}>
    <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" />
  </Ic>
);
export const IInfo = () => (
  <Ic size={14}>
    <circle cx="12" cy="12" r="9" />
    <path d="M12 11v6M12 7.5v.01" />
  </Ic>
);
export const IBulb = () => (
  <Ic size={15}>
    <path d="M9 18h6M10 21h4M12 3a6 6 0 0 0-3.5 10.9c.6.5 1 1.2 1 2.1h5c0-.9.4-1.6 1-2.1A6 6 0 0 0 12 3z" />
  </Ic>
);
export const ITarg = () => (
  <Ic size={15}>
    <circle cx="12" cy="12" r="8" />
    <circle cx="12" cy="12" r="3.2" />
  </Ic>
);
export const ILock = () => (
  <Ic size={13}>
    <rect x="5" y="11" width="14" height="9" rx="2" />
    <path d="M8 11V8a4 4 0 0 1 8 0v3" />
  </Ic>
);
export const IWarn = () => (
  <Ic size={15}>
    <path d="M12 4 3 20h18zM12 10v4M12 17h.01" />
  </Ic>
);
export const IBack = () => (
  <Ic size={12}>
    <path d="m15 6-6 6 6 6" />
  </Ic>
);
export const IFile = () => (
  <Ic size={22}>
    <circle cx="12" cy="12" r="9" />
    <circle cx="12" cy="12" r="3.5" />
  </Ic>
);
export const ISlid = () => (
  <Ic size={17}>
    <path d="M4 7h10M18 7h2M4 17h2M10 17h10" />
    <circle cx="16" cy="7" r="2" />
    <circle cx="8" cy="17" r="2" />
  </Ic>
);
export const ICheck = () => (
  <Ic size={14}>
    <path d="m6 12.5 4 4 8-9" />
  </Ic>
);
export function IKeb() {
  return (
    <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" fill="currentColor">
      <circle cx="12" cy="5" r="1.8" />
      <circle cx="12" cy="12" r="1.8" />
      <circle cx="12" cy="19" r="1.8" />
    </svg>
  );
}

/** Empty / preview illustration (magnifier on a platform). */
export function EmptyArt() {
  return (
    <svg className="gx-art" viewBox="0 0 160 130" aria-hidden="true">
      <path d="M20 98l60-30 60 30-60 26z" fill="#e3ebf6" />
      <ellipse cx="82" cy="96" rx="26" ry="9" fill="none" stroke="#b9c8dc" strokeDasharray="3 3" />
      <path d="M70 92l-12-40M94 92l12-40" stroke="#c9d6e8" strokeWidth="2" />
      <circle cx="82" cy="46" r="22" fill="#eef3fa" stroke="#9fb3cf" strokeWidth="3" />
      <circle cx="82" cy="46" r="14" fill="#fff" stroke="#c9d6e8" strokeWidth="2" />
      <path d="m98 62 14 14" stroke="#9fb3cf" strokeWidth="7" strokeLinecap="round" />
      <path
        d="M112 30l6-4M116 40l8 0M110 22l2-7"
        stroke="#b9c8dc"
        strokeWidth="2"
        strokeLinecap="round"
      />
    </svg>
  );
}

/** "Create a goal template" illustration. */
export function TemplateArt({ stroke = '#3b4a5a' }: { stroke?: string }) {
  return (
    <svg className="gx-art gx-art--t" viewBox="0 0 120 100" aria-hidden="true">
      <path d="M8 70l50-24 50 24-50 22z" fill="#fbe9c6" />
      <path
        d="M14 52 70 26l32 15-56 26z"
        fill="#e3f2f6"
        stroke={stroke}
        strokeWidth="2.5"
        strokeLinejoin="round"
      />
      <circle cx="60" cy="46" r="4" fill="#f2a785" />
      <circle cx="68" cy="44" r="4" fill="#00a4bd" />
    </svg>
  );
}

// --- dropdowns ---------------------------------------------------------------------------------

/** [value, label, description?, locked?] */
export type DdOption = [string, string, string?, boolean?];

/**
 * The design's single-select dropdown (`dd()`): a `.gx-ddb` button and, when open, a `.gx-ddp`
 * panel with optional search. Locked options (not measurable yet) show a lock and can't be picked.
 */
export function Dd({
  id,
  value,
  placeholder,
  options,
  open,
  onToggle,
  onPick,
  search,
  query = '',
  onQuery,
  dis,
  up,
  desc,
}: {
  id: string;
  value: string;
  placeholder: string;
  options: DdOption[];
  open: boolean;
  onToggle: (id: string) => void;
  onPick: (id: string, value: string) => void;
  search?: boolean;
  query?: string;
  onQuery?: (q: string) => void;
  dis?: boolean;
  up?: boolean;
  desc?: boolean;
}) {
  const isOpen = open && !dis;
  const label = options.find((o) => o[0] === value)?.[1] ?? value;
  const q = query.toLowerCase();
  const shown = options.filter((o) => !q || o[1].toLowerCase().includes(q));
  return (
    <div className={'gx-dd' + (dis ? ' is-dis' : '')}>
      <button
        type="button"
        className="gx-ddb"
        data-gx-dd={id}
        aria-haspopup="listbox"
        aria-expanded={isOpen}
        disabled={dis}
        onClick={() => onToggle(id)}
      >
        <span className={label ? '' : 'gx-ph'}>{label || placeholder}</span>
        <span className="gl-caret" />
      </button>
      {isOpen ? (
        <div className={'gx-ddp' + (up ? ' gx-ddp--up' : '')}>
          {search ? (
            <label className="gx-ddq">
              <input
                type="search"
                placeholder="Search"
                data-gx-ddq
                value={query}
                autoComplete="off"
                aria-label="Search"
                autoFocus
                onChange={(e) => onQuery?.(e.target.value)}
              />
              <SearchIcon />
            </label>
          ) : null}
          <div className={'gx-ddl' + (desc ? ' gx-ddl--d' : '')} role="listbox" data-gx-ddl>
            {shown.length ? (
              shown.map((o) => (
                <button
                  key={o[0]}
                  type="button"
                  role="option"
                  className={'gx-ddi' + (o[0] === value ? ' is-on' : '') + (o[3] ? ' is-lock' : '')}
                  aria-selected={o[0] === value}
                  disabled={Boolean(o[3])}
                  title={o[3] ? 'Coming soon' : undefined}
                  onClick={() => onPick(id, o[0])}
                >
                  <span>
                    {o[1]}
                    {o[3] ? (
                      <>
                        {' '}
                        <ILock />
                      </>
                    ) : null}
                  </span>
                  {o[2] ? <small>{o[2]}</small> : null}
                </button>
              ))
            ) : (
              <p className="gx-none">No results</p>
            )}
          </div>
        </div>
      ) : null}
    </div>
  );
}

/** A labelled field (`fld()`): label with optional info icon and required star. */
export function Fld({
  label,
  children,
  req,
  info,
  id,
  cls,
}: {
  label: string;
  children: React.ReactNode;
  req?: boolean;
  info?: boolean;
  id?: string;
  cls?: string;
}) {
  return (
    <div className={'gx-f' + (cls ? ' ' + cls : '')}>
      <label className="gx-lbl" htmlFor={id}>
        {label}
        {info ? (
          <>
            {' '}
            <IInfo />
          </>
        ) : null}
        {req ? (
          <>
            {' '}
            <span className="gx-req">*</span>
          </>
        ) : null}
      </label>
      {children}
    </div>
  );
}

export const NOTES: Array<[keyof Notes, string, string, string, string]> = [
  ['kick', 'Goal kick-off', '', '', 'Receive a notification when the goal has started'],
  [
    'exceeded',
    'Goal becomes',
    'Exceeded',
    'blue',
    'Receive a notification when goal exceeded 100% of the target by the duration of the goal',
  ],
  [
    'achieved',
    'Goal becomes',
    'Achieved',
    'green',
    'Receive a notification when goal reached 100% of the target by the duration of the goal',
  ],
  [
    'missed',
    'Goal becomes',
    'Missed',
    'red',
    'Receive a notification when goal didn’t meet 100% of the target by the duration of the goal',
  ],
];

export interface Notes {
  kick: boolean;
  exceeded: boolean;
  achieved: boolean;
  missed: boolean;
}

/** The notifications checklist (`noteHtml()`). */
export function NotesList({
  notes,
  onChange,
}: {
  notes: Notes;
  onChange: (key: keyof Notes, on: boolean) => void;
}) {
  return (
    <>
      {NOTES.map((x) => (
        <div className="gx-ni" key={x[0]}>
          <label className="check">
            <input
              type="checkbox"
              checked={notes[x[0]]}
              onChange={(e) => onChange(x[0], e.target.checked)}
            />
            <span className="check__box" />
            <span className="gx-nt">
              {x[1]}
              {x[2] ? (
                <>
                  {' '}
                  <span className={'gl-bdg gl-bdg--' + x[3]}>{x[2]}</span>
                </>
              ) : null}
            </span>
          </label>
          <p>{x[4]}</p>
        </div>
      ))}
    </>
  );
}

/**
 * A dialog (centre) or drawer (right) on the `.gl-ov` backdrop (`ovl()`). Clicking the backdrop or
 * pressing Esc closes it.
 */
export function Ovl({
  title,
  onClose,
  children,
  foot,
  drawer,
  big,
  cls,
  mbc,
}: {
  title: string;
  onClose: () => void;
  children: React.ReactNode;
  foot?: React.ReactNode;
  drawer?: boolean;
  big?: boolean;
  cls?: string;
  mbc?: string;
}) {
  useEscape(onClose);
  return (
    <div
      className={'gl-ov' + (drawer ? ' gl-ov--r' : '')}
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        className={(drawer ? 'gl-drawer gl-drawer--q' : 'gl-dlg') + ' gx-dlg' + (cls ?? '')}
        role="dialog"
        aria-modal="true"
        aria-label={title}
      >
        <div className={'gl-mh' + (big ? ' gx-mh--big' : '')}>
          <span>{title}</span>
          <button type="button" className="gl-x" aria-label="Close" onClick={onClose}>
            {'×'}
          </button>
        </div>
        <div className={'gl-mb gx-mb' + (mbc ? ' ' + mbc : '')}>{children}</div>
        {foot ? <div className="gl-mf">{foot}</div> : null}
      </div>
    </div>
  );
}

/** Calls `onEscape` when Esc is pressed (latest callback, one listener). */
export function useEscape(onEscape: (() => void) | null) {
  const ref = useRef(onEscape);
  ref.current = onEscape;
  const active = Boolean(onEscape);
  useEffect(() => {
    if (!active) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' || e.key === 'Esc') ref.current?.();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [active]);
}

/** Closes a menu / dropdown when the pointer goes down outside `selector`. */
export function useOutside(active: boolean, selector: string, close: () => void) {
  const ref = useRef(close);
  ref.current = close;
  useEffect(() => {
    if (!active) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as Element | null;
      if (t && t.closest && t.closest(selector)) return;
      ref.current();
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [active, selector]);
}

/** The page toast (`.gl-toast`): one message at a time for 2.6 s. */
export function useGlToast(): { toast: (m: string) => void; node: React.ReactNode } {
  const [msg, setMsg] = useState<string | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const toast = useCallback((m: string) => {
    setMsg(m);
    if (timer.current) clearTimeout(timer.current);
    timer.current = setTimeout(() => setMsg(null), 2600);
  }, []);
  useEffect(
    () => () => {
      if (timer.current) clearTimeout(timer.current);
    },
    [],
  );
  const node = (
    <div className="gl-toast" data-gl-toast role="status" aria-live="polite" hidden={!msg}>
      {msg}
    </div>
  );
  return { toast, node };
}

/** Locks page scroll while an overlay is open (the design's lockScroll). */
export function useLockScroll(on: boolean) {
  useEffect(() => {
    if (!on) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = prev;
    };
  }, [on]);
}
