'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  createForecastSubmission,
  listForecastDeals,
  listForecastSubmissions,
  updateForecastType,
} from '../api.client';
import {
  fullMoney,
  shortMoney,
  submissionPeriods,
  type ForecastRange,
  type RangeKey,
} from '../periods';
import type {
  ForecastCategory,
  ForecastDeal,
  ForecastRollup,
  ForecastSchedule,
  ForecastSubmission,
  ForecastType,
} from '../types';
import { Caret, ExtSvg, FcLayer, Info, TeamSvg, UserSvg } from './parts';
import { emptySchedule, ScheduleFields, scheduleOk } from './ScheduleFields';

/** Where "Create goal", "Edit goals" and "View in goals" go (the CRM's goals / targets page). */
export const GOALS_HREF = '/reports/targets';

const initials = (n: string) =>
  n
    .split(' ')
    .map((p) => p.charAt(0))
    .join('')
    .slice(0, 2)
    .toUpperCase();

function TypeHead({ type }: { type: ForecastType }) {
  return (
    <>
      <h2 className="fc-dg__t">
        {type.name}
        {type.isDefault ? ' (default)' : ''}
      </h2>
      <p className="fc-measure">
        Measured by: <b>{type.dateLabel}</b> and <b>{type.amountLabel}</b>
      </p>
    </>
  );
}

/** "Deals and goals" (design forecast.js `renderDeals`): a row's deals and its goal progress. */
export function DealsGoalsDrawer({
  subject,
  type,
  range,
  rollup,
  stages,
  query,
  category,
  stageId,
  pipelineName,
  currency,
  onPreview,
  onClose,
}: {
  subject: { kind: 'team' | 'member'; id: string; name: string };
  type: ForecastType;
  range: ForecastRange;
  rollup: ForecastRollup;
  stages: Array<{ id: string; name: string }>;
  query: { typeId: string; pipelineIds: string[]; from: string; to: string };
  category: ForecastCategory | null;
  stageId: string | null;
  pipelineName: string;
  currency: string;
  onPreview: (dealId: string) => void;
  onClose: () => void;
}) {
  const toast = useToast();
  const [tab, setTab] = useState<'deals' | 'goals'>('deals');
  const [menu, setMenu] = useState(false);
  const [picked, setPicked] = useState<Record<string, boolean>>(() =>
    Object.fromEntries(stages.map((s) => [s.id, stageId === null || s.id === stageId])),
  );
  const [deals, setDeals] = useState<ForecastDeal[] | null>(null);

  useEffect(() => {
    let alive = true;
    listForecastDeals({
      ...query,
      ...(subject.kind === 'team' ? { teamId: subject.id } : { ownerId: subject.id }),
    })
      .then((d) => alive && setDeals(d))
      .catch((err) => {
        if (!alive) return;
        setDeals([]);
        toast(errorText(err), 'danger');
      });
    return () => {
      alive = false;
    };
    // Loaded once per open drawer.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const d = rollup;
  const pct = d.goal ? Math.min(100, Math.round((d.closedWon / d.goal) * 100)) : 0;
  const nSel = stages.filter((s) => picked[s.id]).length;
  const all = nSel === stages.length;
  const list = (deals ?? []).filter(
    (x) =>
      x.stageType === 'open' && picked[x.stageId] && (category === null || x.category === category),
  );
  const sum = list.reduce((a, x) => a + x.weighted, 0);

  return (
    <FcLayer onClose={onClose}>
      <div
        className="fc-ov fc-ov--r"
        onMouseDown={(e) => {
          if (e.target === e.currentTarget) onClose();
        }}
      >
        <div
          className="fc-drawer fc-drawer--dg"
          role="dialog"
          aria-modal="true"
          aria-label="Deals and goals"
          onMouseDown={(e) => {
            if (menu && !(e.target as HTMLElement).closest('.fc-stwrap')) setMenu(false);
          }}
        >
          <div className="fc-drawer__h">
            <span>Deals and goals</span>
            <button type="button" className="fc-x" aria-label="Close" onClick={onClose}>
              ×
            </button>
          </div>
          <div className="fc-drawer__b fc-drawer__b--dg">
            <div className="fc-dg__top">
              <TypeHead type={type} />
              <div className="fc-name">
                <span className="fc-av">{subject.kind === 'team' ? <TeamSvg /> : <UserSvg />}</span>
                <span>{subject.name}</span>
              </div>
              <p>
                <b>{range.sub || range.label}</b>{' '}
                {d.goal ? (
                  `Goal ${shortMoney(d.goal, currency)}`
                ) : (
                  <>
                    No goal set
                    <Info tip="Set a goal to track attainment." />
                  </>
                )}
              </p>
              <div className="fc-att__top">
                <span className="fc-track">
                  <span className="fc-fill" style={{ width: `${pct}%` }} />
                </span>
                <span>{d.goal ? `${pct}%` : '—'}</span>
              </div>
              <dl className="fc-dl">
                <dt>Closed</dt>
                <dd>{fullMoney(d.closedWon, currency)}</dd>
                <dt>Goal</dt>
                <dd>{d.goal ? fullMoney(d.goal, currency) : '—'}</dd>
                <dt>Forecasted</dt>
                <dd>{fullMoney(d.submission ?? 0, currency)}</dd>
                <dt>Gap to goal</dt>
                <dd>{d.goal ? fullMoney(Math.max(d.goal - d.closedWon, 0), currency) : '—'}</dd>
              </dl>
            </div>
            <div className="fc-tabs" role="tablist">
              {(['deals', 'goals'] as const).map((t) => (
                <button
                  key={t}
                  type="button"
                  role="tab"
                  className={cn(tab === t && 'is-on')}
                  aria-selected={tab === t}
                  onClick={() => {
                    setTab(t);
                    setMenu(false);
                  }}
                >
                  {t === 'deals' ? 'Deals' : 'Goals'}
                </button>
              ))}
            </div>
            {tab === 'deals' ? (
              <>
                <div className="fc-stwrap">
                  <span>Deal stage:</span>{' '}
                  <button
                    type="button"
                    className="fc-stbtn"
                    aria-expanded={menu}
                    onClick={() => setMenu((m) => !m)}
                  >
                    {nSel} stage{nSel === 1 ? '' : 's'} selected
                    <Caret />
                  </button>
                  {menu ? (
                    <div className="fc-menu fc-menu--st">
                      <label className="check">
                        <input
                          type="checkbox"
                          checked={all}
                          ref={(el) => {
                            if (el) el.indeterminate = !all && nSel > 0;
                          }}
                          onChange={(e) =>
                            setPicked(
                              Object.fromEntries(stages.map((s) => [s.id, e.target.checked])),
                            )
                          }
                        />
                        <span className="check__box" />
                        <b>All stages</b>
                      </label>
                      {stages.map((s) => (
                        <label key={s.id} className="check">
                          <input
                            type="checkbox"
                            checked={Boolean(picked[s.id])}
                            onChange={(e) => setPicked((p) => ({ ...p, [s.id]: e.target.checked }))}
                          />
                          <span className="check__box" />
                          {s.name}
                        </label>
                      ))}
                    </div>
                  ) : null}
                </div>
                <div className="fc-deals-list">
                  {deals === null ? (
                    <p className="fc-empty">Loading deals…</p>
                  ) : list.length ? (
                    list.map((x) => (
                      <div key={x.id} className="fc-deal">
                        <div className="eyebrow">{x.pipelineName}</div>
                        <button type="button" className="link" onClick={() => onPreview(x.id)}>
                          {x.name}
                          <ExtSvg />
                        </button>
                        <div className="fc-deal__m">
                          <span className="fc-chip" title={x.ownerName ?? ''}>
                            {initials(x.ownerName ?? '?')}
                          </span>
                          <span>{fullMoney(x.amount ?? 0, currency)}</span>
                          <span>{x.stageName}</span>
                        </div>
                        {x.nextStep ? (
                          <div className="fc-deal__n">
                            <b>Next Step :</b> {x.nextStep}
                          </div>
                        ) : null}
                      </div>
                    ))
                  ) : (
                    <p className="fc-empty">No deals for the selected stages.</p>
                  )}
                </div>
              </>
            ) : (
              <div className="fc-gl">
                <div className="fc-att__top">
                  <b>{pipelineName}</b>
                  <span>{d.goal ? `${pct}%` : '—'}</span>
                </div>
                <span className="fc-track">
                  <span className="fc-fill" style={{ width: `${pct}%` }} />
                </span>
                <div className="fc-att__bot">
                  <span>{fullMoney(d.closedWon, currency)}</span>
                  <span>
                    {d.goal
                      ? `of ${shortMoney(d.goal, currency)} goal`
                      : subject.kind === 'team'
                        ? 'No team goal set'
                        : 'No goal set'}
                  </span>
                </div>
              </div>
            )}
          </div>
          <div className="fc-drawer__f fc-drawer__f--c">
            {tab === 'deals' ? (
              <>
                <div className="fc-wt">
                  Weighted Amount <b>{fullMoney(sum, currency)}</b>
                </div>
                <Link className="link" href="/deals" target="_blank" rel="noopener">
                  View in deals
                  <ExtSvg />
                </Link>
              </>
            ) : (
              <Link className="link" href={GOALS_HREF} target="_blank" rel="noopener">
                View in goals
                <ExtSvg />
              </Link>
            )}
          </div>
        </div>
      </div>
    </FcLayer>
  );
}

/** "Forecast submission" (design forecast.js `renderSubmit`): Submit and History tabs. */
export function SubmissionDrawer({
  subject,
  type,
  pipelines,
  defaultPipelineId,
  ranges,
  rangeKey,
  prefill,
  teamTotal,
  currency,
  onClose,
  onSubmitted,
}: {
  subject: { kind: 'team' | 'member'; id: string; name: string };
  type: ForecastType;
  pipelines: Array<{ id: string; name: string }>;
  defaultPipelineId: string;
  ranges: ForecastRange[];
  rangeKey: RangeKey;
  prefill: number | null;
  /** "User submission total" of a team for the shown period, when known. */
  teamTotal: (period: ForecastRange) => number | null;
  currency: string;
  onClose: () => void;
  onSubmitted: () => void;
}) {
  const toast = useToast();
  const group = useMemo(() => submissionPeriods(ranges, rangeKey), [ranges, rangeKey]);
  const isT = subject.kind === 'team';
  const [tab, setTab] = useState<'submit' | 'history'>('submit');
  const [pipe, setPipe] = useState(defaultPipelineId);
  const [periodKey, setPeriodKey] = useState<RangeKey>(
    group.some((r) => r.key === rangeKey) ? rangeKey : (group[1]?.key ?? group[0]!.key),
  );
  const [amount, setAmount] = useState(prefill !== null ? String(prefill) : '');
  const [note, setNote] = useState('');
  const [acc, setAcc] = useState({ acc: true, subs: true });
  const [menu, setMenu] = useState(false);
  const [history, setHistory] = useState<ForecastSubmission[] | null>(null);
  const [busy, setBusy] = useState(false);
  const period = group.find((r) => r.key === periodKey) ?? group[0]!;

  useEffect(() => {
    let alive = true;
    setHistory(null);
    if (!pipe) return;
    listForecastSubmissions({
      typeId: type.id,
      pipelineId: pipe,
      periodStart: period.from,
      periodEnd: period.to,
      subjectType: isT ? 'team' : 'user',
      subjectId: subject.id,
    })
      .then((rows) => alive && setHistory(rows))
      .catch(() => alive && setHistory([]));
    return () => {
      alive = false;
    };
  }, [type.id, pipe, period.from, period.to, isT, subject.id]);

  const parsed = parseFloat(amount.replace(/[$,\s]/g, ''));
  const ok = amount.replace(/\s/g, '') !== '' && !Number.isNaN(parsed) && parsed >= 0;
  const total = isT ? teamTotal(period) : null;

  const submit = async () => {
    if (!ok || !pipe) return;
    setBusy(true);
    try {
      await createForecastSubmission({
        typeId: type.id,
        pipelineId: pipe,
        periodStart: period.from,
        periodEnd: period.to,
        subjectType: isT ? 'team' : 'user',
        subjectId: subject.id,
        amount: Math.round(parsed * 100) / 100,
        note: note.trim() || null,
      });
      toast('Forecast submitted', 'success');
      onSubmitted();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const accordion = (
    id: 'acc' | 'subs',
    title: string,
    badge: string,
    content: React.ReactNode,
  ) => (
    <section className="fc-acc">
      <button
        type="button"
        className="fc-acc__h"
        aria-expanded={acc[id]}
        onClick={() => setAcc((a) => ({ ...a, [id]: !a[id] }))}
      >
        <span className={cn('fc-acc__c', acc[id] && 'is-open')} />
        <b>{title}</b>
        {badge ? <span className="fc-badge">{badge}</span> : null}
      </button>
      {acc[id] ? <div className="fc-acc__b">{content}</div> : null}
    </section>
  );
  const subsAcc = accordion(
    'subs',
    `Submissions for ${period.sub}`,
    '',
    <>
      {history === null ? (
        <p>Loading…</p>
      ) : history.length ? (
        <ul className="fc-sbl">
          {history.map((h) => (
            <li key={h.id}>
              <b>{fullMoney(h.amount, currency)}</b>
              {h.note ? ` – ${h.note}` : ''}
            </li>
          ))}
        </ul>
      ) : (
        <p>No forecast submission history.</p>
      )}
      <button
        type="button"
        className="link"
        onClick={() => toast('Submission history page coming soon', 'info')}
      >
        View submissions over time
      </button>
    </>,
  );
  const head = (
    <div className="fc-sbtype">
      <b>
        {type.name}
        {type.isDefault ? ' (default)' : ''}
      </b>
      <span>
        Measured by: {type.dateLabel} and {type.amountLabel}
      </span>
    </div>
  );
  const pos = group.findIndex((r) => r.key === period.key);
  const pipeName = pipelines.find((p) => p.id === pipe)?.name ?? '';

  return (
    <FcLayer onClose={onClose}>
      <div
        className="fc-ov fc-ov--r"
        onMouseDown={(e) => {
          if (e.target === e.currentTarget) onClose();
        }}
      >
        <div
          className="fc-drawer fc-drawer--dg"
          role="dialog"
          aria-modal="true"
          aria-label="Forecast submission"
          onMouseDown={(e) => {
            if (menu && !(e.target as HTMLElement).closest('.fc-menu--sb, [data-fc-sbmenu]')) {
              setMenu(false);
            }
          }}
        >
          <div className="fc-drawer__h">
            <span>Forecast submission</span>
            <button type="button" className="fc-x" aria-label="Close" onClick={onClose}>
              ×
            </button>
          </div>
          <div className="fc-drawer__b fc-drawer__b--dg">
            <div className="fc-sbh">
              <span className="fc-av">{isT ? <TeamSvg /> : <UserSvg />}</span>
              <span>{subject.name}</span>
            </div>
            <div className="fc-tabs" role="tablist">
              <button
                type="button"
                role="tab"
                className={cn(tab === 'submit' && 'is-on')}
                aria-selected={tab === 'submit'}
                onClick={() => {
                  setTab('submit');
                  setMenu(false);
                }}
              >
                Submit
              </button>
              <button
                type="button"
                role="tab"
                className={cn(tab === 'history' && 'is-on')}
                aria-selected={tab === 'history'}
                onClick={() => {
                  setTab('history');
                  setMenu(false);
                }}
              >
                History
              </button>
            </div>
            {tab === 'submit' ? (
              <>
                <div className="fc-sbb">
                  {head}
                  <div className="field">
                    <label className="field__label" htmlFor="fcSbP">
                      Pipeline
                    </label>
                    <select
                      className="input"
                      id="fcSbP"
                      value={pipe}
                      onChange={(e) => setPipe(e.target.value)}
                    >
                      {pipelines.map((p) => (
                        <option key={p.id} value={p.id}>
                          {p.name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div className="field">
                    <label className="field__label" htmlFor="fcSbD">
                      Forecast period
                    </label>
                    <select
                      className="input"
                      id="fcSbD"
                      value={period.key}
                      onChange={(e) => setPeriodKey(e.target.value as RangeKey)}
                    >
                      {group.map((r) => (
                        <option key={r.key} value={r.key}>
                          {r.sub}
                        </option>
                      ))}
                    </select>
                  </div>
                  {isT ? (
                    <div className="fc-sbtot">
                      <b>User submission total</b>
                      <span>All forecast submissions from users on this team.</span>
                      <div>{total ? fullMoney(total, currency) : '—'}</div>
                    </div>
                  ) : null}
                  <div className="field">
                    <label className="field__label" htmlFor="fcSbA">
                      Forecast amount
                    </label>
                    <input
                      className="input"
                      id="fcSbA"
                      type="text"
                      inputMode="decimal"
                      value={amount}
                      onChange={(e) => setAmount(e.target.value)}
                    />
                  </div>
                  <div className="field">
                    <label className="field__label" htmlFor="fcSbN">
                      Note
                    </label>
                    <textarea
                      className="input"
                      id="fcSbN"
                      rows={3}
                      placeholder="What’s changed?"
                      maxLength={2000}
                      value={note}
                      onChange={(e) => setNote(e.target.value)}
                    />
                  </div>
                </div>
                {subsAcc}
              </>
            ) : (
              <>
                <div className="fc-sbb">
                  {head}
                  <div className="fc-sbhist">
                    <div className="fc-sbper">
                      <b>{period.sub}</b>
                      <div className="fc-stwrap fc-stwrap--sb">
                        <span>Pipeline:</span>{' '}
                        <span className="fc-pos">
                          <button
                            type="button"
                            className="fc-stbtn"
                            data-fc-sbmenu
                            aria-expanded={menu}
                            onClick={() => setMenu((m) => !m)}
                          >
                            {pipeName}
                            <Caret />
                          </button>
                          {menu ? (
                            <div className="fc-menu fc-menu--sb">
                              {pipelines.map((p) => (
                                <button
                                  key={p.id}
                                  type="button"
                                  role="menuitem"
                                  className={cn(p.id === pipe && 'is-on')}
                                  onClick={() => {
                                    setPipe(p.id);
                                    setMenu(false);
                                  }}
                                >
                                  {p.name}
                                </button>
                              ))}
                            </div>
                          ) : null}
                        </span>
                      </div>
                    </div>
                    <div className="fc-nav">
                      <button
                        type="button"
                        aria-label="Previous period"
                        disabled={pos <= 0}
                        onClick={() => setPeriodKey(group[pos - 1]!.key)}
                      >
                        ‹
                      </button>
                      <button
                        type="button"
                        aria-label="Next period"
                        disabled={pos >= group.length - 1}
                        onClick={() => setPeriodKey(group[pos + 1]!.key)}
                      >
                        ›
                      </button>
                    </div>
                  </div>
                </div>
                {accordion(
                  'acc',
                  'Forecast accuracy',
                  'N/A',
                  <p>
                    Forecast accuracy is calculated only for previous periods that have completed.
                  </p>,
                )}
                {subsAcc}
              </>
            )}
          </div>
          <div className="fc-drawer__f fc-drawer__f--sb">
            <button type="button" className="link" onClick={onClose}>
              Cancel
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={!ok || !pipe || busy}
              onClick={() => void submit()}
            >
              Submit forecast
            </button>
          </div>
        </div>
      </div>
    </FcLayer>
  );
}

/** Actions › Set submission schedule (design forecast.js `scheduleDrawer`). */
export function ScheduleDrawer({
  type,
  teams,
  timeZone,
  onClose,
  onSaved,
}: {
  type: ForecastType;
  teams: Array<{ id: string; name: string }>;
  timeZone: string;
  onClose: () => void;
  onSaved: (type: ForecastType) => void;
}) {
  const toast = useToast();
  const had = Boolean(type.schedule);
  const [sch, setSch] = useState(() => emptySchedule(type.schedule));
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);
  const save = async () => {
    let schedule: ForecastSchedule | null = null;
    if (sch.on) {
      if (!scheduleOk(sch)) {
        setErr('Complete all required schedule fields.');
        return;
      }
      schedule = {
        start: sch.start,
        time: sch.time,
        repeats: sch.rep as ForecastSchedule['repeats'],
        teamId: sch.teamId === 'all' ? null : sch.teamId,
        reminder: sch.rem as ForecastSchedule['reminder'],
      };
    }
    setBusy(true);
    try {
      const saved = await updateForecastType(type.id, { schedule });
      toast(schedule ? 'Submission schedule saved' : 'Submission schedule removed', 'success');
      onSaved(saved);
    } catch (e) {
      setErr(errorText(e));
    } finally {
      setBusy(false);
    }
  };
  return (
    <FcLayer onClose={onClose}>
      <div
        className="fc-ov fc-ov--r"
        onMouseDown={(e) => {
          if (e.target === e.currentTarget) onClose();
        }}
      >
        <div
          className="fc-drawer"
          role="dialog"
          aria-modal="true"
          aria-label="Set forecast schedule"
        >
          <div className="fc-drawer__h">
            <span>Set forecast schedule for {type.name}</span>
            <button type="button" className="fc-x" aria-label="Close" onClick={onClose}>
              ×
            </button>
          </div>
          <div className="fc-drawer__b">
            <ScheduleFields
              draft={sch}
              onChange={(d) => {
                setSch(d);
                setErr('');
              }}
              teams={teams}
              timeZone={timeZone}
              intro={`Set up a forecast submission schedule for ${type.name}.`}
            />
            <div className="fc-err" hidden={!err} role="alert">
              {err}
            </div>
          </div>
          <div className="fc-drawer__f fc-drawer__f--sb">
            <button type="button" className="link" onClick={onClose}>
              Cancel
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={!(sch.on || had) || busy}
              onClick={() => void save()}
            >
              Save
            </button>
          </div>
        </div>
      </div>
    </FcLayer>
  );
}

/** A small centred dialog (design forecast.js `openModal`). */
export function FcModal({
  title,
  ok,
  onOk,
  onClose,
  error,
  children,
}: {
  title: string;
  ok?: string;
  onOk?: () => void;
  onClose: () => void;
  error?: string;
  children: React.ReactNode;
}) {
  return (
    <FcLayer onClose={onClose}>
      <div
        className="fc-ov"
        onMouseDown={(e) => {
          if (e.target === e.currentTarget) onClose();
        }}
      >
        <div className="fc-modal" role="dialog" aria-modal="true" aria-label={title}>
          <div className="fc-modal__h">
            <span>{title}</span>
            <button type="button" className="fc-x" aria-label="Close" onClick={onClose}>
              ×
            </button>
          </div>
          <div className="fc-modal__b">
            {children}
            <div className="fc-err" hidden={!error}>
              {error}
            </div>
          </div>
          <div className="fc-modal__f">
            {ok ? (
              <button type="button" className="btn-crm btn-crm--primary" onClick={onOk}>
                {ok}
              </button>
            ) : null}
            <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
              {ok ? 'Cancel' : 'Close'}
            </button>
          </div>
        </div>
      </div>
    </FcLayer>
  );
}

/** Close Date › Custom date range (design forecast.js `customModal`). */
export function CustomRangeModal({
  initial,
  onApply,
  onClose,
}: {
  initial: { from: string; to: string } | null;
  onApply: (range: { from: string; to: string }) => void;
  onClose: () => void;
}) {
  const [from, setFrom] = useState(initial?.from ?? '');
  const [to, setTo] = useState(initial?.to ?? '');
  const [error, setError] = useState('');
  return (
    <FcModal
      title="Custom date range"
      ok="Apply"
      error={error}
      onClose={onClose}
      onOk={() => {
        if (!from || !to) return setError('Choose both dates.');
        if (to < from) return setError('The end date must be on or after the start date.');
        onApply({ from, to });
      }}
    >
      <div className="field">
        <label className="field__label" htmlFor="fcCf">
          From
        </label>
        <input
          className="input"
          id="fcCf"
          type="date"
          value={from}
          onChange={(e) => setFrom(e.target.value)}
        />
      </div>
      <div className="field">
        <label className="field__label" htmlFor="fcCt">
          To
        </label>
        <input
          className="input"
          id="fcCt"
          type="date"
          value={to}
          onChange={(e) => setTo(e.target.value)}
        />
      </div>
    </FcModal>
  );
}
