'use client';

/**
 * Goal templates (QA #345, 13 Nov design goals-create-template.php): My templates (saved goal
 * templates: rename, copy, delete, details) and the templates available to set a goal from,
 * filtered by view, category and object. Templates the CRM can't measure yet are locked
 * ("Coming soon") in place of the design's upgrade upsell.
 */
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';
import { errorText, isApiError } from '@/lib/api/errors';
import { deleteGoalTemplate, getGoalOptions, updateGoalTemplate } from '../api.client';
import { EMPTY_OPTIONS, labelOfDate, labelOfProperty, objectOf } from '../model';
import { useCanManageGoals } from '../permissions';
import type { GoalOptions, GoalTemplate } from '../types';
import { useToast } from '@/components/crm/ToastProvider';

type Icon = 'purple' | 'green' | 'orange' | 'gray';

interface Card {
  id: string;
  section: 'my' | 'available';
  name: string;
  desc: string;
  category: string;
  object: string;
  property: string;
  aggregation: string;
  unit: string;
  filterField: string;
  filterValue: string;
  icon: Icon;
  /** Where "Set goal" goes; null = locked (coming soon). */
  href: string | null;
  saved?: GoalTemplate;
}

const AVAILABLE: Array<Omit<Card, 'section' | 'desc' | 'id'> & { key: string }> = [
  {
    key: 'quota',
    name: 'Quota',
    category: 'Sales',
    object: 'Deal',
    property: 'Amount',
    aggregation: 'Sum',
    unit: 'Currency',
    filterField: 'Close date',
    filterValue: 'In the goal period (won deals)',
    icon: 'purple',
    href: '/goals/new?preset=quota',
  },
  {
    key: 'forecastable_quota',
    name: 'Forecastable Quota',
    category: 'Sales',
    object: 'Deal',
    property: 'Amount',
    aggregation: 'Sum',
    unit: 'Currency',
    filterField: 'Close date',
    filterValue: 'In the goal period (won deals)',
    icon: 'purple',
    href: '/goals/new?template=forecastable_quota',
  },
  {
    key: 'deals_created',
    name: 'Deals created',
    category: 'Sales',
    object: 'Deal',
    property: 'Record ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Create date',
    filterValue: 'In the goal period',
    icon: 'purple',
    href: '/goals/new?template=deals_created',
  },
  {
    key: 'contacts_lifecycle',
    name: 'Number of contacts in a lifecycle stage',
    category: 'Marketing',
    object: 'Contact',
    property: 'Lifecycle Stage',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Lifecycle stage',
    filterValue: 'Lead, Marketing Qualified Lead, Opportunity',
    icon: 'green',
    href: null,
  },
  {
    key: 'tasks_completed',
    name: 'Tasks completed',
    category: 'Sales',
    object: 'Engagement',
    property: 'Record ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Completed date',
    filterValue: 'In the goal period',
    icon: 'purple',
    href: '/goals/new?preset=tasks_completed',
  },
  {
    key: 'leads_created',
    name: 'Leads created',
    category: 'Sales',
    object: 'Lead',
    property: 'Record ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Create date',
    filterValue: 'In the goal period',
    icon: 'purple',
    href: '/goals/new?template=leads_created',
  },
  {
    key: 'conversations_closed',
    name: 'Conversations closed',
    category: 'Customer service',
    object: 'Engagement',
    property: 'Thread ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Conversation status',
    filterValue: 'Closed',
    icon: 'orange',
    href: null,
  },
  {
    key: 'meetings_booked',
    name: 'Meetings booked',
    category: 'Sales',
    object: 'Meeting',
    property: 'Record ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Meeting start time',
    filterValue: 'In the goal period (not cancelled)',
    icon: 'purple',
    href: '/goals/new?template=meetings_booked',
  },
  {
    key: 'tickets_closed',
    name: 'Tickets closed',
    category: 'Customer service',
    object: 'Engagement',
    property: 'Ticket ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Ticket status',
    filterValue: 'Closed, Resolved',
    icon: 'orange',
    href: null,
  },
  {
    key: 'network_conversions',
    name: 'Network conversions',
    category: 'Marketing',
    object: 'CTA Submission',
    property: 'Submission ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Conversion source',
    filterValue: 'Network campaigns',
    icon: 'green',
    href: null,
  },
  {
    key: 'notes_created',
    name: 'Notes created',
    category: 'Sales',
    object: 'Engagement',
    property: 'Record ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Create date',
    filterValue: 'In the goal period',
    icon: 'purple',
    href: '/goals/new?preset=notes_created',
  },
  {
    key: 'ticket_resolution',
    name: 'Average ticket resolution time',
    category: 'Customer service',
    object: 'Engagement',
    property: 'Time to close',
    aggregation: 'Average',
    unit: 'Hours',
    filterField: 'Pipeline',
    filterValue: 'Support Pipeline',
    icon: 'orange',
    href: null,
  },
  {
    key: 'cost_per_contact',
    name: 'Cost per contact in a lifecycle stage',
    category: 'Marketing',
    object: 'Contact',
    property: 'Acquisition cost',
    aggregation: 'Average',
    unit: 'Currency',
    filterField: 'Lifecycle stage',
    filterValue: 'Customer, Opportunity',
    icon: 'green',
    href: null,
  },
  {
    key: 'contacts_ads',
    name: 'Contacts from last ad interactions',
    category: 'Marketing',
    object: 'Contact',
    property: 'Contact ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Ad interaction source',
    filterValue: 'Google Ads, Meta Ads',
    icon: 'green',
    href: null,
  },
  {
    key: 'ticket_response',
    name: 'Average ticket response time',
    category: 'Customer service',
    object: 'Engagement',
    property: 'First response time',
    aggregation: 'Average',
    unit: 'Hours',
    filterField: 'Channel',
    filterValue: 'Email, Chat',
    icon: 'orange',
    href: null,
  },
  {
    key: 'emails_sent',
    name: 'Emails sent',
    category: 'Sales',
    object: 'Engagement',
    property: 'Record ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Activity date',
    filterValue: 'In the goal period (sent from the CRM)',
    icon: 'purple',
    href: '/goals/new?template=emails_sent',
  },
  {
    key: 'calls_made',
    name: 'Calls made',
    category: 'Sales',
    object: 'Call',
    property: 'Record ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Activity date',
    filterValue: 'In the goal period',
    icon: 'purple',
    href: '/goals/new?template=calls_made',
  },
  {
    key: 'activities_completed',
    name: 'Activities completed',
    category: 'Sales',
    object: 'Engagement',
    property: 'Record ID',
    aggregation: 'Count',
    unit: 'Number',
    filterField: 'Completed date',
    filterValue: 'In the goal period (completed tasks)',
    icon: 'purple',
    href: '/goals/new?template=activities_completed',
  },
];

const CATEGORIES = ['Customer service', 'Marketing', 'Sales'];
const OBJECTS = [
  'Call',
  'Company',
  'Contact',
  'CTA Submission',
  'Deal',
  'Engagement',
  'Event',
  'Lead',
  'Line Item',
  'Meeting',
];

function CardIcon({ icon }: { icon: Icon }) {
  if (icon === 'gray') {
    return (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      >
        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
        <polyline points="14 2 14 8 20 8" />
        <line x1="16" y1="13" x2="8" y2="13" />
        <line x1="16" y1="17" x2="8" y2="17" />
        <polyline points="10 9 9 9 8 9" />
      </svg>
    );
  }
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      {icon === 'purple' ? (
        <path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z" />
      ) : icon === 'green' ? (
        <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83" />
      ) : (
        <>
          <path d="M3 18v-6a9 9 0 0 1 18 0v6" />
          <path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z" />
        </>
      )}
    </svg>
  );
}

function myCard(t: GoalTemplate, options: GoalOptions): Card {
  const d = t.definition;
  const o = objectOf(options.catalogue, d.objectType);
  const currency =
    d.aggregation !== 'COUNT' && o?.properties.find((p) => p.key === d.property)?.currency;
  return {
    id: t.id,
    section: 'my',
    name: t.name,
    desc: t.description ?? '',
    category: 'Sales',
    object: o?.label ?? d.objectType,
    property: labelOfProperty(options.catalogue, d.objectType, d.property),
    aggregation:
      d.aggregation === 'COUNT'
        ? 'Count'
        : d.aggregation.charAt(0) + d.aggregation.slice(1).toLowerCase(),
    unit: currency ? 'Currency' : 'Number',
    filterField: labelOfDate(options.catalogue, d.objectType, d.dateProperty),
    filterValue: 'In the goal period',
    icon: 'gray',
    href: '/goals/new?templateId=' + encodeURIComponent(t.id),
    saved: t,
  };
}

type Filter = { type: 'view' | 'category' | 'object'; value: string; label: string };

export function GoalTemplatesView() {
  const router = useRouter();
  const canManage = useCanManageGoals();
  const toast = useToast();
  const [options, setOptions] = useState<GoalOptions | null>(null);
  const [filter, setFilter] = useState<Filter>({
    type: 'view',
    value: 'all',
    label: 'All templates',
  });
  const [noticeOpen, setNoticeOpen] = useState(true);
  const [sideOpen, setSideOpen] = useState(false);
  const [acc, setAcc] = useState({ category: true, object: true });
  const [edit, setEdit] = useState<{ id: string; name: string; desc: string } | null>(null);
  const [drop, setDrop] = useState<string | null>(null);
  const [details, setDetails] = useState<Card | null>(null);
  const [filtersOpen, setFiltersOpen] = useState(true);
  const [del, setDel] = useState<Card | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    const ac = new AbortController();
    getGoalOptions({ signal: ac.signal })
      .then(setOptions)
      .catch((e: unknown) => {
        if (!ac.signal.aborted) toast(errorText(e), 'danger');
      });
    return () => ac.abort();
  }, [toast]);

  useEffect(() => {
    const onDown = (e: MouseEvent) => {
      const t = e.target as Element;
      if (!t.closest('[data-sidebar-wrapper]')) setSideOpen(false);
      if (!t.closest('.gt-card__edit-wrap')) setEdit(null);
      if (!t.closest('[data-dropdown-wrap]')) setDrop(null);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      setSideOpen(false);
      setEdit(null);
      setDrop(null);
      setDetails(null);
      setDel(null);
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, []);

  useEffect(() => {
    if (!details && !del) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = prev;
    };
  }, [details, del]);

  const opts = options ?? EMPTY_OPTIONS;
  const cards = useMemo<Card[]>(
    () => [
      ...opts.savedTemplates.map((t) => myCard(t, opts)),
      ...AVAILABLE.map((a) => ({
        ...a,
        id: 'tpl-' + a.key,
        section: 'available' as const,
        desc: '',
      })),
    ],
    [opts],
  );
  const visible = (c: Card) =>
    filter.type === 'view'
      ? filter.value === 'all' || c.section === 'my'
      : filter.type === 'category'
        ? c.category === filter.value
        : c.object === filter.value;
  const my = cards.filter((c) => c.section === 'my' && visible(c));
  const avail = cards.filter((c) => c.section === 'available' && visible(c));
  const apply = (f: Filter) => {
    setFilter(f);
    setSideOpen(false);
    setEdit(null);
    setDrop(null);
  };
  const triggerLabel =
    filter.type === 'view'
      ? filter.label
      : filter.type.charAt(0).toUpperCase() + filter.type.slice(1) + ': ' + filter.label;

  const saveEdit = async () => {
    if (!edit) return;
    const name = edit.name.trim();
    if (!name) {
      toast('Enter a template name', 'danger');
      return;
    }
    try {
      const t = await updateGoalTemplate(edit.id, { name, description: edit.desc.trim() || null });
      setOptions((o) =>
        o ? { ...o, savedTemplates: o.savedTemplates.map((x) => (x.id === t.id ? t : x)) } : o,
      );
      setEdit(null);
      toast('Template updated', 'success');
    } catch (e) {
      toast(
        isApiError(e) && e.status === 409
          ? 'A template with this name already exists.'
          : errorText(e),
        'danger',
      );
    }
  };

  const confirmDelete = async () => {
    if (!del?.saved) return;
    setBusy(true);
    try {
      await deleteGoalTemplate(del.saved.id);
      setOptions((o) =>
        o ? { ...o, savedTemplates: o.savedTemplates.filter((x) => x.id !== del.saved!.id) } : o,
      );
      toast('Template "' + del.name + '" deleted', 'info');
      setDel(null);
    } catch (e) {
      toast(errorText(e), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const navItem = (
    type: Filter['type'],
    value: string,
    label: string,
    cls: 'gt-nav-item' | 'gt-nav-subitem',
  ) => {
    const on = filter.type === type && filter.value === value;
    return (
      <button
        key={type + value}
        type="button"
        className={cls + (on ? ' is-active' : '')}
        role={cls === 'gt-nav-item' ? 'tab' : undefined}
        aria-selected={cls === 'gt-nav-item' ? on : undefined}
        onClick={() => apply({ type, value, label })}
      >
        {label}
      </button>
    );
  };

  const cardNode = (c: Card) => {
    const locked = c.href === null;
    const editing = edit?.id === c.id;
    return (
      <article
        key={c.id}
        className={
          'gt-card' +
          (c.section === 'my' ? ' gt-card--custom' : '') +
          (locked ? ' gt-card--locked' : '')
        }
      >
        {c.section === 'my' && canManage ? (
          <div className="gt-card__edit-wrap">
            <button
              type="button"
              className={'gt-card__edit-btn' + (editing ? ' is-active' : '')}
              aria-label="Edit the name and description of this template"
              onClick={() => {
                setDrop(null);
                setEdit(editing ? null : { id: c.id, name: c.name, desc: c.desc });
              }}
            >
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                aria-hidden="true"
              >
                <path d="M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z" />
              </svg>
            </button>
            <div
              className={'gt-tooltip' + (editing ? ' is-hidden' : '')}
              role="tooltip"
              aria-hidden="true"
            >
              <span>Edit the name and description of this template</span>
              <div className="gt-tooltip__arrow" />
            </div>
            {editing ? (
              <div className="gt-popover" role="dialog" aria-label="Edit template">
                <div className="gt-popover__arrow" />
                <div className="gt-popover__body">
                  <div className="gt-form-group">
                    <label className="gt-label" htmlFor={'edit-name-' + c.id}>
                      Name
                    </label>
                    <input
                      type="text"
                      id={'edit-name-' + c.id}
                      className="gt-input"
                      value={edit.name}
                      maxLength={100}
                      autoFocus
                      onChange={(e) => setEdit({ ...edit, name: e.target.value })}
                    />
                  </div>
                  <div className="gt-form-group">
                    <label className="gt-label" htmlFor={'edit-desc-' + c.id}>
                      Description
                    </label>
                    <textarea
                      id={'edit-desc-' + c.id}
                      className="gt-textarea"
                      rows={4}
                      maxLength={500}
                      value={edit.desc}
                      onChange={(e) => setEdit({ ...edit, desc: e.target.value })}
                    />
                  </div>
                  <div className="gt-popover__actions">
                    <button
                      type="button"
                      className="btn-crm btn-crm--teal btn-crm--pill gt-btn-save"
                      onClick={() => void saveEdit()}
                    >
                      Save
                    </button>
                    <button
                      type="button"
                      className="btn-crm btn-crm--outline btn-crm--pill gt-btn-cancel"
                      onClick={() => setEdit(null)}
                    >
                      Cancel
                    </button>
                  </div>
                </div>
              </div>
            ) : null}
          </div>
        ) : null}
        <div className={'gt-card__icon gt-card__icon--' + c.icon} aria-hidden="true">
          <CardIcon icon={c.icon} />
        </div>
        <h3 className="gt-card__title">{c.name}</h3>
        {c.desc ? <p className="gt-card__desc">{c.desc}</p> : null}
        {locked ? (
          <div className="gt-card__actions gt-card__actions--stacked">
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--pill gt-btn-upgrade"
              disabled
              title="Coming soon"
            >
              <span>Coming soon</span>
              <svg
                className="gt-icon-lock"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                aria-hidden="true"
              >
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                <path d="M7 11V7a5 5 0 0 1 10 0v4" />
              </svg>
            </button>
            <button type="button" className="gt-link-details" onClick={() => setDetails(c)}>
              View details
            </button>
          </div>
        ) : (
          <div className="gt-card__actions">
            {canManage ? (
              <Link href={c.href!} className="btn-crm btn-crm--outline btn-crm--pill gt-btn-set">
                Set goal
              </Link>
            ) : null}
            {c.section === 'my' && canManage ? (
              <div className="gt-actions-dropdown" data-dropdown-wrap>
                <button
                  type="button"
                  className={'gt-btn-actions' + (drop === c.id ? ' is-active' : '')}
                  aria-expanded={drop === c.id}
                  aria-haspopup="true"
                  onClick={() => {
                    setEdit(null);
                    setDrop(drop === c.id ? null : c.id);
                  }}
                >
                  <span>Actions</span>
                  <svg
                    className="gt-chevron-actions"
                    viewBox="0 0 12 8"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    aria-hidden="true"
                  >
                    <path d="m1 2 5 4 5-4" />
                  </svg>
                </button>
                {drop === c.id ? (
                  <div className="gt-dropdown-menu" role="menu">
                    <div className="gt-dropdown-arrow" />
                    <Link
                      href={'/goals/templates/new?copy=' + encodeURIComponent(c.id)}
                      className="gt-dropdown-item"
                      role="menuitem"
                    >
                      <span className="gt-dropdown-icon">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
                          <path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
                        </svg>
                      </span>
                      <span className="gt-dropdown-text">
                        <strong>Copy template</strong>
                        <small>Copy and create a new template based on this one.</small>
                      </span>
                    </Link>
                    <button
                      type="button"
                      className="gt-dropdown-item gt-dropdown-item--danger"
                      role="menuitem"
                      onClick={() => {
                        setDrop(null);
                        setDel(c);
                      }}
                    >
                      <span className="gt-dropdown-icon">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M10 11v6M14 11v6" />
                        </svg>
                      </span>
                      <span className="gt-dropdown-text">
                        <strong>Delete template</strong>
                        <small>Permanently delete this template. This can{'’'}t be undone.</small>
                      </span>
                    </button>
                  </div>
                ) : null}
              </div>
            ) : null}
            <button type="button" className="gt-link-details" onClick={() => setDetails(c)}>
              View details
            </button>
          </div>
        )}
      </article>
    );
  };

  return (
    <div className="gt-page" data-goals-template-page>
      <header className="gt-header">
        <Link href="/goals" className="gt-back-link">
          <svg
            className="gt-icon-back"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
          >
            <path d="m15 18-6-6 6-6" />
          </svg>
          <span>Back to goals</span>
        </Link>
        <div className="gt-header-bar">
          <h1 className="gt-title">Goal templates</h1>
          {canManage ? (
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--pill gt-btn-create"
              onClick={() => router.push('/goals/templates/new')}
            >
              Create new template
            </button>
          ) : null}
        </div>
        <div className={'gt-notice' + (noticeOpen ? '' : ' is-dismissed')} role="alert">
          <div className="gt-notice__content">
            <strong className="gt-notice__title">Some goal template names have changed</strong>
            <span className="gt-notice__text">
              Some goal template names have been updated.{' '}
              <a
                href="#learn-what-changed"
                className="gt-notice__link"
                onClick={(e) => {
                  e.preventDefault();
                  toast('Documentation is coming soon', 'info');
                }}
              >
                Learn what changed {'↗'}
              </a>
            </span>
          </div>
          <button
            type="button"
            className="gt-notice__close"
            aria-label="Dismiss notice"
            onClick={() => setNoticeOpen(false)}
          >
            {'×'}
          </button>
        </div>
      </header>

      <div className="gt-layout">
        <div className={'gt-sidebar-wrapper' + (sideOpen ? ' is-open' : '')} data-sidebar-wrapper>
          <button
            type="button"
            className="gt-filter-trigger"
            aria-expanded={sideOpen}
            aria-controls="gt-sidebar-panel"
            onClick={() => setSideOpen(!sideOpen)}
          >
            <span className="gt-filter-trigger__left">
              <svg
                className="gt-filter-trigger__icon iconSize-14"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                aria-hidden="true"
              >
                <line x1="4" y1="6" x2="20" y2="6" />
                <line x1="6" y1="12" x2="18" y2="12" />
                <line x1="8" y1="18" x2="16" y2="18" />
              </svg>
              <span className="gt-filter-trigger__label">{triggerLabel}</span>
            </span>
            <svg
              className="gt-filter-trigger__chevron iconSize-14"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </button>
          <aside
            className={'gt-sidebar' + (sideOpen ? ' is-open' : '')}
            id="gt-sidebar-panel"
            aria-label="Filter templates"
          >
            <nav className="gt-nav-list" role="tablist">
              {navItem('view', 'all', 'All templates', 'gt-nav-item')}
              {navItem('view', 'my', 'My templates', 'gt-nav-item')}
              <div className="gt-nav-divider" role="separator" />
              {(['category', 'object'] as const).map((kind, i) => (
                <span key={kind} style={{ display: 'contents' }}>
                  {i ? <div className="gt-nav-divider" role="separator" /> : null}
                  <div className={'gt-accordion' + (acc[kind] ? ' is-open' : '')}>
                    <button
                      type="button"
                      className="gt-accordion-header"
                      aria-expanded={acc[kind]}
                      onClick={() => setAcc({ ...acc, [kind]: !acc[kind] })}
                    >
                      <span className="gt-accordion-title">
                        {kind === 'category' ? 'Category' : 'Object'}
                      </span>
                      <svg
                        className="gt-accordion-chevron"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        aria-hidden="true"
                      >
                        <path d="m18 15-6-6-6 6" />
                      </svg>
                    </button>
                    <div className="gt-accordion-body">
                      {(kind === 'category' ? CATEGORIES : OBJECTS).map((v) =>
                        navItem(kind, v, v, 'gt-nav-subitem'),
                      )}
                    </div>
                  </div>
                </span>
              ))}
            </nav>
          </aside>
        </div>

        <main className="gt-content">
          {my.length + avail.length ? (
            <div className="gt-templates-container">
              {my.length ? (
                <section className="gt-section">
                  <h2 className="gt-section-heading">My templates</h2>
                  <div className="gt-grid">{my.map(cardNode)}</div>
                </section>
              ) : null}
              {avail.length ? (
                <section className="gt-section">
                  <h2 className="gt-section-heading">Available with your plan</h2>
                  <div className="gt-grid">{avail.map(cardNode)}</div>
                </section>
              ) : null}
            </div>
          ) : (
            <section className="gt-empty-state" aria-live="polite">
              <div className="gt-empty-state__content">
                <h2 className="gt-empty-state__title">No templates found</h2>
                <p className="gt-empty-state__text">
                  No <span>{filter.label}</span> templates found.
                </p>
              </div>
              <div className="gt-empty-state__art" aria-hidden="true">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src="/crm/assets/img/no-template.svg" alt="Isometric 3D Chart Illustration" />
              </div>
            </section>
          )}
        </main>
      </div>

      {details ? (
        <div className="gt-modal-wrap">
          <div className="gt-modal-backdrop" onClick={() => setDetails(null)} />
          <div
            className="gt-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="gt-modal-title"
          >
            <div className="gt-modal__header">
              <h2 id="gt-modal-title" className="gt-modal__title">
                {details.name}
              </h2>
              <button
                type="button"
                className="gt-modal__close-btn"
                aria-label="Close dialog"
                onClick={() => setDetails(null)}
              >
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <line x1="18" y1="6" x2="6" y2="18" />
                  <line x1="6" y1="6" x2="18" y2="18" />
                </svg>
              </button>
            </div>
            <div className="gt-modal__body">
              <div className="gt-modal__content-grid">
                <div className="gt-modal__details-col">
                  <h3 className="gt-modal__section-heading">About this goal</h3>
                  <div className="gt-detail-row">
                    <span className="gt-detail-label">Category:</span>
                    <span className="gt-detail-value">{details.category}</span>
                  </div>
                  <div className="gt-detail-row">
                    <span className="gt-detail-label">Object used:</span>
                    <span className="gt-detail-value">{details.object}</span>
                  </div>
                  <div className="gt-detail-row">
                    <span className="gt-detail-label">Property used:</span>
                    <span className="gt-detail-value">{details.property}</span>
                  </div>
                  <div className="gt-detail-block">
                    <span className="gt-detail-block__label">How data is aggregated?</span>
                    <span className="gt-detail-block__value">{details.aggregation}</span>
                  </div>
                  <div className="gt-detail-block">
                    <span className="gt-detail-block__label">
                      What unit of measurement is used?
                    </span>
                    <span className="gt-detail-block__value">{details.unit}</span>
                  </div>
                  <div className={'gt-filters-accordion' + (filtersOpen ? ' is-open' : '')}>
                    <button
                      type="button"
                      className="gt-filters-accordion__toggle"
                      aria-expanded={filtersOpen}
                      onClick={() => setFiltersOpen(!filtersOpen)}
                    >
                      <svg
                        className="gt-filters-chevron"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      >
                        <path d="m6 9 6 6 6-6" />
                      </svg>
                      <span>What filters are being applied?</span>
                    </button>
                    <div className="gt-filters-accordion__panel">
                      <div className="gt-filter-group-card">
                        <h4 className="gt-filter-group-title">Group 1</h4>
                        <div className="gt-filter-pill-wrap">
                          <div className="gt-filter-pill">
                            <span className="gt-filter-pill__field">{details.filterField}</span>
                            <span className="gt-filter-pill__op">is any of</span>
                            <strong className="gt-filter-pill__val">{details.filterValue}</strong>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="gt-modal__art-col" aria-hidden="true">
                  <svg
                    className="gt-funnel-illustration"
                    viewBox="0 0 160 180"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <ellipse
                      cx="80"
                      cy="154"
                      rx="42"
                      ry="14"
                      fill="#FDF4E6"
                      stroke="#E5D6BD"
                      strokeWidth="1.5"
                    />
                    <path d="M38 154 L80 172 L122 154 L122 159 L80 177 L38 159 Z" fill="#D9C7AC" />
                    <circle
                      cx="98"
                      cy="148"
                      r="4.5"
                      fill="#00BDA5"
                      stroke="#2D3E50"
                      strokeWidth="1.5"
                    />
                    <path
                      d="M74 100 L74 134 C74 138, 77 141, 81 141 L92 141 C96 141, 99 138, 99 134 L99 130"
                      fill="none"
                      stroke="#2D3E50"
                      strokeWidth="7"
                      strokeLinecap="round"
                    />
                    <path
                      d="M74 100 L74 134 C74 138, 77 141, 81 141 L92 141 C96 141, 99 138, 99 134 L99 130"
                      fill="none"
                      stroke="#486581"
                      strokeWidth="4"
                      strokeLinecap="round"
                    />
                    <path
                      d="M54 62 L74 102 L86 102 L106 62 Z"
                      fill="#486581"
                      stroke="#2D3E50"
                      strokeWidth="2.5"
                      strokeLinejoin="round"
                    />
                    <path d="M60 66 L75 98 L85 98 L98 66 Z" fill="#627D98" />
                    <ellipse
                      cx="80"
                      cy="62"
                      rx="28"
                      ry="10"
                      fill="#334E68"
                      stroke="#2D3E50"
                      strokeWidth="2.5"
                    />
                    <ellipse cx="80" cy="62" rx="22" ry="7.5" fill="#102A43" />
                    <circle
                      cx="80"
                      cy="38"
                      r="6.5"
                      fill="#3B82F6"
                      stroke="#2D3E50"
                      strokeWidth="1.8"
                    />
                    <circle cx="78" cy="36" r="2" fill="#93C5FD" />
                    <circle
                      cx="68"
                      cy="48"
                      r="5"
                      fill="#38BDF8"
                      stroke="#2D3E50"
                      strokeWidth="1.8"
                    />
                    <circle
                      cx="88"
                      cy="48"
                      r="5.5"
                      fill="#00BDA5"
                      stroke="#2D3E50"
                      strokeWidth="1.8"
                    />
                    <circle
                      cx="78"
                      cy="56"
                      r="6"
                      fill="#FF7A59"
                      stroke="#2D3E50"
                      strokeWidth="1.8"
                    />
                    <circle cx="76" cy="54" r="1.8" fill="#FFB7A5" />
                    <circle
                      cx="94"
                      cy="58"
                      r="4.5"
                      fill="#84CC16"
                      stroke="#2D3E50"
                      strokeWidth="1.5"
                    />
                  </svg>
                </div>
              </div>
            </div>
            <div className="gt-modal__footer">
              <button
                type="button"
                className="btn-crm btn-crm--primary btn-crm--pill gt-btn-got-it"
                autoFocus
                onClick={() => setDetails(null)}
              >
                Got it
              </button>
            </div>
          </div>
        </div>
      ) : null}

      {del ? (
        <div className="gt-modal-wrap">
          <div className="gt-modal-backdrop" onClick={() => setDel(null)} />
          <div
            className="gt-modal gt-modal--delete"
            role="dialog"
            aria-modal="true"
            aria-labelledby="gt-delete-title"
          >
            <div className="gt-modal__header">
              <h2 id="gt-delete-title" className="gt-modal__title">
                Delete template
              </h2>
              <button
                type="button"
                className="gt-modal__close-btn"
                aria-label="Close dialog"
                onClick={() => setDel(null)}
              >
                {'×'}
              </button>
            </div>
            <div className="gt-modal__body">
              <p className="gt-delete-text">
                Are you sure you want to delete <strong>&quot;{del.name}&quot;</strong>? This
                template will be permanently removed and this action cannot be undone.
              </p>
            </div>
            <div className="gt-modal__footer gt-modal__footer--flush">
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--pill"
                onClick={() => setDel(null)}
              >
                Cancel
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--danger btn-crm--pill"
                disabled={busy}
                onClick={() => void confirmDelete()}
              >
                Delete
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}
