import { useState, useEffect, type FormEvent, type ReactNode } from 'react'
import { useNavigate, useParams, Link } from 'react-router-dom'
import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query'
import { ArrowLeft, Plus, Trash2, Save } from 'lucide-react'
import { api } from '@/lib/api'
import { Button } from '@/components/Button'
import { Field, TextInput, TextArea, Select, AsyncSelect, Checkbox, MoneyInput, NumberInput } from '@/components/Field'
import {
  useUnits, useCountries, useCurrencies, usePriceTypes,
} from '@/lib/useLookups'
import { useOrgSettings } from '@/lib/useOrgSettings'
import { BarcodeType, Packaging, type Product } from '@/lib/types'
import { ProductImageGallery } from '@/components/ProductImageGallery'
import { generateEan13InternalPrefix2, generateBarcode, generateArticle } from '@/lib/barcode'

interface PriceRow { id?: string; priceTypeId: string; amount: number; currencyId: string }
interface BarcodeRow { id?: string; code: string; type: BarcodeType; isPrimary: boolean }

interface Form {
  name: string
  article: string
  description: string
  unitOfMeasureId: string
  vat: number
  vatEnabled: boolean
  productGroupId: string
  countryOfOriginId: string
  isService: boolean
  packaging: Packaging
  isMarked: boolean
  minStock: string
  maxStock: string
  referencePrice: string
  purchaseCurrencyId: string
  imageUrl: string
  prices: PriceRow[]
  barcodes: BarcodeRow[]
}


const emptyForm: Form = {
  name: '', article: '', description: '',
  unitOfMeasureId: '', vat: 16, vatEnabled: true,
  productGroupId: '', countryOfOriginId: '',
  isService: false, packaging: Packaging.Piece, isMarked: false,
  minStock: '', maxStock: '',
  referencePrice: '', purchaseCurrencyId: '',
  imageUrl: '',
  prices: [],
  barcodes: [],
}

export function ProductEditPage() {
  const { id } = useParams<{ id: string }>()
  const isNew = !id || id === 'new'
  const navigate = useNavigate()
  const qc = useQueryClient()

  const units = useUnits()
  const countries = useCountries()
  const currencies = useCurrencies()
  const priceTypes = usePriceTypes()
  const org = useOrgSettings()

  const existing = useQuery({
    queryKey: ['/api/catalog/products', id],
    queryFn: async () => (await api.get<Product>(`/api/catalog/products/${id}`)).data,
    enabled: !isNew,
  })

  const [form, setForm] = useState<Form>(emptyForm)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!isNew && existing.data) {
      const p = existing.data
      setForm({
        name: p.name, article: p.article ?? '', description: p.description ?? '',
        unitOfMeasureId: p.unitOfMeasureId, vat: p.vat, vatEnabled: p.vatEnabled,
        productGroupId: p.productGroupId ?? '',
        countryOfOriginId: p.countryOfOriginId ?? '',
        isService: p.isService, packaging: p.packaging, isMarked: p.isMarked,

        minStock: p.minStock?.toString() ?? '',
        maxStock: p.maxStock?.toString() ?? '',
        referencePrice: p.referencePrice?.toString() ?? '',
        purchaseCurrencyId: p.purchaseCurrencyId ?? '',
        imageUrl: p.imageUrl ?? '',
        prices: p.prices.map((x) => ({ id: x.id, priceTypeId: x.priceTypeId, amount: x.amount, currencyId: x.currencyId })),
        barcodes: p.barcodes.map((x) => ({ id: x.id, code: x.code, type: x.type, isPrimary: x.isPrimary })),
      })
    }
  }, [isNew, existing.data])

  useEffect(() => {
    if (isNew && form.unitOfMeasureId === '' && units.data?.length) {
      // Дефолт — «штука» (ОКЕИ 796), иначе первая.
      const sht = units.data.find((u) => u.code === '796') ?? units.data[0]
      setForm((f) => ({ ...f, unitOfMeasureId: sht.id }))
    }

    if (isNew && form.purchaseCurrencyId === '' && currencies.data?.length) {
      const def = org.data?.defaultCurrencyId
        ? currencies.data?.find(c => c.id === org.data!.defaultCurrencyId)
        : currencies.data?.find(c => c.code === 'KZT')
      setForm((f) => ({ ...f, purchaseCurrencyId: def?.id ?? currencies.data?.[0]?.id ?? '' }))
    }
    // Дефолт Vat для нового товара — из Country.VatRate организации.
    if (isNew && org.data && form.vat === 16 && org.data.vatRate !== 16) {
      setForm((f) => ({ ...f, vat: org.data!.vatRate }))
    }
    // У нового товара сразу автогенерируется артикул — уникальность
    // окончательно подтверждает сервер. Поле остаётся редактируемым,
    // пользователь может заменить вручную.
    if (isNew && form.article === '') {
      const a = generateArticle()
      setForm((f) => ({ ...f, article: a }))
    }
    // У нового товара сразу один сгенерированный штрихкод, чтобы кнопку Сохранить
    // можно было нажать без лишних кликов.
    if (isNew && form.barcodes.length === 0) {
      setForm((f) => ({
        ...f,
        barcodes: [{ code: generateEan13InternalPrefix2(), type: BarcodeType.Ean13, isPrimary: true }],
      }))
    }
  }, [isNew, units.data, currencies.data, org.data, form.unitOfMeasureId, form.purchaseCurrencyId, form.vat, form.article, form.barcodes.length])

  const save = useMutation({
    mutationFn: async () => {
      const payload = {
        name: form.name,
        article: form.article || null,
        description: form.description || null,
        unitOfMeasureId: form.unitOfMeasureId,
        // Если UI скрывает Vat (showVatEnabledOnProduct=false), посылаем null,
        // бэкенд заполнит дефолтом из страны при создании / сохранит прежнее при update.
        vat: org.data?.showVatEnabledOnProduct ? form.vat : null,
        vatEnabled: form.vatEnabled,
        productGroupId: form.productGroupId || null,
        defaultSupplierId: null,
        countryOfOriginId: form.countryOfOriginId || null,
        isService: form.isService,
        packaging: form.packaging,
        isMarked: form.isMarked,

        minStock: form.minStock === '' ? null : Number(form.minStock),
        maxStock: form.maxStock === '' ? null : Number(form.maxStock),
        referencePrice: form.referencePrice === '' ? null : Number(form.referencePrice),
        purchaseCurrencyId: form.purchaseCurrencyId || null,
        imageUrl: form.imageUrl || null,
        prices: form.prices.map((p) => ({ priceTypeId: p.priceTypeId, amount: Number(p.amount), currencyId: p.currencyId })),
        barcodes: form.barcodes.map((b) => ({ code: b.code, type: b.type, isPrimary: b.isPrimary })),
      }
      if (isNew) {
        return (await api.post<Product>('/api/catalog/products', payload)).data
      }
      await api.put(`/api/catalog/products/${id}`, payload)
      return null
    },
    onSuccess: (created) => {
      qc.invalidateQueries({ queryKey: ['/api/catalog/products'] })
      navigate(created ? `/catalog/products/${created.id}` : '/catalog/products')
    },
    onError: (e: Error) => {
      const msg = (e as { response?: { data?: { error?: string } } }).response?.data?.error ?? e.message
      setError(msg)
    },
  })

  const remove = useMutation({
    mutationFn: async () => { await api.delete(`/api/catalog/products/${id}`) },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['/api/catalog/products'] })
      navigate('/catalog/products')
    },
  })

  const onSubmit = (e: FormEvent) => { e.preventDefault(); save.mutate() }

  const updatePrice = (i: number, patch: Partial<PriceRow>) =>
    setForm({ ...form, prices: form.prices.map((p, ix) => ix === i ? { ...p, ...patch } : p) })

  const addBarcode = () => setForm({ ...form, barcodes: [...form.barcodes, {
    code: generateEan13InternalPrefix2(), type: BarcodeType.Ean13, isPrimary: form.barcodes.length === 0,
  }] })
  const removeBarcode = (i: number) =>
    setForm({ ...form, barcodes: form.barcodes.filter((_, ix) => ix !== i) })
  const updateBarcode = (i: number, patch: Partial<BarcodeRow>) =>
    setForm({ ...form, barcodes: form.barcodes.map((b, ix) => ix === i ? { ...b, ...patch } : b) })

  // У каждого PriceType с IsRequired=true должна быть запись в form.prices
  // с Amount > 0. Сервер делает ту же проверку (400 иначе), но дублируем
  // на фронте чтобы кнопка Save не клатилась с непонятным «Request failed with status 400».
  const missingRequiredPrices = (priceTypes.data ?? [])
    .filter((pt) => pt.isRequired)
    .filter((pt) => {
      const row = form.prices.find((p) => p.priceTypeId === pt.id)
      return !row || row.amount <= 0
    })

  const canSave = form.name.trim().length > 0
    && form.article.trim().length > 0
    && !!form.unitOfMeasureId
    && !!form.productGroupId
    && form.barcodes.length > 0
    && missingRequiredPrices.length === 0

  return (
    <form onSubmit={onSubmit} className="flex flex-col h-full">
      {/* Sticky top bar */}
      <div className="flex items-center justify-between gap-4 px-6 py-3 border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900">
        <div className="flex items-center gap-3 min-w-0">
          <Link
            to="/catalog/products"
            className="text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 flex-shrink-0"
            title="Назад к списку"
          >
            <ArrowLeft className="w-5 h-5" />
          </Link>
          <div className="min-w-0">
            <h1 className="text-base font-semibold text-slate-900 dark:text-slate-100 truncate">
              {isNew ? 'Новый товар' : form.name || 'Товар'}
            </h1>
            <p className="text-xs text-slate-500">
              {isNew ? 'Создание новой позиции каталога' : 'Редактирование'}
            </p>
          </div>
        </div>
        <div className="flex gap-2 flex-shrink-0">
          {!isNew && (
            <Button
              type="button"
              variant="danger"
              size="sm"
              onClick={() => { if (confirm('Удалить товар?')) remove.mutate() }}
            >
              <Trash2 className="w-4 h-4" /> Удалить
            </Button>
          )}
          <Button type="submit" disabled={!canSave || save.isPending}>
            <Save className="w-4 h-4" /> {save.isPending ? 'Сохраняю…' : 'Сохранить'}
          </Button>
        </div>
      </div>

      {/* Scrollable body */}
      <div className="flex-1 overflow-auto">
        <div className="max-w-5xl mx-auto p-3 sm:p-6 space-y-4 sm:space-y-5">
          {error && (
            <div className="p-3 rounded-md bg-red-50 text-red-700 text-sm border border-red-200">{error}</div>
          )}

          <Section title="Основное">
            <Grid cols={3}>
              <Field label="Название *" className="col-span-2">
                <TextInput required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
              </Field>
              <Field label="Артикул *">
                <TextInput required value={form.article} onChange={(e) => setForm({ ...form, article: e.target.value })} />
              </Field>
            </Grid>

            <div className="mt-4 pt-4 border-t border-slate-100 dark:border-slate-800">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-xs font-semibold uppercase tracking-wide text-slate-500">Штрихкоды</h3>
                <Button type="button" variant="secondary" size="sm" onClick={addBarcode}>
                  <Plus className="w-3.5 h-3.5" /> Добавить
                </Button>
              </div>
              {form.barcodes.length === 0 ? (
                <div className="text-sm text-red-600 py-2">У товара должен быть хотя бы один штрихкод.</div>
              ) : (
                <div className="space-y-2">
                  {form.barcodes.map((b, i) => (
                    <div key={i} className="grid grid-cols-12 gap-2 items-center">
                      <div className="col-span-6">
                        <TextInput placeholder="Код" value={b.code} onChange={(e) => updateBarcode(i, { code: e.target.value })} />
                      </div>
                      <div className="col-span-3">
                        <Select value={b.type} onChange={(e) => {
                          const newType = Number(e.target.value) as BarcodeType
                          updateBarcode(i, { type: newType, code: generateBarcode(newType) })
                        }}>
                          <option value={BarcodeType.Ean13}>EAN-13</option>
                          <option value={BarcodeType.Ean8}>EAN-8</option>
                          <option value={BarcodeType.Code128}>CODE 128</option>
                          <option value={BarcodeType.Code39}>CODE 39</option>
                          <option value={BarcodeType.Upca}>UPC-A</option>
                          <option value={BarcodeType.Upce}>UPC-E</option>
                          <option value={BarcodeType.Other}>Прочий</option>
                        </Select>
                      </div>
                      <div className="col-span-2">
                        <Checkbox
                          label="Основной"
                          checked={b.isPrimary}
                          onChange={(v) => setForm({ ...form, barcodes: form.barcodes.map((x, ix) => ({ ...x, isPrimary: ix === i ? v : false })) })}
                        />
                      </div>
                      {form.barcodes.length > 1 ? (
                        <button
                          type="button"
                          onClick={() => removeBarcode(i)}
                          className="col-span-1 text-slate-400 hover:text-red-600 flex justify-center"
                          title="Удалить строку"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      ) : (
                        <div className="col-span-1" />
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>

            {org.data?.showDescriptionOnProduct && (
              <div className="mt-4 pt-4 border-t border-slate-100 dark:border-slate-800">
                <Field label="Описание">
                  <TextArea rows={2} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
                </Field>
              </div>
            )}
          </Section>

          <Section
            title="Цены"
            action={
              <div className="flex items-center gap-2">
                {!isNew && id && (
                  <Button type="button" variant="secondary" size="sm" onClick={async () => {
                    try {
                      const res = await api.post<{ retail: number }>(`/api/catalog/products/${id}/recalc-retail`)
                      const def = priceTypes.data?.find((pt) => pt.isSystem) ?? priceTypes.data?.find((pt) => pt.isRetail) ?? priceTypes.data?.[0]
                      if (def) {
                        setForm((f) => {
                          const has = f.prices.some(p => p.priceTypeId === def.id)
                          return {
                            ...f,
                            prices: has
                              ? f.prices.map(p => p.priceTypeId === def.id ? { ...p, amount: res.data.retail } : p)
                              : [...f.prices, { priceTypeId: def.id, amount: res.data.retail, currencyId: currencies.data?.[0]?.id ?? '' }],
                          }
                        })
                      }
                      await qc.invalidateQueries({ queryKey: ['/api/catalog/products', id] })
                    } catch (e) {
                      const msg = (e as { response?: { data?: { error?: string } } }).response?.data?.error ?? 'Ошибка пересчёта'
                      setError(msg)
                    }
                  }}>
                    Привести к себестоимости
                  </Button>
                )}
              </div>
            }
          >
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-x-6 gap-y-5">
              <div>
                <h3 className="text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3">Закупка</h3>
                <div className="space-y-3">
                  {org.data?.showReferencePriceOnProduct && (
                    <Field label="Эталонная цена">
                      <MoneyInput
                        value={form.referencePrice === '' ? null : Number(form.referencePrice)}
                        onChange={(n) => setForm({ ...form, referencePrice: n == null ? '' : String(n) })}
                        currencyCode={currencies.data?.find((c) => c.id === form.purchaseCurrencyId)?.code ?? org.data?.defaultCurrencyCode ?? undefined}
                        currencySymbol={currencies.data?.find((c) => c.id === form.purchaseCurrencyId)?.symbol ?? org.data?.defaultCurrencySymbol ?? undefined}
                      />
                      <p className="text-xs text-slate-400 mt-1">не обязательное поле</p>
                    </Field>
                  )}
                  <Field label="Себестоимость">
                    <MoneyInput
                      value={existing.data?.cost ?? 0}
                      onChange={() => {}}
                      disabled
                      currencyCode={org.data?.defaultCurrencyCode ?? undefined}
                      currencySymbol={org.data?.defaultCurrencySymbol ?? undefined}
                    />
                    <p className="text-xs text-slate-400 mt-1">расчётная (скользящее среднее)</p>
                  </Field>
                  {org.data?.multiCurrencyEnabled && (
                    <Field label="Валюта закупки">
                      <Select value={form.purchaseCurrencyId} onChange={(e) => setForm({ ...form, purchaseCurrencyId: e.target.value })}>
                        <option value="">—</option>
                        {currencies.data?.map((c) => <option key={c.id} value={c.id}>{c.code}</option>)}
                      </Select>
                    </Field>
                  )}
                </div>
              </div>

              <div className="lg:border-l lg:border-slate-100 lg:dark:border-slate-800 lg:pl-6">
                <h3 className="text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3">Цены продажи</h3>
                {/* Список цен рендерится по справочнику PriceType: одно поле на каждый
                  * тип, без выпадашки выбора. Значение хранится в form.prices,
                  * key = priceTypeId. Для отсутствующих записей при наборе создаётся
                  * новая, при стирании — null Amount (UI пустое). Обязательные (IsRequired)
                  * помечаются звёздочкой. */}
                <div className="space-y-3">
                  {priceTypes.data?.slice().sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name)).map((pt) => {
                    const idx = form.prices.findIndex(p => p.priceTypeId === pt.id)
                    const row = idx >= 0 ? form.prices[idx] : null
                    const required = pt.isRequired
                    return (
                      <Field key={pt.id} label={`${pt.name}${required ? ' *' : ''}`}>
                        <MoneyInput
                          value={row?.amount ?? null}
                          onChange={(n) => {
                            if (n == null) {
                              setForm({ ...form, prices: form.prices.filter(x => x.priceTypeId !== pt.id) })
                              return
                            }
                            if (idx >= 0) {
                              updatePrice(idx, { amount: n })
                            } else {
                              const cur = currencies.data?.find(c => c.code === 'KZT')?.id ?? currencies.data?.[0]?.id ?? ''
                              setForm({ ...form, prices: [...form.prices, { priceTypeId: pt.id, amount: n, currencyId: cur }] })
                            }
                          }}
                          currencyCode={currencies.data?.find((c) => c.id === row?.currencyId)?.code ?? org.data?.defaultCurrencyCode ?? undefined}
                          currencySymbol={currencies.data?.find((c) => c.id === row?.currencyId)?.symbol ?? org.data?.defaultCurrencySymbol ?? undefined}
                        />
                      </Field>
                    )
                  })}
                {priceTypes.data?.length === 0 && (
                  <div className="text-sm text-slate-400 py-2">Нет ни одного типа цен. Создай в «Настройки → Типы цен».</div>
                )}
                </div>
              </div>
            </div>
            {missingRequiredPrices.length > 0 && (
              <div className="text-sm text-red-600 mt-3">
                Заполни обязательные цены: {missingRequiredPrices.map((pt) => `«${pt.name}»`).join(', ')} (значение должно быть больше 0).
              </div>
            )}
          </Section>

          <Section title="Классификация">
            <Grid cols={3}>
              <Field label="Группа *">
                <AsyncSelect
                  url="/api/catalog/product-groups"
                  value={form.productGroupId}
                  onChange={(v) => setForm({ ...form, productGroupId: v })}
                  placeholder="Выберите группу…"
                  getLabel={(item) => String(item['path'] ?? item['name'] ?? '')}
                />
              </Field>
              <Field label="Единица измерения *">
                <Select required value={form.unitOfMeasureId} onChange={(e) => setForm({ ...form, unitOfMeasureId: e.target.value })}>
                  {units.data?.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
                </Select>
              </Field>
              <Field label="Фасовка">
                <Select value={form.packaging} onChange={(e) => setForm({ ...form, packaging: Number(e.target.value) as Packaging })}>
                  <option value={Packaging.Piece}>Штучный</option>
                  <option value={Packaging.Weight}>Весовой</option>
                  <option value={Packaging.Liquid}>Разливной</option>
                </Select>
              </Field>
            </Grid>
            {org.data?.showCountryOfOriginOnProduct && (
              <Grid cols={2}>
                <Field label="Страна происхождения">
                  <Select value={form.countryOfOriginId} onChange={(e) => setForm({ ...form, countryOfOriginId: e.target.value })}>
                    <option value="">—</option>
                    {countries.data?.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
                  </Select>
                </Field>
              </Grid>
            )}
            {org.data?.showVatEnabledOnProduct && form.vatEnabled && (
              <Grid cols={3}>
                <Field label="Ставка НДС, %">
                  <NumberInput
                    value={form.vat}
                    onChange={(n) => setForm({ ...form, vat: n ?? 0 })}
                  />
                </Field>
              </Grid>
            )}
            <div className="pt-3 mt-3 border-t border-slate-100 dark:border-slate-800 flex flex-wrap gap-x-6 gap-y-2">
              {org.data?.showVatEnabledOnProduct && (
                <Checkbox label="В том числе НДС" checked={form.vatEnabled} onChange={(v) => setForm({ ...form, vatEnabled: v })} />
              )}
              {org.data?.showServiceOnProduct && (
                <Checkbox label="Услуга" checked={form.isService} onChange={(v) => setForm({ ...form, isService: v })} />
              )}
              {org.data?.showMarkedOnProduct && (
                <Checkbox label="Маркируемый (Честный знак / Datamatrix)" checked={form.isMarked} onChange={(v) => setForm({ ...form, isMarked: v })} />
              )}
            </div>
          </Section>

          {org.data?.showMinMaxStock && (
            <AdvancedSection>
              <Grid cols={4}>
                <Field label="Минимальный остаток (для уведомления)">
                  <NumberInput
                    value={form.minStock === '' ? null : Number(form.minStock)}
                    onChange={(n) => setForm({ ...form, minStock: n == null ? '' : String(n) })}
                    placeholder="—"
                  />
                </Field>
                <Field label="Максимальный остаток (для автозаказа)">
                  <NumberInput
                    value={form.maxStock === '' ? null : Number(form.maxStock)}
                    onChange={(n) => setForm({ ...form, maxStock: n == null ? '' : String(n) })}
                    placeholder="—"
                  />
                </Field>
              </Grid>
            </AdvancedSection>
          )}

          {!isNew && id && (
            <Section title="Изображения">
              <ProductImageGallery productId={id} />
            </Section>
          )}
        </div>
      </div>
    </form>
  )
}

function Section({ title, children, action }: { title: string; children: ReactNode; action?: ReactNode }) {
  return (
    <section className="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 overflow-hidden">
      <header className="flex flex-wrap items-center justify-between gap-2 px-4 sm:px-5 py-3 border-b border-slate-100 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-800/30">
        <h2 className="text-sm font-semibold text-slate-900 dark:text-slate-100">{title}</h2>
        {action}
      </header>
      <div className="p-4 sm:p-5">{children}</div>
    </section>
  )
}

function Grid({ cols, children }: { cols: 2 | 3 | 4; children: ReactNode }) {
  const cls = cols === 2 ? 'grid-cols-1 sm:grid-cols-2' : cols === 3 ? 'grid-cols-1 sm:grid-cols-2 md:grid-cols-3' : 'grid-cols-1 sm:grid-cols-2 md:grid-cols-4'
  return <div className={`grid ${cls} gap-x-4 gap-y-3`}>{children}</div>
}

function AdvancedSection({ children }: { children: ReactNode }) {
  const [open, setOpen] = useState(false)
  return (
    <section className="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 overflow-hidden">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="w-full flex items-center justify-between px-5 py-3 border-b border-slate-100 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-800/30 text-left hover:bg-slate-100/60 dark:hover:bg-slate-800/50"
      >
        <h2 className="text-sm font-semibold text-slate-900 dark:text-slate-100">Расширенные параметры</h2>
        <span className="text-xs text-slate-500">{open ? 'свернуть' : 'развернуть'}</span>
      </button>
      {open && <div className="p-5">{children}</div>}
    </section>
  )
}
