'use client';

/**
 * Goals dialogs and drawers (13 Nov design, goals.js): clone / delete confirmation, Export,
 * Create goal report (and the report it shows), Quick edit, Quick details, goal definition and
 * the row Actions menu.
 */
import { useEffect, useMemo, useRef, useState } from 'react';
import { barSvg, dailySvg, gaugeSvg, lineSvg } from '../charts';
import { XFMT, XLANG, type ExportFormat } from '../export';
import {
  DASH,
  MON,
  MONFULL,
  TRACK_LABEL,
  formulaOf,
  initials,
  labelOfDate,
  labelOfProperty,
  nf,
  objectOf,
  rangeLabel,
  round2,
  sum,
  val,
  type GoalVM,
  type Row,
  type Tab,
} from '../model';
import type { CatalogueObject } from '../types';
import { Caret, CopyIcon, InfoIcon, SearchIcon, TemplateArt, useEscape } from './parts';

function Overlay({
  onClose,
  right,
  children,
}: {
  onClose: () => void;
  right?: boolean;
  children: React.ReactNode;
}) {
  useEscape(onClose);
  return (
    <div
      className={'gl-ov' + (right ? ' gl-ov--r' : '')}
      data-gl-ov
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      {children}
    </div>
  );
}

function Head({ title, onClose }: { title: string; onClose: () => void }) {
  return (
    <div className="gl-mh">
      <span>{title}</span>
      <button type="button" className="gl-x" aria-label="Close" onClick={onClose}>
        {'×'}
      </button>
    </div>
  );
}

const plural = (n: number) => n + ' goal' + (n === 1 ? '' : 's');

/** Clone / Delete N goals (`confirmModal()`); delete asks for the number of goals. */
export function ConfirmDialog({
  kind,
  count,
  nextYear = false,
  busy,
  onClose,
  onConfirm,
}: {
  kind: 'clone' | 'delete';
  count: number;
  /** The row menu's "Clone this goal for the upcoming year". */
  nextYear?: boolean;
  busy: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  const [typed, setTyped] = useState('');
  const p = plural(count);
  const one = count === 1;
  const title = (kind === 'clone' ? 'Clone ' : 'Delete ') + p;
  const ok = kind === 'clone' || typed.trim() === String(count);
  return (
    <Overlay onClose={onClose}>
      <div className="gl-dlg gl-dlg--s" role="dialog" aria-modal="true" aria-label={title}>
        <Head title={title} onClose={onClose} />
        <div className="gl-mb gl-mb--c">
          {kind === 'clone' ? (
            <p>
              You{'’'}re about to clone {p}
              {nextYear ? ' for the upcoming year' : ''}.{' '}
              {one ? 'A copy will be' : 'Copies will be'} created with the same settings, and all
              assignees will be kept.
              {nextYear ? ' Dates and monthly targets move one year ahead.' : ''}
            </p>
          ) : (
            <>
              <p>
                You{'’'}re about to delete {p}. This means you{'’'}ll lose all goals for teams and
                users who are working on {one ? 'this goal' : 'these goals'}.
              </p>
              <p>
                All historical progress data tracked for {one ? 'this goal' : 'these goals'} will
                also be permanently deleted.
              </p>
              <div className="gl-fld">
                <label className="gl-dl" htmlFor="glDn">
                  Type the number of goals below to delete
                </label>
                <input
                  className="input"
                  id="glDn"
                  type="text"
                  inputMode="numeric"
                  autoComplete="off"
                  placeholder={String(count)}
                  value={typed}
                  autoFocus
                  onChange={(e) => setTyped(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && ok && !busy) {
                      e.preventDefault();
                      onConfirm();
                    }
                  }}
                />
              </div>
            </>
          )}
          <div className="gl-mf gl-mf--in">
            <button
              type="button"
              className={'btn-crm ' + (kind === 'clone' ? 'btn-crm--primary' : 'btn-crm--danger')}
              disabled={!ok || busy}
              autoFocus={kind === 'clone'}
              onClick={onConfirm}
            >
              {title}
            </button>
            <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
              Cancel
            </button>
          </div>
        </div>
      </div>
    </Overlay>
  );
}

function Tipi({ t }: { t: string }) {
  return (
    <span className="gl-i" tabIndex={0} role="img" aria-label={t} title={t}>
      <InfoIcon />
    </span>
  );
}

function ExtIcon() {
  return (
    <svg className="gl-ext" viewBox="0 0 24 24" width="12" height="12" aria-hidden="true">
      <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 interface ExportChoice {
  name: string;
  fmt: ExportFormat;
  lang: string;
  mode: 'view' | 'props' | 'all';
  incName: boolean;
  limit: '1000' | 'all';
}

/** The Export dialog (`renderExport()`). */
export function ExportDialog({
  label,
  count,
  onClose,
  onExport,
  onSoon,
}: {
  label: string;
  count: number;
  onClose: () => void;
  onExport: (x: ExportChoice) => void;
  onSoon: () => void;
}) {
  const [x, setX] = useState<ExportChoice>({
    name: label,
    fmt: 'CSV',
    lang: 'en',
    mode: 'view',
    incName: true,
    limit: '1000',
  });
  const [open, setOpen] = useState<'fmt' | 'lang' | null>(null);
  const [q, setQ] = useState('');
  const [cust, setCust] = useState(true);
  const [err, setErr] = useState('');
  const dis = x.mode === 'props';
  const slow = 'May result in slower exports';
  const langName = XLANG.find((l) => l[0] === x.lang)?.[1] ?? 'English';
  const run = () => {
    if (!x.name.trim()) {
      setErr('Enter an export name.');
      return;
    }
    onExport(x);
  };
  const combo = (
    id: 'fmt' | 'lang',
    label2: string,
    tip: string,
    cur: string,
    list: Array<[string, string, boolean]>,
  ) => {
    const isOpen = open === id;
    const ql = q.toLowerCase();
    const opts = list.filter((o) => id !== 'lang' || !ql || o[1].toLowerCase().includes(ql));
    return (
      <div className="gl-xf">
        <span className="gl-dl" id={'glX' + id}>
          {label2}
          {tip ? (
            <>
              {' '}
              <Tipi t={tip} />
            </>
          ) : null}
        </span>
        <div className="gl-cb">
          <button
            type="button"
            className="gl-cb__b"
            aria-haspopup="listbox"
            aria-expanded={isOpen}
            aria-labelledby={'glX' + id}
            onClick={() => {
              setOpen(isOpen ? null : id);
              setQ('');
            }}
          >
            <span>{cur}</span>
            <Caret />
          </button>
          {isOpen ? (
            <div className="gl-menu">
              {id === 'lang' ? (
                <label className="gl-menu__s">
                  <span className="gl-sr">Search languages</span>
                  <input
                    type="search"
                    className="input"
                    placeholder="Search"
                    value={q}
                    autoComplete="off"
                    autoFocus
                    onChange={(e) => setQ(e.target.value)}
                  />
                  <SearchIcon />
                </label>
              ) : null}
              <div className="gl-menu__l" role="listbox">
                {opts.length ? (
                  opts.map((o) => (
                    <button
                      key={o[0]}
                      type="button"
                      role="option"
                      className={'gl-mi' + (o[2] ? ' is-on' : '')}
                      aria-selected={o[2]}
                      onClick={() => {
                        setX((s) => ({ ...s, [id]: o[0] }));
                        setOpen(null);
                        setQ('');
                      }}
                    >
                      {o[1]}
                    </button>
                  ))
                ) : (
                  <p className="gl-menu__none">No results</p>
                )}
              </div>
            </div>
          ) : null}
        </div>
      </div>
    );
  };
  const radio = (
    name: string,
    v: string,
    cur: string,
    label2: string,
    hint: string,
    disabled: boolean,
    onPick: () => void,
  ) => (
    <label className={'gl-radio' + (disabled ? ' is-dis' : '')}>
      <input
        type="radio"
        name={name}
        value={v}
        checked={cur === v && !disabled}
        disabled={disabled}
        onChange={onPick}
      />
      <span>
        {label2}
        {hint ? <small className="gl-hint">{hint}</small> : null}
      </span>
    </label>
  );
  const lim =
    x.limit === 'all'
      ? 'All associated records in each association column of each row'
      : 'Up to 1,000 associated records in each association column of each row';
  return (
    <Overlay onClose={open ? () => setOpen(null) : onClose}>
      <div
        className="gl-dlg gl-dlg--x"
        role="dialog"
        aria-modal="true"
        aria-label="Export"
        onClick={(e) => {
          if (open && !(e.target as Element).closest('.gl-cb')) setOpen(null);
        }}
      >
        <Head title="Export" onClose={onClose} />
        <div className="gl-mb gl-mb--x">
          <div className="gl-xrow">
            <b>Send to</b>
            <button type="button" className="link" onClick={onSoon}>
              Not getting our emails?
            </button>
          </div>
          <p className="gl-xmuted">
            The exported file will be posted in your{' '}
            <button type="button" className="link" onClick={onSoon}>
              Notifications Center
              <ExtIcon />
            </button>
            . View this and past exports in{' '}
            <button type="button" className="link" onClick={onSoon}>
              Export Audit
              <ExtIcon />
            </button>
            .
          </p>
          <hr />
          <div className="gl-xp">
            <p className="gl-dl">Prepare your export file</p>
            <p>
              Exporting: <b>{label}</b> &nbsp;{count} row{count === 1 ? '' : 's'} in 1 file
            </p>
          </div>
          <div className="gl-xf">
            <label className="gl-dl" htmlFor="glXn">
              Export name
            </label>
            <input
              className="input"
              id="glXn"
              type="text"
              maxLength={120}
              value={x.name}
              autoComplete="off"
              autoFocus
              onChange={(e) => {
                setX({ ...x, name: e.target.value });
                setErr('');
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  run();
                }
              }}
            />
          </div>
          <div className="gl-x2">
            {combo(
              'fmt',
              'File format',
              '',
              x.fmt,
              XFMT.map((f) => [f, f, f === x.fmt]),
            )}
            {combo(
              'lang',
              'Language of column headers',
              'Column headers in the exported file use this language. Your data is not translated.',
              langName,
              XLANG.map((l) => [l[0], l[1], l[0] === x.lang]),
            )}
          </div>
          <div className="gl-xp">
            <p className="gl-dl">Data included in export</p>
            <ul className="gl-ul">
              {x.mode === 'props' ? (
                <>
                  <li>All properties on records</li>
                  <li>No associations</li>
                </>
              ) : (
                <>
                  {x.mode === 'view' ? (
                    <>
                      <li>Properties in your view</li>
                      <li>Associations in your view</li>
                    </>
                  ) : (
                    <>
                      <li>All properties on records</li>
                      <li>All associations on records</li>
                    </>
                  )}
                  <li className="gl-sub">
                    <ul>
                      <li>{lim}</li>
                      <li>
                        {x.incName ? (
                          <>
                            <b>Associated record name</b> and <b>associated record ID</b>
                          </>
                        ) : (
                          <b>Associated record ID only</b>
                        )}
                      </li>
                    </ul>
                  </li>
                </>
              )}
            </ul>
          </div>
          <hr />
          <button
            type="button"
            className="gl-acc"
            aria-expanded={cust}
            onClick={() => setCust(!cust)}
          >
            <span className={'gl-chev' + (cust ? ' is-open' : '')} aria-hidden="true" />
            Customize
          </button>
          {cust ? (
            <div className="gl-xc">
              <div className="gl-grp" role="radiogroup" aria-labelledby="glXp">
                <p className="gl-dl" id="glXp">
                  Properties included in export
                </p>
                {radio(
                  'glXm',
                  'view',
                  x.mode,
                  'Properties and associations in your view',
                  '',
                  false,
                  () => setX({ ...x, mode: 'view', incName: true, limit: '1000' }),
                )}
                {radio('glXm', 'props', x.mode, 'All properties on records', '', false, () =>
                  setX({ ...x, mode: 'props' }),
                )}
                {radio(
                  'glXm',
                  'all',
                  x.mode,
                  'All properties and all associations on records',
                  slow,
                  false,
                  () => setX({ ...x, mode: 'all', incName: false, limit: 'all' }),
                )}
              </div>
              <div className="gl-grp" role="group" aria-labelledby="glXa">
                <p className="gl-dl" id="glXa">
                  Associations included in export{' '}
                  <Tipi t="Associated records are the teams and users linked to each row." />
                </p>
                <label className={'check' + (dis ? ' is-dis' : '')}>
                  <input
                    type="checkbox"
                    checked={x.incName && !dis}
                    disabled={dis}
                    onChange={(e) => setX({ ...x, incName: e.target.checked })}
                  />
                  <span className="check__box" />
                  <span>
                    Include associated record name<small className="gl-hint">{slow}</small>
                  </span>
                </label>
                {radio(
                  'glXl',
                  '1000',
                  x.limit,
                  'Include up to 1,000 associated records in each association column',
                  '',
                  dis,
                  () => setX({ ...x, limit: '1000' }),
                )}
                {radio(
                  'glXl',
                  'all',
                  x.limit,
                  'Include all associated records in each association column',
                  slow,
                  dis,
                  () => setX({ ...x, limit: 'all' }),
                )}
              </div>
            </div>
          ) : null}
          <div className="gl-err" hidden={!err}>
            {err}
          </div>
          <div className="gl-mf gl-mf--in">
            <button type="button" className="btn-crm btn-crm--primary" onClick={run}>
              Export
            </button>
            <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
              Cancel
            </button>
          </div>
        </div>
      </div>
    </Overlay>
  );
}

const VIS: Array<['gauge' | 'line' | 'bar', string, string]> = [
  ['gauge', 'Gauge', 'Total goal progress across users or teams'],
  ['line', 'Line', 'Goal attainment over time'],
  ['bar', 'Bar', 'Total progress by user or team'],
];

function VisIcon({ k }: { k: 'gauge' | 'line' | 'bar' }) {
  if (k === 'gauge') {
    return (
      <svg viewBox="0 0 36 36" aria-hidden="true">
        <path d="M5 26a13 13 0 0 1 26 0" fill="none" stroke="#e1e6ec" strokeWidth="5" />
        <path d="M5 26a13 13 0 0 1 17-12.3" fill="none" stroke="#2456e6" strokeWidth="5" />
      </svg>
    );
  }
  if (k === 'line') {
    return (
      <svg viewBox="0 0 36 36" aria-hidden="true">
        <path
          d="M3 28 12 14l7 8 6-12 8 14"
          fill="none"
          stroke="#2456e6"
          strokeWidth="2.4"
          strokeLinejoin="round"
        />
        <path d="M3 20 12 9l7 6 6-9 8 10" fill="none" stroke="#8fb0f0" strokeWidth="2" />
      </svg>
    );
  }
  return (
    <svg viewBox="0 0 36 36" aria-hidden="true">
      <rect x="3" y="6" width="28" height="4" fill="#2456e6" />
      <rect x="3" y="13" width="20" height="4" fill="#b3366b" />
      <rect x="3" y="20" width="14" height="4" fill="#8fb0f0" />
      <rect x="3" y="27" width="8" height="4" fill="#f2a9c9" />
    </svg>
  );
}

const whoOk = (g: GoalVM, w: 'users' | 'teams') =>
  (!g.users.length && !g.teams.length) ||
  (w === 'users' ? g.src.userProgress.length > 0 : g.teams.length > 0);

/** Create goal report drawer (`renderReport()`): goal, contributor type, visualization. */
export function ReportDrawer({
  goals,
  initialId,
  onClose,
  onCreate,
}: {
  goals: GoalVM[];
  initialId: string | null;
  onClose: () => void;
  onCreate: (r: { goalId: string; who: 'users' | 'teams'; vis: 'gauge' | 'line' | 'bar' }) => void;
}) {
  const first = goals.find((g) => g.id === initialId) ?? goals[0] ?? null;
  const [goalId, setGoalId] = useState(first?.id ?? '');
  const [who, setWho] = useState<'users' | 'teams'>(
    first && whoOk(first, 'users') ? 'users' : 'teams',
  );
  const [vis, setVis] = useState<'gauge' | 'line' | 'bar'>('gauge');
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState('');
  const g = goals.find((x) => x.id === goalId) ?? null;
  const list = goals.filter((x) => !q || x.name.toLowerCase().includes(q.toLowerCase()));
  return (
    <Overlay right onClose={open ? () => setOpen(false) : onClose}>
      <div
        className="gl-drawer"
        role="dialog"
        aria-modal="true"
        aria-label="Create goal report"
        onClick={(e) => {
          if (open && !(e.target as Element).closest('.gl-cb')) setOpen(false);
        }}
      >
        <Head title="Create goal report" onClose={onClose} />
        <div className="gl-mb">
          <div className="gl-grp">
            <p className="gl-step" id="glS1">
              Step 1. Choose a goal.
            </p>
            <div className="gl-cb">
              <button
                type="button"
                className="gl-cb__b"
                aria-haspopup="listbox"
                aria-expanded={open}
                aria-labelledby="glS1"
                onClick={() => {
                  setOpen(!open);
                  setQ('');
                }}
              >
                <span>{g ? g.name : ''}</span>
                <Caret />
              </button>
              {open ? (
                <div className="gl-menu">
                  <label className="gl-menu__s">
                    <span className="gl-sr">Search for a goal</span>
                    <input
                      type="search"
                      className="input"
                      placeholder="Search for a goal"
                      value={q}
                      autoComplete="off"
                      autoFocus
                      onChange={(e) => setQ(e.target.value)}
                    />
                    <SearchIcon />
                  </label>
                  <div className="gl-menu__l" role="listbox">
                    {list.length ? (
                      list.map((x) => (
                        <button
                          key={x.id}
                          type="button"
                          role="option"
                          className={'gl-mi' + (goalId === x.id ? ' is-on' : '')}
                          aria-selected={goalId === x.id}
                          onClick={() => {
                            setGoalId(x.id);
                            setOpen(false);
                            if (!whoOk(x, who)) setWho(whoOk(x, 'users') ? 'users' : 'teams');
                          }}
                        >
                          {x.name}
                        </button>
                      ))
                    ) : (
                      <p className="gl-menu__none">No results</p>
                    )}
                  </div>
                </div>
              ) : null}
            </div>
          </div>
          <div className="gl-grp" role="radiogroup" aria-labelledby="glS2">
            <p className="gl-step" id="glS2">
              Step 2. Choose the type of contributor.
            </p>
            {(['users', 'teams'] as const).map((w) => {
              const dis = g ? !whoOk(g, w) : false;
              return (
                <label key={w} className={'gl-radio' + (dis ? ' is-dis' : '')}>
                  <input
                    type="radio"
                    name="glWho"
                    value={w}
                    checked={who === w}
                    disabled={dis}
                    onChange={() => setWho(w)}
                  />{' '}
                  {w === 'users' ? 'Users' : 'Teams'}
                </label>
              );
            })}
          </div>
          <div className="gl-grp" role="radiogroup" aria-labelledby="glS3">
            <p className="gl-step" id="glS3">
              Step 3. Choose a visualization type.
            </p>
            <div className="gl-vis">
              {VIS.map((v) => (
                <button
                  key={v[0]}
                  type="button"
                  role="radio"
                  aria-checked={vis === v[0]}
                  className={'gl-vc' + (vis === v[0] ? ' is-on' : '')}
                  onClick={() => setVis(v[0])}
                >
                  <VisIcon k={v[0]} />
                  <span>
                    <b>{v[1]}</b>
                    <span>{v[2]}</span>
                  </span>
                </button>
              ))}
            </div>
          </div>
        </div>
        <div className="gl-mf">
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={!g}
            onClick={() => g && onCreate({ goalId: g.id, who, vis })}
          >
            Create goal report
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </div>
    </Overlay>
  );
}

/** The report a goal report shows (`showReport()`). */
export function ReportResult({
  g,
  who,
  vis,
  year,
  lastMonth,
  onClose,
}: {
  g: GoalVM;
  who: 'users' | 'teams';
  vis: 'gauge' | 'line' | 'bar';
  year: number;
  lastMonth: number;
  onClose: () => void;
}) {
  const pct = g.goal ? (g.prog / g.goal) * 100 : 0;
  const items =
    who === 'users'
      ? g.src.userProgress.map((u) => ({
          l: u.name,
          v: sum(u.targets) ? (u.actualTotal / sum(u.targets)) * 100 : 0,
        }))
      : g.src.teamProgress.map((t) => ({
          l: t.name,
          v: sum(t.targets) ? (t.actualTotal / sum(t.targets)) * 100 : 0,
        }));
  const chart =
    vis === 'gauge'
      ? gaugeSvg(pct)
      : vis === 'line'
        ? lineSvg(g.src.actuals, g.goal, lastMonth)
        : items.length
          ? barSvg(items)
          : '';
  const v = VIS.find((x) => x[0] === vis)!;
  const sub = val(g, g.prog) + ' of ' + val(g, g.goal) + ' · ' + rangeLabel(year);
  return (
    <Overlay onClose={onClose}>
      <div className="gl-dlg" role="dialog" aria-modal="true" aria-label={g.name + ' report'}>
        <Head title={g.name} onClose={onClose} />
        <div className="gl-mb">
          <div className="gl-rep">
            {chart ? (
              <div dangerouslySetInnerHTML={{ __html: chart }} />
            ) : (
              <p className="gl-rep__s">This goal has no {who} to show.</p>
            )}
            <p className="gl-rep__s">
              {v[1]} report by {who === 'users' ? 'user' : 'team'} {'·'} {sub}
            </p>
          </div>
        </div>
        <div className="gl-mf">
          <button type="button" className="btn-crm btn-crm--primary" autoFocus onClick={onClose}>
            Close
          </button>
        </div>
      </div>
    </Overlay>
  );
}

/** Spreads a new monthly total over a goal's target rows (proportionally, else evenly). */
export function spreadTotals(
  rows: Array<{ type: 'user' | 'team'; id: string; months: number[] }>,
  totals: number[],
): Array<{ type: 'user' | 'team'; id: string; months: number[] }> {
  const primary = rows.some((r) => r.type === 'team') ? 'team' : 'user';
  const main = rows.filter((r) => r.type === primary);
  return rows.map((r) => {
    if (r.type !== primary) return r;
    return {
      ...r,
      months: r.months.map((v, m) => {
        const old = main.reduce((s, x) => s + (x.months[m] ?? 0), 0);
        const t = totals[m] ?? 0;
        return round2(old > 0 ? (v * t) / old : t / Math.max(1, main.length));
      }),
    };
  });
}

const QN: Array<['kickoff' | 'exceeded' | 'achieved' | 'missed', string, string, string, string]> =
  [
    ['kickoff', '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 QuickSave {
  name: string;
  totals: Record<number, number[]>;
  notifications: { kickoff: boolean; exceeded: boolean; achieved: boolean; missed: boolean };
}

/** Quick edit drawer (`renderQuick()`): name, monthly targets per year, notifications. */
export function QuickEditDrawer({
  g,
  teams,
  thisYear,
  loadYear,
  onClose,
  onSave,
  onToast,
}: {
  g: GoalVM;
  teams: string[];
  thisYear: number;
  loadYear: (year: number) => Promise<number[]>;
  onClose: () => void;
  onSave: (s: QuickSave) => Promise<string | null>;
  onToast: (m: string) => void;
}) {
  const [tab, setTab] = useState<'goal' | 'notif'>('goal');
  const [name, setName] = useState(g.name);
  const [year, setYear] = useState(thisYear);
  const [t, setT] = useState<Record<number, string[]>>({});
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const [n, setN] = useState({ ...g.src.notifications });
  const unit = g.unit === 'usd' ? 'Amount (USD)' : 'Number of units';
  // The targets of a year, loaded once when it is first shown (the latest loader, one request).
  const loader = useRef(loadYear);
  loader.current = loadYear;
  const loaded = Boolean(t[year]);
  useEffect(() => {
    if (loaded) return;
    let live = true;
    void loader.current(year).then((months) => {
      if (live) setT((s) => (s[year] ? s : { ...s, [year]: months.map((v) => String(v)) }));
    });
    return () => {
      live = false;
    };
  }, [year, loaded]);
  const arr = t[year];
  const save = async () => {
    const nm = name.trim();
    if (!nm) {
      setTab('goal');
      setErr('Enter a goal name.');
      return;
    }
    const totals: Record<number, number[]> = {};
    for (const y of Object.keys(t).map(Number)) {
      const out: number[] = [];
      for (let i = 0; i < 12; i++) {
        const v = parseFloat(t[y]![i] ?? '');
        if (!isFinite(v) || v < 0) {
          setTab('goal');
          setYear(y);
          setErr('Enter a target of 0 or more for ' + MON[i] + ' ' + y + '.');
          return;
        }
        out.push(v);
      }
      totals[y] = out;
    }
    setBusy(true);
    const e = await onSave({ name: nm, totals, notifications: n });
    setBusy(false);
    if (e) {
      setTab('goal');
      setErr(e);
    }
  };
  return (
    <Overlay right onClose={onClose}>
      <div
        className="gl-drawer gl-drawer--q"
        role="dialog"
        aria-modal="true"
        aria-label={g.tpl + ' quick edit'}
      >
        <Head title={g.tpl} onClose={onClose} />
        <div className="gl-tabs" role="tablist">
          {(
            [
              ['goal', 'Goal'],
              ['notif', 'Notifications'],
            ] as const
          ).map((x) => (
            <button
              key={x[0]}
              type="button"
              role="tab"
              className={'gl-tab' + (tab === x[0] ? ' is-on' : '')}
              aria-selected={tab === x[0]}
              onClick={() => {
                setTab(x[0]);
                setErr('');
              }}
            >
              {x[1]}
            </button>
          ))}
        </div>
        <div className="gl-mb gl-mb--q">
          {tab === 'goal' ? (
            <>
              <div className="gl-qf">
                <label className="gl-dl" htmlFor="glQn">
                  Name
                </label>
                <input
                  className="input gl-qin"
                  id="glQn"
                  type="text"
                  maxLength={120}
                  value={name}
                  autoComplete="off"
                  autoFocus
                  onChange={(e) => {
                    setName(e.target.value);
                    setErr('');
                  }}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') {
                      e.preventDefault();
                      void save();
                    }
                  }}
                />
              </div>
              <div className="gl-qf">
                <span className="gl-dl">Team</span>
                <div className="gl-ro">{teams.length ? teams.join(', ') : DASH}</div>
              </div>
              <div className="gl-qf">
                <span className="gl-dl">Cadence</span>
                <div className="gl-ro">{g.cad || 'Monthly'}</div>
              </div>
              <div className="gl-qt">
                <b>Targets</b>
                <span className="gl-qt__r">
                  <button
                    type="button"
                    className="link"
                    disabled={!arr}
                    onClick={() => {
                      if (!arr) return;
                      setT({ ...t, [year]: arr.map(() => arr[0]!) });
                      setErr('');
                      onToast('Applied ' + MON[0] + ' target to every month');
                    }}
                  >
                    Apply target
                  </button>
                  <span className="gl-range gl-range--q">
                    <button
                      type="button"
                      aria-label="Previous year"
                      disabled={year <= thisYear - 2}
                      onClick={() => setYear(year - 1)}
                    >
                      {'‹'}
                    </button>
                    <span aria-live="polite">{year}</span>
                    <button
                      type="button"
                      aria-label="Next year"
                      disabled={year >= thisYear}
                      onClick={() => setYear(year + 1)}
                    >
                      {'›'}
                    </button>
                  </span>
                </span>
              </div>
              <div className="gl-qg">
                {MON.map((m, i) => (
                  <label key={m} className="gl-qr" htmlFor={'glQt' + i}>
                    <span className="gl-qr__m">
                      {m} {year}
                    </span>
                    <span className="gl-qr__u">{unit}</span>
                    <input
                      className="input"
                      id={'glQt' + i}
                      type="number"
                      min="0"
                      step="any"
                      value={arr?.[i] ?? ''}
                      disabled={!arr}
                      onChange={(e) => {
                        if (!arr) return;
                        const next = arr.slice();
                        next[i] = e.target.value;
                        setT({ ...t, [year]: next });
                        setErr('');
                      }}
                    />
                  </label>
                ))}
              </div>
            </>
          ) : (
            <>
              <p className="gl-qh">Select notifications</p>
              {QN.map((o) => (
                <label key={o[0]} className="check gl-qn">
                  <input
                    type="checkbox"
                    checked={n[o[0]]}
                    onChange={(e) => setN({ ...n, [o[0]]: e.target.checked })}
                  />
                  <span className="check__box" />
                  <span>
                    <span className="gl-qn__t">
                      {o[1]}
                      {o[2] ? <span className={'gl-bdg gl-bdg--' + o[3]}>{o[2]}</span> : null}
                    </span>
                    <small className="gl-hint">{o[4]}</small>
                  </span>
                </label>
              ))}
            </>
          )}
          <div className="gl-err" hidden={!err}>
            {err}
          </div>
        </div>
        <div className="gl-mf">
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={busy}
            onClick={() => void save()}
          >
            Save
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </div>
    </Overlay>
  );
}

const pad = (n: number) => (n < 10 ? '0' + n : '' + n);
const ord = (n: number) =>
  n +
  (n % 10 === 1 && n !== 11
    ? 'st'
    : n % 10 === 2 && n !== 12
      ? 'nd'
      : n % 10 === 3 && n !== 13
        ? 'rd'
        : 'th');
function stamp(d: Date): string {
  const h = d.getHours();
  const m = d.getMinutes();
  return (
    MONFULL[d.getMonth()] +
    ' ' +
    ord(d.getDate()) +
    ' at ' +
    (h % 12 || 12) +
    ':' +
    pad(m) +
    (h < 12 ? 'am' : 'pm')
  );
}

/** Quick details drawer (`renderDetails()`) for a goal or a team's / user's part of it. */
export function QuickDetailsDrawer({
  g,
  row,
  year,
  today,
  catalogue,
  updatedAt,
  onClose,
  onRefresh,
}: {
  g: GoalVM;
  row: Row | null;
  year: number;
  today: { year: number; month: number };
  catalogue: CatalogueObject[];
  updatedAt: Date;
  onClose: () => void;
  onRefresh: () => void;
}) {
  const [m, setM] = useState(year === today.year ? today.month - 1 : year < today.year ? 11 : 0);
  const ents = useMemo(() => {
    if (row && row.user) {
      const u = g.src.userProgress.find((x) => x.name === row.user);
      return u ? [{ n: u.name, kind: 'u' as const, t: u.targets, a: u.actuals }] : [];
    }
    if (row && row.team) {
      const tm = g.src.teamProgress.find((x) => x.name === row.team);
      return tm ? [{ n: tm.name, kind: 't' as const, t: tm.targets, a: tm.actuals }] : [];
    }
    if (g.src.teamProgress.length)
      return g.src.teamProgress.map((x) => ({
        n: x.name,
        kind: 't' as const,
        t: x.targets,
        a: x.actuals,
      }));
    return g.src.userProgress.map((x) => ({
      n: x.name,
      kind: 'u' as const,
      t: x.targets,
      a: x.actuals,
    }));
  }, [g, row]);
  const now = new Date();
  const todayD = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const start = new Date(year, m, 1);
  const end = new Date(year, m + 1, 0);
  const ended = end < todayD;
  const days = end.getDate();
  let tgt = 0;
  let prog = 0;
  const rows = ents.map((e) => {
    const et = e.t[m] ?? 0;
    const ep = e.a[m] ?? 0;
    tgt += et;
    prog += ep;
    const p = et ? (ep / et) * 100 : 0;
    return (
      <div className="gl-de" key={e.kind + e.n}>
        <div className="gl-de__h">
          <span className="gl-av gl-av--s" aria-hidden="true">
            {e.kind === 't' ? <CopyIcon /> : initials(e.n)}
          </span>
          <span className="gl-de__n">{e.n}</span>
          <b>{nf(Math.round(p))}%</b>
        </div>
        <span className="gl-track">
          <span
            className="gl-fill"
            style={{ width: Math.max(0, Math.min(100, p)).toFixed(1) + '%' }}
          />
        </span>
      </div>
    );
  });
  const pct = tgt ? (prog / tgt) * 100 : 0;
  const rp = round2(prog);
  const rt = round2(tgt);
  const shown =
    year === today.year && m === today.month - 1 ? Math.min(days, now.getDate()) : ended ? days : 0;
  const badge: [string, string] | null =
    pct > 100.0001
      ? ['blue', 'Exceeded']
      : pct >= 99.9999
        ? ['green', 'Achieved']
        : ended
          ? ['red', 'Missed']
          : null;
  const rng = m + 1 + '/1/' + year + ' to ' + (m + 1) + '/' + days + '/' + year;
  const since = ended ? Math.floor((todayD.getTime() - end.getTime()) / 864e5) : 0;
  const f = formulaOf(catalogue, g.src);
  const drow = (l: string, v: string) => (
    <div className="gl-dr2">
      <span>{l}</span>
      <span>{v}</span>
    </div>
  );
  return (
    <Overlay right onClose={onClose}>
      <div
        className="gl-drawer gl-drawer--q"
        role="dialog"
        aria-modal="true"
        aria-label={g.name + ' quick details'}
      >
        <Head title={g.tpl} onClose={onClose} />
        <div className="gl-mb gl-mb--q">
          <div className="gl-dh">
            <h2 className="gl-dh__t">{g.name}</h2>
            {badge ? <span className={'gl-bdg gl-bdg--' + badge[0]}>{badge[1]}</span> : null}
          </div>
          <select
            className="input gl-dsel"
            aria-label="Goal period"
            value={m}
            onChange={(e) => setM(Number(e.target.value))}
          >
            {MON.map((mm, i) => (
              <option key={mm} value={i}>
                {mm} {year}
              </option>
            ))}
          </select>
          <div className="gl-des">{rows}</div>
          <p className="gl-dupd">
            Last updated on {stamp(updatedAt)} <InfoIcon />
          </p>
          <div className="gl-card gl-dchart">
            <span className="gl-beta">Beta</span>
            <h3 className="gl-card__t">
              Monthly target over time. <InfoIcon />
            </h3>
            <span className="gl-chip">From {rng} | Daily</span>
            <p className="gl-leg">
              <i aria-hidden="true" />
              {g.name}
            </p>
            <p className="gl-ytl">Goal progress</p>
            <div dangerouslySetInnerHTML={{ __html: dailySvg(m, year, pct, shown) }} />
          </div>
          <div className="gl-d2">
            <div className="gl-card gl-stat">
              <b>Remaining goal target</b>
              <span>{val(g, Math.max(0, rt - rp))}</span>
            </div>
            <div className="gl-card gl-stat">
              <b>Days since past due</b>
              <span>{since}</span>
            </div>
          </div>
          <div className="gl-card gl-cur">
            <p className="gl-chips">
              <span className="gl-chip">
                From {m + 1}/1/{year} to {m + 1}/{days}/{year}
              </span>
              <span className="gl-chip">Filters (1)</span>
            </p>
            <p className="gl-cur__l">CURRENT PROGRESS</p>
            <p className="gl-cur__v">{val(g, rp)}</p>
          </div>
          <p className="gl-note">
            If the time zone set in your CRM account isn{'’'}t using UTC, this report may show a
            different value from other goal progress reports.
          </p>
          <h3 className="gl-qh2">Details</h3>
          <div className="gl-dd">
            {drow('Goal target', val(g, rt))}
            {drow('Cadence', g.cad || 'Monthly')}
            {drow('Start date', pad(start.getMonth() + 1) + '/01/' + year)}
            {drow('End date', pad(end.getMonth() + 1) + '/' + pad(days) + '/' + year)}
            {drow('Goal created by', g.by || DASH)}
          </div>
          <hr />
          <h3 className="gl-qh2">Goal calculation</h3>
          <p>This goal is calculated using the following formula and filters:</p>
          <p className="gl-dl">Formula</p>
          <p>
            f(x) = <span className="gl-fx">{f}</span>
          </p>
          <p className="gl-dl">Tracking method</p>
          <p>
            {g.src.definition.tracking === 'lower'
              ? 'Lower value is better'
              : 'Higher value is better'}
          </p>
        </div>
        <div className="gl-mf gl-mf--d">
          <button type="button" className="btn-crm btn-crm--outline" autoFocus onClick={onClose}>
            Close
          </button>
          <button type="button" className="link gl-rf" onClick={onRefresh}>
            Refresh goal progress
          </button>
        </div>
      </div>
    </Overlay>
  );
}

/** "View goal definition" (`openGoalDefinition()`). */
export function GoalDefinitionDialog({
  g,
  catalogue,
  onClose,
}: {
  g: GoalVM;
  catalogue: CatalogueObject[];
  onClose: () => void;
}) {
  const d = g.src.definition;
  const custom = g.src.templateKey === 'custom';
  return (
    <Overlay onClose={onClose}>
      <div
        className="gl-dlg gl-goal-definition"
        role="dialog"
        aria-modal="true"
        aria-label="Custom goal"
      >
        <Head title="Custom goal" onClose={onClose} />
        <div className="gl-mb gl-goal-definition__body">
          <h2>About this goal</h2>
          <div className="gl-definition-svg-area">
            <div>
              <div className="gl-definition-row">
                <b>Category:</b>
                <span>{custom ? 'Custom' : g.tpl}</span>
              </div>
              <div className="gl-definition-row">
                <b>Object used:</b>
                <span>{objectOf(catalogue, d.objectType)?.label ?? d.objectType}</span>
              </div>
              <div className="gl-definition-row">
                <b>Property used:</b>
                <span>{labelOfProperty(catalogue, d.objectType, d.property)}</span>
              </div>
              <h3>How is data aggregated?</h3>
              <p>{d.aggregation === 'COUNT' ? 'Count' : d.aggregation}</p>
              <h3>What unit of measurement is used?</h3>
              <p>{g.unit === 'usd' ? 'Currency' : 'Number'}</p>
            </div>
            <TemplateArt stroke=" 3b4a5a" />
          </div>
          <details className="gl-definition-filters">
            <summary>What filters are being applied?</summary>
            <p>
              {[
                labelOfDate(catalogue, d.objectType, d.dateProperty) + ' in the goal period',
                g.pipe ? 'Pipeline is ' + g.pipe : '',
                TRACK_LABEL[d.tracking],
              ]
                .filter(Boolean)
                .join(' · ')}
            </p>
          </details>
          <button
            type="button"
            className="btn-crm btn-crm--primary gl-definition-done"
            autoFocus
            onClick={onClose}
          >
            Got it
          </button>
        </div>
      </div>
    </Overlay>
  );
}

/** The row Actions menu (`openRowMenu()`), fixed under its button. */
export function RowMenu({
  tab,
  rowKey,
  anchor,
  canManage = true,
  onPick,
  onClose,
}: {
  tab: Tab;
  rowKey: string;
  anchor: DOMRect;
  /** Without "Manage targets": no Clone or Quick edit (QA #583). */
  canManage?: boolean;
  onPick: (k: 'report' | 'clone' | 'details' | 'quick', key: string) => void;
  onClose: () => void;
}) {
  useEscape(onClose);
  useEffect(() => {
    const onDown = (e: MouseEvent) => {
      const t = e.target as Element;
      if (!t.closest('[data-gl-ract]') && !t.closest('.gl-menu--fix')) onClose();
    };
    const onScroll = (e: Event) => {
      const t = e.target as Element | null;
      if (!t || !t.closest || !t.closest('.gl-menu--fix')) onClose();
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('scroll', onScroll, true);
    window.addEventListener('resize', onClose);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('scroll', onScroll, true);
      window.removeEventListener('resize', onClose);
    };
  }, [onClose]);
  const gl = tab === 'goals';
  const w = 330;
  const h = 68 + 64 * (gl ? (canManage ? 1 : 0) : canManage ? 2 : 1);
  const x = Math.max(8, Math.min(anchor.left, window.innerWidth - w - 8));
  let y = anchor.bottom + 6;
  if (y + h > window.innerHeight - 8) y = Math.max(8, anchor.top - h - 6);
  const mi = (k: 'report' | 'clone' | 'details' | 'quick', t: string, s: string) => (
    <button
      key={k}
      type="button"
      role="menuitem"
      className="gl-mi gl-mi--2"
      onClick={() => onPick(k, rowKey)}
    >
      <span>
        {t}
        <small>{s}</small>
      </span>
    </button>
  );
  return (
    <div data-gl-pop="">
      <div
        className="gl-menu gl-menu--fix"
        role="menu"
        style={{ left: Math.round(x), top: Math.round(y) }}
      >
        {mi('report', 'Report', 'Create a report for this goal')}
        {gl
          ? canManage
            ? mi('clone', 'Clone', 'Clone this goal for the upcoming year')
            : null
          : [
              mi('details', 'Quick details', 'View high level reporting and goal definition'),
              canManage ? mi('quick', 'Quick edit', 'Edit targets and goal notifications') : null,
            ]}
      </div>
    </div>
  );
}
