'use client';

import Link from 'next/link';
import {
  useCallback,
  useEffect,
  useRef,
  useState,
  type CSSProperties,
  type DragEvent,
} from 'react';
import { Alert } from '@/components/crm/Alert';
import { useToast } from '@/components/crm/ToastProvider';
import { actionErrorText, useUserPrefs } from '@/features/contacts/ui/actions/shared';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { changeObjectRecordStage, getObjectBoard, updateObjectRecord } from '../api.client';
import { EMPTY, formatDateTime } from '../columns';
import { saveErrorText } from '../errors';
import { disqualificationReasons, isLeadObject } from '../leads';
import { objectRecordPath } from '../paths';
import { chipOf, type ChipTone, type ObjectPreset } from '../presets';
import type { ObjectSchema } from '../useObjectSchema';
import type { CustomValues, ObjectBoard, ObjectBoardColumn, ObjectRecord } from '../types';
import { Avatar } from '@/features/list-page/ui/RecordAvatar';
import { LpIcon } from '@/features/list-page/ui/LpIcon';
import { Icon } from './icons';
import { ConvertLeadDrawer } from './lead/ConvertLeadDrawer';
import { DisqualifyDialog, QualifyDialog } from './lead/LeadStageDialogs';
import {
  boardColumnStyle,
  requiredNames,
  shownStageColor,
  stageColor,
  stageRequirementsOf,
} from '@/features/pipelines/stageRules';
import { StageName } from '@/features/pipelines/ui/StageName';
import { StagePill } from '@/features/pipelines/ui/StagePill';
import { useRecordStageGate } from '@/features/pipelines/ui/useStageGate';

const PER_COLUMN = 20;
/** The most cards a column may load (the API's limit). */
const PER_COLUMN_MAX = 100;

function initials(name: string): string {
  return (
    name
      .split(/\s+/)
      .filter(Boolean)
      .slice(0, 2)
      .map((p) => p[0]?.toUpperCase() ?? '')
      .join('') || '?'
  );
}

/**
 * `.evl-board`: the records in columns by stage, owner or a dropdown field, with each column's
 * count. Dragging a card to another column changes the record's stage (stage history is kept),
 * owner or field; the card moves at once and goes back if the API refuses.
 */
export function ObjectBoardView({
  schema,
  groupBy,
  pipelineId,
  search,
  filter,
  reloadKey,
  preset,
  canEditRecord,
  onPreview,
  onAssign,
  onTotal,
  onMoved,
  card,
  values,
}: {
  schema: ObjectSchema;
  /** `stage`, `owner` or `custom.<field>`. */
  groupBy: string;
  pipelineId: string | undefined;
  search: string;
  /** The view's filter and the page's, as JSON. */
  filter: string | undefined;
  /** Changes when the list should load again (a record was created, edited, …). */
  reloadKey: number;
  /** The object's defaults (HUB-267); with one, cards are drawn as the ticket design shows. */
  preset: ObjectPreset | null;
  /** Whether the user may change this record (the permission set's edit scope). */
  canEditRecord: (record: ObjectRecord) => boolean;
  onPreview: (record: ObjectRecord, edit: boolean) => void;
  onAssign: (record: ObjectRecord) => void;
  /** Records on the board (all columns), for the page's count. */
  onTotal: (total: number | null) => void;
  /** LP4 (L-B12): a card was moved and saved (the page refreshes its metrics strip). */
  onMoved?: () => void;
  /**
   * The 28 Oct list design's card (leads): avatar, name and preview, "Label: value" lines, the
   * owner chip and a date.
   */
  card?: {
    lines: (record: ObjectRecord) => Array<[string, string]>;
    meta?: (record: ObjectRecord) => string | undefined;
    /** EV4: the record's initials before its name; Events have none (list-page.js:2266). */
    avatar?: boolean;
  };
  /**
   * Board settings > Select property values (28 Oct design): the columns to show, in order
   * (`''` is "No value"); every column when left out.
   */
  values?: string[] | null;
}) {
  const toast = useToast();
  const { definition, pipelines } = schema;
  const [board, setBoard] = useState<ObjectBoard | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [perColumn, setPerColumn] = useState(PER_COLUMN);
  const [movingId, setMovingId] = useState<string | null>(null);
  const [dropKey, setDropKey] = useState<string | null | undefined>(undefined);
  const dragRef = useRef<{ id: string; from: string | null } | null>(null);
  /**
   * Leads (HUB-340): a card dropped on Disqualified waits for the reason, one dropped on
   * Qualified for "convert or just qualify"; it moves only once that is answered.
   */
  const [pending, setPending] = useState<{
    kind: 'disqualify' | 'qualify' | 'convert';
    record: ObjectRecord;
    from: string;
    to: string;
    stageName: string;
  } | null>(null);
  /** The dialogs stay mounted and keep the last card while they close (like the record pages). */
  const [pendingOpen, setPendingOpen] = useState(false);
  const closePending = () => setPendingOpen(false);
  const isLead = isLeadObject(definition);
  // LP5: "Set pipeline display colors" for the column names.
  const stageDisplay = definition.stageDisplayStyle ?? 'none';
  // 24 Nov: required fields to enter a stage, and a ticket's resolution when it closes.
  const gate = useRecordStageGate(schema);
  const pipelineName = new Map(pipelines.map((p) => [p.id, p.name]));
  const chipLabels = new Map(
    (schema.defs.find((d) => d.name === preset?.chip?.field)?.options ?? []).map((o) => [
      o.value,
      o.label,
    ]),
  );
  const chipFor = (record: ObjectRecord) =>
    preset?.chip
      ? chipOf(
          preset,
          record.customProperties[preset.chip.field],
          chipLabels.get(String(record.customProperties[preset.chip.field] ?? '')),
        )
      : null;

  const load = useCallback(
    async (signal?: AbortSignal) => {
      setLoading(true);
      setError(null);
      try {
        const next = await getObjectBoard(
          definition.key,
          {
            groupBy,
            perColumn,
            ...(groupBy === 'stage' && pipelineId ? { pipelineId } : {}),
            ...(search ? { search } : {}),
            ...(filter ? { filter } : {}),
          },
          { signal },
        );
        if (!signal?.aborted) {
          setBoard(next);
          onTotal(next.columns.reduce((sum, col) => sum + col.count, 0));
        }
      } catch (err) {
        if (!signal?.aborted) setError(errorText(err));
      } finally {
        if (!signal?.aborted) setLoading(false);
      }
    },
    [definition.key, groupBy, perColumn, pipelineId, search, filter, onTotal],
  );

  useEffect(() => {
    const controller = new AbortController();
    void load(controller.signal);
    return () => controller.abort();
  }, [load, reloadKey]);

  const keyOf = (col: ObjectBoardColumn) => col.key ?? '';

  /** The record moved from one column to another, on the page only. */
  const shift = (prev: ObjectBoard, record: ObjectRecord, from: string, to: string) => ({
    ...prev,
    columns: prev.columns.map((col) => {
      if (keyOf(col) === from) {
        return {
          ...col,
          count: col.count - 1,
          records: col.records.filter((r) => r.id !== record.id),
        };
      }
      if (keyOf(col) === to) {
        return { ...col, count: col.count + 1, records: [record, ...col.records] };
      }
      return col;
    }),
  });

  /** The pipeline stage of a column (its settings: colour, required properties). */
  const stageOf = (id: string | null | undefined) =>
    id ? (pipelines.flatMap((p) => p.stages).find((s) => s.id === id) ?? null) : null;

  /** A card's record replaced by a newer copy (fields saved by the stage gate). */
  const replaceCard = (saved: ObjectRecord) =>
    setBoard((prev) =>
      prev
        ? {
            ...prev,
            columns: prev.columns.map((col) => ({
              ...col,
              records: col.records.map((r) =>
                r.id === saved.id ? { ...saved, linkCounts: r.linkCounts } : r,
              ),
            })),
          }
        : prev,
    );

  /**
   * Saves a move: the card moves at once and goes back when the API refuses (the error is
   * thrown). `fields` are saved with a stage move (a lead's disqualification, a ticket's
   * resolution).
   */
  const persist = async (
    record: ObjectRecord,
    from: string,
    to: string,
    fields?: CustomValues,
  ): Promise<ObjectRecord> => {
    const target = board?.columns.find((c) => keyOf(c) === to);
    setBoard((prev) => (prev ? shift(prev, record, from, to) : prev));
    setMovingId(record.id);
    try {
      let saved: ObjectRecord;
      if (groupBy === 'stage') {
        saved = await changeObjectRecordStage(definition.key, record.id, {
          stageId: to,
          updatedAt: record.updatedAt,
          ...(fields ? { customProperties: fields } : {}),
        });
      } else if (groupBy === 'owner') {
        saved = await updateObjectRecord(definition.key, record.id, {
          ownerId: to || null,
          updatedAt: record.updatedAt,
        });
      } else {
        const field = groupBy.slice('custom.'.length);
        saved = await updateObjectRecord(definition.key, record.id, {
          customProperties: { [field]: to || null },
          updatedAt: record.updatedAt,
        });
      }
      replaceCard(saved);
      onMoved?.();
      toast(
        `Moved ${record.displayName || 'the record'} to ${target?.label ?? 'the column'}.`,
        'success',
      );
      return saved;
    } catch (err) {
      setBoard((prev) => (prev ? shift(prev, record, to, from) : prev));
      // The card is stale: without a reload every later drag of it would conflict again.
      if (isApiError(err) && err.isConflict) void load();
      throw err;
    } finally {
      setMovingId(null);
    }
  };

  /**
   * Moves a card. Into a stage, the design's stage gate runs first: the stage's required fields
   * the record lacks, then a ticket's resolution, or a lead's Disqualify / Qualify dialog.
   * `confirmed` carries what that dialog asked for; a refusal is then thrown for it to show.
   */
  const move = async (
    recordId: string,
    from: string,
    to: string,
    confirmed?: { fields?: CustomValues },
  ) => {
    if (!board || from === to || movingId) return;
    let record = board.columns
      .find((c) => keyOf(c) === from)
      ?.records.find((r) => r.id === recordId);
    if (!record) return;
    const target = board.columns.find((c) => keyOf(c) === to);
    const stage =
      groupBy === 'stage'
        ? (stageOf(to) ??
          (target
            ? { id: to, name: target.label, stageType: target.stage?.stageType, properties: [] }
            : null))
        : null;
    try {
      if (stage && !confirmed) {
        if (requiredNames(stage).length) {
          const filled = await gate.fillRequired(record, stage);
          if (!filled) return;
          record = filled;
          replaceCard(filled);
        }
        const closing = isLead ? target?.stage?.stageType : undefined;
        if (closing === 'lost' || closing === 'won') {
          setPending({
            kind: closing === 'lost' ? 'disqualify' : 'qualify',
            record,
            from,
            to,
            stageName: target?.label ?? '',
          });
          setPendingOpen(true);
          return;
        }
      }
      try {
        await persist(record, from, to, confirmed?.fields);
      } catch (err) {
        // Required fields set meanwhile: ask for the ones the API names, then move again.
        const names = stage ? stageRequirementsOf(err) : null;
        if (!stage || !names) throw err;
        const filled = await gate.fillRequired(record, stage, names);
        if (!filled) return;
        await persist(filled, from, to, confirmed?.fields);
      }
    } catch (err) {
      if (confirmed) throw new Error(saveErrorText(err, schema.defs));
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    }
  };

  const onDragStart = (e: DragEvent<HTMLElement>, record: ObjectRecord, from: string) => {
    dragRef.current = { id: record.id, from };
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', record.id);
  };

  if (error && !board) return <Alert tone="danger">{error}</Alert>;
  if (!board) {
    return (
      <div className="lp-content">
        <div className="lp-empty">
          <p>Loading board…</p>
        </div>
      </div>
    );
  }

  const canLoadMore =
    perColumn < PER_COLUMN_MAX && board.columns.some((c) => c.records.length < c.count);
  const shownColumns = values
    ? values.flatMap((v) => board.columns.filter((c) => keyOf(c) === v))
    : board.columns;

  return (
    <div className={cn('lp-content', loading && 'is-loading')}>
      {error ? <Alert tone="danger">{error}</Alert> : null}
      <div className="lp-boardwrap">
        <div className="lp-board" role="list">
          {shownColumns.map((col) => {
            const key = keyOf(col);
            const color =
              groupBy === 'stage' && col.stage
                ? shownStageColor(
                    {
                      name: col.label,
                      stageType: col.stage.stageType,
                      color: col.stage.color ?? stageOf(key)?.color,
                    },
                    { lead: isLead },
                  )
                : null;
            return (
              <section
                key={key || 'none'}
                className={cn('lp-col', color && 'lp-col--stage', dropKey === key && 'is-over')}
                style={color ? (boardColumnStyle(color) as CSSProperties) : undefined}
                aria-label={`${col.label}: ${col.count}`}
                onDragOver={(e) => {
                  if (!dragRef.current) return;
                  e.preventDefault();
                  e.dataTransfer.dropEffect = 'move';
                  if (dropKey !== key) setDropKey(key);
                }}
                onDragLeave={(e) => {
                  if (!e.currentTarget.contains(e.relatedTarget as Node | null))
                    setDropKey(undefined);
                }}
                onDrop={(e) => {
                  e.preventDefault();
                  setDropKey(undefined);
                  const drag = dragRef.current;
                  dragRef.current = null;
                  if (drag && drag.from !== null) void move(drag.id, drag.from, key);
                }}
              >
                <header className="lp-col__head">
                  {/* LP5: with a display style the name draws its own dot or badge. */}
                  {color && stageDisplay === 'none' ? (
                    <span className="lp-col__dot" aria-hidden="true" />
                  ) : null}
                  <span className="lp-col__name">
                    {groupBy === 'stage' && col.stage && stageDisplay !== 'none' ? (
                      <StageName
                        name={col.label}
                        color={stageColor(
                          {
                            name: col.label,
                            stageType: col.stage.stageType,
                            color: col.stage.color ?? stageOf(key)?.color,
                          },
                          { lead: isLead },
                        )}
                        style={stageDisplay}
                      />
                    ) : (
                      col.label
                    )}
                  </span>
                  <span className="lp-col__count">{col.count.toLocaleString()}</span>
                </header>
                <div className="lp-col__body">
                  {col.records.map((record) =>
                    card ? (
                      <DesignCard
                        key={record.id}
                        record={record}
                        lines={card.lines(record)}
                        meta={card.meta?.(record)}
                        avatar={card.avatar ?? true}
                        stageName={groupBy === 'stage' ? col.label : null}
                        moving={movingId === record.id}
                        canEdit={canEditRecord(record)}
                        columns={board.columns}
                        currentKey={key}
                        onDragStart={(e) => onDragStart(e, record, key)}
                        onDragEnd={() => {
                          dragRef.current = null;
                          setDropKey(undefined);
                        }}
                        onMove={(to) => void move(record.id, key, to)}
                        onPreview={onPreview}
                      />
                    ) : (
                      <BoardCard
                        key={record.id}
                        record={record}
                        pipeline={
                          record.pipelineId ? pipelineName.get(record.pipelineId) : undefined
                        }
                        showPipeline={definition.hasPipeline}
                        chip={chipFor(record)}
                        styled={preset !== null}
                        moving={movingId === record.id}
                        canEdit={canEditRecord(record)}
                        columns={board.columns}
                        currentKey={key}
                        stageName={groupBy === 'stage' ? col.label : null}
                        onDragStart={(e) => onDragStart(e, record, key)}
                        onDragEnd={() => {
                          dragRef.current = null;
                          setDropKey(undefined);
                        }}
                        onMove={(to) => void move(record.id, key, to)}
                        onPreview={onPreview}
                        onAssign={onAssign}
                      />
                    ),
                  )}
                  {col.records.length === 0 ? (
                    <p className="lp-col__empty">
                      {card ? `Drag ${definition.pluralLabel.toLowerCase()} here` : 'No records'}
                    </p>
                  ) : null}
                  {col.records.length < col.count ? (
                    <p className="lp-col__empty">
                      Showing {col.records.length} of {col.count.toLocaleString()}
                    </p>
                  ) : null}
                </div>
              </section>
            );
          })}
        </div>
      </div>
      {canLoadMore ? (
        <button
          type="button"
          className="lp-pill crm-mt-2"
          disabled={loading}
          onClick={() => setPerColumn(PER_COLUMN_MAX)}
        >
          Show up to {PER_COLUMN_MAX} cards per column
        </button>
      ) : null}
      {gate.dialogs}
      {isLead && pending ? (
        <>
          <DisqualifyDialog
            open={pendingOpen && pending.kind === 'disqualify'}
            leadName={pending.record.displayName || 'this lead'}
            reasons={disqualificationReasons(schema.defs)}
            initialReason={
              (pending.record.customProperties['hs_lead_disqualification_reason'] as
                string | undefined) ?? null
            }
            onClose={closePending}
            onConfirm={async (fields) => {
              await move(pending.record.id, pending.from, pending.to, { fields });
              closePending();
            }}
          />
          <QualifyDialog
            open={pendingOpen && pending.kind === 'qualify'}
            leadName={pending.record.displayName || 'this lead'}
            stageName={pending.stageName}
            converted={Boolean(pending.record.convertedDealId)}
            onClose={closePending}
            onConvert={() => setPending({ ...pending, kind: 'convert' })}
            onQualify={async () => {
              await move(pending.record.id, pending.from, pending.to, {});
              closePending();
            }}
          />
          <ConvertLeadDrawer
            open={pendingOpen && pending.kind === 'convert'}
            objectKey={definition.key}
            lead={pending.record}
            owners={schema.owners}
            onClose={() => {
              closePending();
              // A converted lead moved to Qualified: show it there.
              void load();
            }}
            onConverted={() => void load()}
          />
        </>
      ) : null}
    </div>
  );
}

function BoardCard({
  record,
  pipeline,
  showPipeline,
  chip,
  styled,
  moving,
  canEdit,
  columns,
  currentKey,
  stageName,
  onDragStart,
  onDragEnd,
  onMove,
  onPreview,
  onAssign,
}: {
  record: ObjectRecord;
  pipeline: string | undefined;
  showPipeline: boolean;
  /** The preset's chip field for this record, e.g. a ticket's priority. */
  chip: { label: string; tone: ChipTone } | null;
  /** The ticket design's card: the name, the chip and the owner's initials. */
  styled: boolean;
  moving: boolean;
  canEdit: boolean;
  columns: ObjectBoardColumn[];
  currentKey: string;
  /** Boards by stage: the column's stage, for the "In stage: Nd" pill. */
  stageName: string | null;
  onDragStart: (e: DragEvent<HTMLElement>) => void;
  onDragEnd: () => void;
  onMove: (to: string) => void;
  onPreview: (record: ObjectRecord, edit: boolean) => void;
  onAssign: (record: ObjectRecord) => void;
}) {
  const prefs = useUserPrefs();
  const datePrefs = { region: prefs.regionFormat, timeZone: prefs.timeZone };
  const name = record.displayName || 'Untitled';
  const noEdit = "Your permissions don't allow you to edit this record";
  const owner = record.owner?.name ?? null;
  return (
    <article
      className={cn('lp-bcard evl-card', styled && 'evl-card--rich', moving && 'is-moving')}
      draggable={!moving && canEdit}
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
    >
      <Link className="lp-bcard__name" href={objectRecordPath(record.objectKey, record.id)}>
        {name}
      </Link>
      {styled ? (
        <div className="evl-card__row">
          {chip ? <span className={`evl-chip evl-chip--${chip.tone}`}>{chip.label}</span> : null}
          <span
            className={cn('evl-card__avatar', !owner && 'is-none')}
            title={owner ? `Owner: ${owner}` : 'No owner'}
            aria-label={owner ? `Owner: ${owner}` : 'No owner'}
          >
            {owner ? initials(owner) : '—'}
          </span>
        </div>
      ) : (
        <dl className="evl-card__meta">
          <div>
            <dt>Owner:</dt>
            <dd>{owner ?? EMPTY}</dd>
          </div>
          {showPipeline ? (
            <div>
              <dt>Pipeline:</dt>
              <dd>{pipeline ?? EMPTY}</dd>
            </div>
          ) : null}
          <div>
            <dt>Object create date/time:</dt>
            <dd>{formatDateTime(record.createdAt, datePrefs)}</dd>
          </div>
          <div>
            <dt>Object last modified date/time:</dt>
            <dd>{formatDateTime(record.updatedAt, datePrefs)}</dd>
          </div>
        </dl>
      )}
      {stageName ? <StagePill stageName={stageName} record={record} /> : null}
      <div className="evl-card__tools">
        {/* Keyboard and touch users move cards with this menu instead of dragging. */}
        <select
          className="evl-card__move"
          aria-label={`Move ${name} to`}
          value={currentKey}
          disabled={moving || !canEdit}
          title={canEdit ? undefined : noEdit}
          onChange={(e) => onMove(e.target.value)}
        >
          {columns.map((c) => (
            <option key={c.key ?? 'none'} value={c.key ?? ''}>
              {c.label}
            </option>
          ))}
        </select>
        <button
          type="button"
          className="ev-iconbtn ev-iconbtn--xs"
          aria-label={`Preview ${name}`}
          title="Preview"
          onClick={() => onPreview(record, false)}
        >
          <Icon name="eye" size={12} />
        </button>
        <button
          type="button"
          className="ev-iconbtn ev-iconbtn--xs"
          aria-label={`Edit ${name}`}
          title={canEdit ? 'Edit' : noEdit}
          disabled={!canEdit}
          onClick={() => onPreview(record, true)}
        >
          <Icon name="pencil" size={12} />
        </button>
        <button
          type="button"
          className="ev-iconbtn ev-iconbtn--xs"
          aria-label={`Assign ${name}`}
          title={canEdit ? 'Assign' : noEdit}
          disabled={!canEdit}
          onClick={() => onAssign(record)}
        >
          <Icon name="user" size={12} />
        </button>
      </div>
    </article>
  );
}

/** The list design's card (`.lp-bcard`, as LpBoard draws it), keeping drag and keyboard moves. */
function DesignCard({
  record,
  lines,
  meta,
  avatar,
  stageName,
  moving,
  canEdit,
  columns,
  currentKey,
  onDragStart,
  onDragEnd,
  onMove,
  onPreview,
}: {
  record: ObjectRecord;
  lines: Array<[string, string]>;
  meta: string | undefined;
  avatar: boolean;
  /** Boards by stage: the column's stage, for the "In stage: Nd" pill (card.html). */
  stageName: string | null;
  moving: boolean;
  canEdit: boolean;
  columns: ObjectBoardColumn[];
  currentKey: string;
  onDragStart: (e: DragEvent<HTMLElement>) => void;
  onDragEnd: () => void;
  onMove: (to: string) => void;
  onPreview: (record: ObjectRecord, edit: boolean) => void;
}) {
  const name = record.displayName || 'Untitled';
  const owner = record.owner?.name ?? null;
  return (
    <article
      className={cn('lp-bcard', moving && 'is-dragging')}
      draggable={!moving && canEdit}
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      aria-label={name}
    >
      <div className="lp-bcard__top">
        {avatar ? <Avatar name={name} size="xs" /> : null}
        <Link className="lp-bcard__name" href={objectRecordPath(record.objectKey, record.id)}>
          {name}
        </Link>
        <button
          type="button"
          className="lp-icon-btn lp-icon-btn--sm"
          aria-label={`Preview ${name}`}
          onClick={() => onPreview(record, false)}
        >
          <LpIcon name="eye" />
        </button>
      </div>
      {lines.map(([label, value]) => (
        <div key={label} className="lp-bcard__line">
          <span>{label}:</span> {value}
        </div>
      ))}
      <div className="lp-bcard__foot">
        {owner ? (
          <span className="lp-owner">
            <Avatar name={owner} size="xs" />
            {owner}
          </span>
        ) : (
          <span className="lp-muted">No owner</span>
        )}
        {meta ? <span title="Create date">{meta}</span> : null}
      </div>
      {stageName ? <StagePill stageName={stageName} record={record} /> : null}
      {/* Keyboard users move cards with this menu instead of dragging. */}
      <select
        className="crm-visually-hidden"
        aria-label={`Move ${name} to`}
        value={currentKey}
        disabled={moving || !canEdit}
        onChange={(e) => onMove(e.target.value)}
      >
        {columns.map((c) => (
          <option key={c.key ?? 'none'} value={c.key ?? ''}>
            {c.label}
          </option>
        ))}
      </select>
    </article>
  );
}
