import { useEffect, useMemo, useState } from 'react'
import { ChevronDown, ChevronUp, Copy, Loader2, Pencil, Play, RefreshCcw, Trash2 } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { Button, Card, Loader } from '../components/common'
import { Header } from '../components/layout/Header'
import { endpoints, getErrorMessage } from '../api/client'
import { getDateLocale, t, tf } from '../lib/i18n'
import type { ConversationMessage, SavedContentPlan } from '../types'

interface SessionPreviewState {
  technical: ConversationMessage[]
  content: ConversationMessage[]
}

interface ChatSessionResponse {
  messages?: ConversationMessage[]
}

function buildPreviewMessages(messages: ConversationMessage[]): ConversationMessage[] {
  if (messages.length <= 4) {
    return messages
  }

  const firstAssistantIndex = messages.findIndex((message) => message.role === 'assistant')
  const firstAssistant = firstAssistantIndex >= 0 ? messages[firstAssistantIndex] : null
  const tail = messages.slice(-4)

  if (!firstAssistant) {
    return tail
  }

  const preview = [firstAssistant, ...tail]
  return preview.filter((message, index) => (
    preview.findIndex((item) => item.role === message.role && item.content === message.content) === index
  ))
}

function PlanToggle({
  checked,
  onToggle,
}: {
  checked: boolean
  onToggle: () => void
}) {
  return (
    <button
      type="button"
      onClick={onToggle}
      className={`relative inline-flex h-6 w-11 rounded-full transition-colors ${
        checked ? 'bg-bc-primary' : 'bg-bc-gray-300'
      }`}
    >
      <span
        className="absolute top-1 h-4 w-4 rounded-full bg-white shadow transition-all duration-200"
        style={{ insetInlineStart: checked ? '1.5rem' : '0.25rem' }}
      />
    </button>
  )
}

function formatDate(value: string | null | undefined): string {
  if (!value) return '—'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  return new Intl.DateTimeFormat(getDateLocale(), {
    dateStyle: 'medium',
    timeStyle: 'short',
  }).format(date)
}

function formatRecurringSummary(plan: SavedContentPlan): string {
  const schedule = plan.schedule_config
  if (!schedule) {
    if (plan.repeat_frequency === 'daily') return t('Daily')
    if (plan.repeat_frequency === 'monthly') return t('Monthly')
    if (plan.repeat_frequency === 'weekly') return t('Weekly')
    return '—'
  }

  const weekdayLabels = [t('Sun'), t('Mon'), t('Tue'), t('Wed'), t('Thu'), t('Fri'), t('Sat')]
  const unitLabel = schedule.unit === 'month'
    ? t(schedule.interval === 1 ? 'month' : 'months')
    : schedule.unit === 'day'
      ? t(schedule.interval === 1 ? 'day' : 'days')
      : t(schedule.interval === 1 ? 'week' : 'weeks')
  const weekdayLabel = schedule.unit === 'week' && schedule.weekdays.length > 0
    ? ` • ${schedule.weekdays.map((weekday) => weekdayLabels[weekday] || weekday).join(', ')}`
    : ''

  return `${t('Every')} ${schedule.interval > 1 ? `${schedule.interval} ` : ''}${unitLabel}${weekdayLabel} • ${String(schedule.hour).padStart(2, '0')}:00`
}

function formatRemainingBudget(plan: SavedContentPlan): string {
  if (!plan.schedule_counters) {
    return '—'
  }

  const parts = [
    plan.schedule_counters.remaining_runs !== null ? `${plan.schedule_counters.remaining_runs} ${t('Runs Left')}` : '',
    plan.schedule_counters.remaining_posts !== null ? `${plan.schedule_counters.remaining_posts} ${t('Posts Left')}` : '',
  ].filter(Boolean)

  return parts.length > 0 ? parts.join(' • ') : t('Unlimited')
}

function getTopicTreeArticleCount(plan: SavedContentPlan): number {
  const pillars = plan.content_plan?.topic_tree?.pillars || []
  const articleCount = pillars.reduce((total, pillar) => (
    total + (pillar.clusters || []).reduce((clusterTotal, cluster) => clusterTotal + (cluster.articles || []).length, 0)
  ), 0)
  if (articleCount > 0) return articleCount
  const fromCounts = pillars.reduce((total, pillar) => (
    total + (pillar.article_count || (pillar.clusters || []).reduce((ct, c) => ct + (c.article_count || 0), 0))
  ), 0)
  if (fromCounts > 0) return fromCounts
  return plan.content_plan?.topic_tree?.total_articles || 0
}

const NEW_FLOW_DRAFT_KEY = 'bc:content-new-flow-draft'
const NEW_FLOW_MAX_AGE = 2 * 60 * 60 * 1000

function hasUnsavedNewFlowDraft(): boolean {
  try {
    const raw = sessionStorage.getItem(NEW_FLOW_DRAFT_KEY)
    if (!raw) return false
    const draft = JSON.parse(raw) as { timestamp?: number; config?: { postType?: string } }
    if (!draft.config?.postType) return false
    if (typeof draft.timestamp === 'number' && Date.now() - draft.timestamp > NEW_FLOW_MAX_AGE) return false
    return true
  } catch {
    return false
  }
}

export default function ContentPlansPage() {
  const navigate = useNavigate()
  const [plans, setPlans] = useState<SavedContentPlan[]>([])
  const [loading, setLoading] = useState(true)
  const [expandedId, setExpandedId] = useState<number | null>(null)
  const [busyAction, setBusyAction] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [sessionPreviews, setSessionPreviews] = useState<Record<number, SessionPreviewState>>({})
  const [planTermNames, setPlanTermNames] = useState<Record<number, string[]>>({})
  const [hasUnsavedDraft] = useState(() => hasUnsavedNewFlowDraft())
  const [runningPlanId, setRunningPlanId] = useState<number | null>(null)
  const [runError, setRunError] = useState<string | null>(null)

  const handleRunPlan = async (plan: SavedContentPlan) => {
    if (!plan.post_type || !plan.reporter_id) {
      navigate(`/generate?planId=${plan.id}&intent=review&step=settings`)
      return
    }

    setRunningPlanId(plan.id)
    setRunError(null)

    try {
      await endpoints.sprintGenerate({
        post_type: plan.post_type,
        taxonomy: plan.taxonomy_scope || undefined,
        term: plan.term_scope || undefined,
        reporter_id: plan.reporter_id,
        topic: plan.topic,
        keywords: plan.keywords,
        count: plan.post_count,
        length: plan.post_length,
        content_plan: plan.content_plan || undefined,
        content_answers: plan.content_answers || undefined,
        technical_summary: plan.technical_rules?.summary || undefined,
        technical_answers: plan.technical_rules?.rules || undefined,
        plan_id: plan.id,
      })

      try {
        await endpoints.markContentPlanRun(plan.id)
      } catch {
        // Non-fatal: sprint is running, mark failed
      }

      navigate('/jobs')
    } catch (err: unknown) {
      const message = getErrorMessage(err, t('Failed to start the plan'))
      setRunError(message)
      setRunningPlanId(null)
    }
  }

  const loadPlans = async () => {
    setLoading(true)
    setError(null)

    try {
      const res = await endpoints.getContentPlans()
      const data = res.data as { items?: SavedContentPlan[] }
      setPlans(Array.isArray(data?.items) ? data.items : [])
    } catch (err) {
      setError(getErrorMessage(err, t('Unknown error')))
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    void loadPlans()
  }, [])

  useEffect(() => {
    if (!expandedId || (sessionPreviews[expandedId] && planTermNames[expandedId] !== undefined)) {
      return
    }

    const plan = plans.find((item) => item.id === expandedId)
    if (!plan) {
      return
    }

    const normalizedTermScope = plan.term_scope && plan.term_scope !== '-' ? plan.term_scope : null

    void (async () => {
      try {
        const [technicalRes, contentRes] = await Promise.all([
          plan.technical_session_id
            ? endpoints.getChatSession(plan.technical_session_id).catch(() => null)
            : Promise.resolve(null),
          plan.content_session_id
            ? endpoints.getChatSession(plan.content_session_id).catch(() => null)
            : Promise.resolve(null),
        ])

        const nextTermNames = plan.taxonomy_scope && normalizedTermScope
          ? await endpoints
            .getTaxonomyTerms(plan.post_type, plan.taxonomy_scope)
            .then((res) => {
              const selectedSlugs = normalizedTermScope.split(',').filter(Boolean)
              return ((res.data as Array<{ slug: string; name: string }>) || [])
                .filter((term) => selectedSlugs.includes(term.slug))
                .map((term) => term.name)
            })
            .catch(() => normalizedTermScope.split(',').filter(Boolean))
          : []

        setSessionPreviews((current) => ({
          ...current,
          [plan.id]: {
            technical: buildPreviewMessages(((technicalRes?.data as ChatSessionResponse | undefined)?.messages || [])),
            content: buildPreviewMessages(((contentRes?.data as ChatSessionResponse | undefined)?.messages || [])),
          },
        }))
        setPlanTermNames((current) => ({
          ...current,
          [plan.id]: nextTermNames,
        }))
      } catch {
        setSessionPreviews((current) => ({
          ...current,
          [plan.id]: {
            technical: [],
            content: [],
          },
        }))
        setPlanTermNames((current) => ({
          ...current,
          [plan.id]: normalizedTermScope ? normalizedTermScope.split(',').filter(Boolean) : [],
        }))
      }
    })()
  }, [expandedId, planTermNames, plans, sessionPreviews])

  const groupedPlans = useMemo(() => {
    return plans.map((plan) => ({
      ...plan,
      keywordSummary: plan.keywords.length > 0 ? plan.keywords.slice(0, 4) : [],
    }))
  }, [plans])

  const handleToggleActive = async (plan: SavedContentPlan) => {
    setBusyAction(`toggle-${plan.id}`)
    try {
      const res = await endpoints.toggleContentPlanActive(plan.id, !plan.is_active)
      const updated = res.data as SavedContentPlan
      setPlans((current) => current.map((item) => (item.id === updated.id ? updated : item)))
    } catch (err) {
      setError(getErrorMessage(err, t('Unknown error')))
    } finally {
      setBusyAction(null)
    }
  }

  const handleDuplicate = async (planId: number) => {
    setBusyAction(`duplicate-${planId}`)
    try {
      await endpoints.duplicateContentPlan(planId)
      await loadPlans()
    } catch (err) {
      setError(getErrorMessage(err, t('Unknown error')))
    } finally {
      setBusyAction(null)
    }
  }

  const handleDelete = async (planId: number) => {
    if (!window.confirm(t('Delete this content plan?'))) {
      return
    }

    setBusyAction(`delete-${planId}`)
    try {
      await endpoints.deleteContentPlan(planId)
      setPlans((current) => current.filter((item) => item.id !== planId))
      if (expandedId === planId) {
        setExpandedId(null)
      }
    } catch (err) {
      setError(getErrorMessage(err, t('Unknown error')))
    } finally {
      setBusyAction(null)
    }
  }

  return (
    <div className="min-h-screen">
      <Header
        title={t('Content Plans')}
        subtitle={t('Manage reusable content writing plans for your AI team')}
        helpContent={[
          t('Content plans save your generation settings for repeated use.'),
          t('One-time plans run once when you click Play. Recurring plans run automatically on schedule.'),
          t('Each plan includes: content type, reporter, topic, keywords, and schedule.'),
          t('Click Play to run a plan — it submits research and generation to the Jobs page.'),
        ]}
      />

      <div className="p-6">
        <div className="mx-auto max-w-6xl">
          <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
            <div>
              <h2 className="text-2xl font-bold text-bc-gray-800">{t('Content Plans')}</h2>
              <p className="mt-1 text-sm text-bc-gray-500">
                {t('Create, run, review, duplicate, and monitor all of your reusable plans in one place.')}
              </p>
            </div>
            <div className="flex gap-2">
              <Button variant="ghost" onClick={() => void loadPlans()} icon={<RefreshCcw className="w-4 h-4" />}>
                {t('Refresh')}
              </Button>
              <Button onClick={() => {
                sessionStorage.removeItem(NEW_FLOW_DRAFT_KEY)
                navigate('/generate?intent=new&step=select')
              }}>
                {t('Create New Plan')}
              </Button>
              {hasUnsavedDraft && (
                <Button variant="secondary" onClick={() => navigate('/generate?intent=new&step=select')}>
                  {t('Continue unsaved work')}
                </Button>
              )}
            </div>
          </div>

          {error ? (
            <div className="mb-4 rounded-bc border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
              {error}
            </div>
          ) : null}

          {runError ? (
            <div className="mb-4 flex items-center gap-2 rounded-bc border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
              <span className="flex-1">{runError}</span>
              <button type="button" onClick={() => setRunError(null)} className="text-bc-gray-400 hover:text-bc-gray-600">✕</button>
            </div>
          ) : null}

          {loading ? (
            <div className="flex items-center justify-center py-20">
              <Loader />
            </div>
          ) : groupedPlans.length === 0 ? (
            <Card className="py-16 text-center">
              <h3 className="text-xl font-semibold text-bc-gray-800">{t('No content plans yet')}</h3>
              <p className="mt-2 text-bc-gray-500">
                {t('Start a new content generation and save its configuration to build your plan library.')}
              </p>
              <div className="mt-6 flex flex-wrap justify-center gap-2">
                <Button onClick={() => {
                  sessionStorage.removeItem(NEW_FLOW_DRAFT_KEY)
                  navigate('/generate?intent=new&step=select')
                }}>
                  {t('Create New Plan')}
                </Button>
                {hasUnsavedDraft && (
                  <Button variant="secondary" onClick={() => navigate('/generate?intent=new&step=select')}>
                    {t('Continue unsaved work')}
                  </Button>
                )}
              </div>
            </Card>
          ) : (
            <div className="space-y-4">
              {groupedPlans.map((plan) => {
                const isExpanded = expandedId === plan.id
                const preview = sessionPreviews[plan.id]
                const selectedCategories = planTermNames[plan.id] || []

                return (
                  <Card key={plan.id} className="overflow-hidden p-0">
                    <div className="bg-white px-5 py-4">
                      <div className="flex flex-wrap items-start justify-between gap-4">
                        <div className="min-w-0 flex-1">
                          <div className="flex flex-wrap items-center gap-2">
                            <h3 className="truncate text-lg font-semibold text-bc-gray-800">
                              {plan.name || t('Untitled Plan')}
                            </h3>
                            <span className="rounded-full bg-bc-gray-100 px-2.5 py-1 text-xs text-bc-gray-600">
                              {plan.reporter_name || t('No reporter')}
                            </span>
                            <span className="rounded-full bg-bc-primary-light px-2.5 py-1 text-xs text-bc-primary">
                              {plan.generation_type === 'repeating' ? t('Repeating plan') : t('One-time plan')}
                            </span>
                            {plan.content_plan?.research_enabled ? (
                              <span className="rounded-full bg-emerald-50 px-2.5 py-1 text-xs text-emerald-700">
                                {t('Research enabled')}
                              </span>
                            ) : null}
                            {getTopicTreeArticleCount(plan) > 0 ? (
                              <span className="rounded-full bg-violet-50 px-2.5 py-1 text-xs text-violet-700">
                                {tf('%d topic angles', getTopicTreeArticleCount(plan))}
                              </span>
                            ) : null}
                          </div>
                          <div className="mt-2 flex flex-wrap items-center gap-2 text-sm text-bc-gray-500">
                            <span>{plan.post_type}</span>
                            <span>•</span>
                            <span>{tf('%d posts planned', plan.post_count)}</span>
                            <span>•</span>
                            <span>{tf('Last run: %s', formatDate(plan.last_run_at))}</span>
                            {plan.generation_type === 'repeating' ? (
                              <>
                                <span>•</span>
                                <span>{tf('Next run: %s', formatDate(plan.next_run_at))}</span>
                              </>
                            ) : null}
                          </div>
                          {plan.keywordSummary.length > 0 ? (
                            <div className="mt-3 flex flex-wrap gap-2">
                              {plan.keywordSummary.map((keyword) => (
                                <span
                                  key={keyword}
                                  className="rounded-full bg-bc-gray-100 px-2.5 py-1 text-xs text-bc-gray-600"
                                >
                                  {keyword}
                                </span>
                              ))}
                            </div>
                          ) : null}
                        </div>

                        <div className="flex items-center gap-2">
                          {plan.generation_type === 'repeating' ? (
                            <label
                              className="flex items-center gap-3"
                              onClick={(event) => event.stopPropagation()}
                            >
                              <span className="text-sm text-bc-gray-600">{t('Plan active')}</span>
                              <PlanToggle checked={plan.is_active} onToggle={() => void handleToggleActive(plan)} />
                            </label>
                          ) : null}
                          {plan.post_type && plan.reporter_id ? (
                            <button
                              type="button"
                              title={t('Run this plan')}
                              disabled={runningPlanId === plan.id}
                              className="rounded-bc p-2 text-bc-gray-500 transition-colors hover:bg-bc-gray-100 hover:text-bc-primary disabled:opacity-50"
                              onClick={() => void handleRunPlan(plan)}
                            >
                              {runningPlanId === plan.id ? (
                                <Loader2 className="h-4 w-4 animate-spin" />
                              ) : (
                                <Play className="h-4 w-4" />
                              )}
                            </button>
                          ) : (
                            <button
                              type="button"
                              title={t('Complete setup')}
                              className="rounded-bc p-2 text-bc-gray-500 transition-colors hover:bg-bc-gray-100 hover:text-bc-primary"
                              onClick={() => navigate(`/generate?planId=${plan.id}&intent=review&step=settings`)}
                            >
                              <Pencil className="h-4 w-4" />
                            </button>
                          )}
                          <button
                            type="button"
                            title={t('Review this plan')}
                            className="rounded-bc p-2 text-bc-gray-500 transition-colors hover:bg-bc-gray-100 hover:text-bc-primary"
                            onClick={() => navigate(`/generate?planId=${plan.id}&intent=review&step=select`)}
                          >
                            <Pencil className="h-4 w-4" />
                          </button>
                          <button
                            type="button"
                            title={t('Duplicate')}
                            className="rounded-bc p-2 text-bc-gray-500 transition-colors hover:bg-bc-gray-100 hover:text-bc-primary"
                            onClick={() => void handleDuplicate(plan.id)}
                            disabled={busyAction === `duplicate-${plan.id}`}
                          >
                            <Copy className="h-4 w-4" />
                          </button>
                          <button
                            type="button"
                            title={t('Delete')}
                            className="rounded-bc p-2 text-bc-gray-500 transition-colors hover:bg-red-50 hover:text-bc-error"
                            onClick={() => void handleDelete(plan.id)}
                            disabled={busyAction === `delete-${plan.id}`}
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                          <button
                            type="button"
                            onClick={() => setExpandedId(isExpanded ? null : plan.id)}
                            className="rounded-bc p-2 text-bc-gray-400 transition-colors hover:bg-bc-gray-100 hover:text-bc-gray-700"
                            aria-label={isExpanded ? t('Collapse plan') : t('Expand plan')}
                          >
                            {isExpanded ? <ChevronUp className="w-5 h-5" /> : <ChevronDown className="w-5 h-5" />}
                          </button>
                        </div>
                      </div>
                    </div>

                    {isExpanded ? (
                      <div className="border-t border-bc-gray-200 px-5 py-5">
                        <div className="space-y-5">
                          <div>
                            <h4 className="font-semibold text-bc-gray-800">{t('Generation settings')}</h4>
                            <div className="mt-3 grid gap-3 md:grid-cols-2">
                              <div className="rounded-bc bg-bc-gray-50 p-3 text-sm text-bc-gray-700">
                                <strong>{t('Category')}:</strong> {selectedCategories.length > 0 ? selectedCategories.join(', ') : '—'}
                              </div>
                              <div className="rounded-bc bg-bc-gray-50 p-3 text-sm text-bc-gray-700">
                                <strong>{t('Topic / Instructions')}:</strong> {plan.topic || '—'}
                              </div>
                              <div className="rounded-bc bg-bc-gray-50 p-3 text-sm text-bc-gray-700">
                                <strong>{t('Keywords')}:</strong> {plan.keywords.length > 0 ? plan.keywords.join(', ') : '—'}
                              </div>
                              <div className="rounded-bc bg-bc-gray-50 p-3 text-sm text-bc-gray-700">
                                <strong>{t('Post length')}:</strong> {t(plan.post_length === 'auto' ? 'AI decides' : (String(plan.post_length || 'medium').charAt(0).toUpperCase() + String(plan.post_length || 'medium').slice(1)))}
                              </div>
                              <div className="rounded-bc bg-bc-gray-50 p-3 text-sm text-bc-gray-700">
                                <strong>{t('Number of posts')}:</strong> {plan.post_count}
                              </div>
                              <div className="rounded-bc bg-bc-gray-50 p-3 text-sm text-bc-gray-700">
                                <strong>{t('Category distribution')}:</strong> {plan.count_per_category ? t('Per category') : t('Total')}
                              </div>
                              {plan.generation_type === 'repeating' ? (
                                <>
                                  <div className="rounded-bc bg-bc-gray-50 p-3 text-sm text-bc-gray-700">
                                    <strong>{t('Recurring schedule')}:</strong> {formatRecurringSummary(plan)}
                                  </div>
                                  <div className="rounded-bc bg-bc-gray-50 p-3 text-sm text-bc-gray-700">
                                    <strong>{t('Remaining budget')}:</strong> {formatRemainingBudget(plan)}
                                  </div>
                                </>
                              ) : null}
                            </div>
                          </div>

                          <div>
                            <h4 className="font-semibold text-bc-gray-800">{t('Technical rules')}</h4>
                            <div className="mt-3 rounded-bc bg-bc-gray-50 p-4 text-sm text-bc-gray-700 whitespace-pre-wrap">
                              {plan.technical_rules?.summary || '—'}
                            </div>
                          </div>

                          <div>
                            <h4 className="font-semibold text-bc-gray-800">{t('Content Plan')}</h4>
                            <div className="mt-3 rounded-bc bg-bc-gray-50 p-4 text-sm text-bc-gray-700 whitespace-pre-wrap">
                              {plan.summary || '—'}
                            </div>
                            <div className="mt-3 grid gap-3 md:grid-cols-2">
                              <div className="rounded-bc bg-bc-gray-50 p-3 text-sm text-bc-gray-700">
                                <strong>{t('Research')}:</strong>{' '}
                                {plan.content_plan?.research_enabled ? t('Enabled') : t('Disabled')}
                              </div>
                              <div className="rounded-bc bg-bc-gray-50 p-3 text-sm text-bc-gray-700">
                                <strong>{t('Topic Tree')}:</strong>{' '}
                                {getTopicTreeArticleCount(plan) > 0
                                  ? tf('%d angles planned', getTopicTreeArticleCount(plan))
                                  : t('Not planned yet')}
                              </div>
                            </div>
                          </div>

                          <div>
                            <h4 className="font-semibold text-bc-gray-800">{t('Saved chat preview')}</h4>
                            <div className="mt-3 space-y-3">
                              <div className="rounded-bc border border-bc-gray-200 p-3">
                                <div className="mb-2 text-sm font-medium text-bc-gray-800">{t('Technical chat')}</div>
                                <div className="space-y-2 text-sm text-bc-gray-600">
                                  {(preview?.technical || []).length > 0 ? preview.technical.map((message, index) => (
                                    <div key={`${message.role}-${index}`} className="rounded-bc bg-bc-gray-50 px-3 py-2">
                                      <strong>{message.role === 'assistant' ? t('Assistant') : t('You')}:</strong> {message.content}
                                    </div>
                                  )) : <div>—</div>}
                                </div>
                              </div>
                              <div className="rounded-bc border border-bc-gray-200 p-3">
                                <div className="mb-2 text-sm font-medium text-bc-gray-800">{t('Content planning chat')}</div>
                                <div className="space-y-2 text-sm text-bc-gray-600">
                                  {(preview?.content || []).length > 0 ? preview.content.map((message, index) => (
                                    <div key={`${message.role}-${index}`} className="rounded-bc bg-bc-gray-50 px-3 py-2">
                                      <strong>{message.role === 'assistant' ? t('Assistant') : t('You')}:</strong> {message.content}
                                    </div>
                                  )) : <div>—</div>}
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    ) : null}
                  </Card>
                )
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
