import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { Badge, Button, Card, EmptyState, Select } from "../../components/ui";
import { useData, useRepos } from "../../data/DataContext";
import type { OwnPost, ThreadsAccount } from "../../domain/types";
import {
  buildAccountInsights,
  ensureInsightHistory,
  fmtDelta,
  fmtEngRate,
  monthKeyFromDate,
  monthLabel,
  topPostsForMonth,
  type AccountInsightsReport,
  type AccountInsightsSnapshot,
  type MonthBucket,
} from "../../lib/accountInsights";
import {
  needsPastMonthBackfill,
  OWN_POSTS_CURRENT_TTL_MS,
  syncOwnPostsGated,
} from "../../lib/ownPostsSyncGate";
import { formatLocalDateTime } from "../../lib/time";
import { useI18n } from "../../i18n/I18nContext";

type Props = {
  /** 由創作頁帶入；空則面板內自選帳號 */
  accountId?: string;
  /** 隱藏內建帳號列（創作頁已有 studio bar） */
  hideAccountSelect?: boolean;
  /** 顯示頁級標題（獨立 /app/insights 用） */
  showTitle?: boolean;
};

function DeltaBadge({ value }: { value: number | null }) {
  const { t } = useI18n();
  if (value == null) return <Badge tone="neutral">{t("common.dash")}</Badge>;
  if (value > 0) return <Badge tone="success">{fmtDelta(value)}</Badge>;
  if (value < 0) return <Badge tone="danger">{fmtDelta(value)}</Badge>;
  return <Badge tone="neutral">{t("insights.zeroPct")}</Badge>;
}

function MonthBars({
  months,
  metric,
  selectedKey,
  onSelect,
}: {
  months: MonthBucket[];
  metric: "views" | "likes" | "replies" | "posts";
  selectedKey: string;
  onSelect: (monthKey: string) => void;
}) {
  const { t, locale } = useI18n();
  const max = Math.max(1, ...months.map((m) => m[metric]));
  const labels: Record<typeof metric, string> = {
    views: t("insights.metricViews"),
    likes: t("insights.metricLikes"),
    replies: t("insights.metricReplies"),
    posts: t("insights.metricPostsFull"),
  };
  const loc = locale === "en" ? "en-US" : "zh-TW";
  return (
    <div className="hb-insights-bars" aria-label={t("insights.barsAria", { metric: labels[metric] })}>
      <p className="hb-field__label" style={{ margin: "0 0 0.5rem" }}>
        {t("insights.barsLabel", { metric: labels[metric], n: months.length })}
        <span className="text-muted" style={{ fontWeight: 500 }}>
          {t("insights.clickBar")}
        </span>
      </p>
      <div className="hb-insights-bars__row" role="listbox" aria-label={t("insights.pickMonthAria")}>
        {months.map((m) => {
          const h = Math.round((m[metric] / max) * 100);
          const selected = m.key === selectedKey;
          const valStr = m[metric].toLocaleString(loc);
          return (
            <button
              key={m.key}
              type="button"
              role="option"
              aria-selected={selected}
              className={`hb-insights-bar${selected ? " is-selected" : ""}${m.source === "estimate" ? " is-estimate" : ""}`}
              onClick={() => onSelect(m.key)}
              title={t("insights.barTitle", {
                label: m.label,
                value: valStr,
                est: m.source === "estimate" ? t("insights.est") : "",
              })}
            >
              <div className="hb-insights-bar__track">
                <div
                  className={`hb-insights-bar__fill${selected ? " is-current" : ""}${m.source === "estimate" ? " is-estimate" : ""}`}
                  style={{ height: `${Math.max(h, m[metric] > 0 ? 6 : 2)}%` }}
                />
              </div>
              <span className="hb-insights-bar__val">
                {metric === "views" && m.views >= 1000
                  ? `${Math.round(m.views / 100) / 10}k`
                  : m[metric]}
              </span>
              <span className={`hb-insights-bar__lab${selected ? " is-current" : ""}`}>
                {t("insights.monthSuffix", { m: m.label.replace(/^\d+\//, "") })}
              </span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Sparkline({
  months,
  metric,
  selectedKey,
  onSelect,
}: {
  months: MonthBucket[];
  metric: "views" | "likes";
  selectedKey: string;
  onSelect: (monthKey: string) => void;
}) {
  const { t } = useI18n();
  const w = 280;
  const h = 56;
  const pad = 4;
  const vals = months.map((m) => m[metric]);
  const max = Math.max(1, ...vals);
  const min = Math.min(...vals, 0);
  const span = Math.max(1, max - min);
  const pts = vals.map((v, i) => {
    const x = pad + (i * (w - pad * 2)) / Math.max(1, vals.length - 1);
    const y = h - pad - ((v - min) / span) * (h - pad * 2);
    return `${x},${y}`;
  });
  const poly = pts.join(" ");
  return (
    <svg
      className="hb-insights-spark"
      viewBox={`0 0 ${w} ${h}`}
      width="100%"
      height={h}
      role="img"
      aria-label={t("insights.sparkAria")}
    >
      <polyline
        fill="none"
        stroke="var(--hb-brand)"
        strokeWidth="2.2"
        strokeLinejoin="round"
        strokeLinecap="round"
        points={poly}
      />
      {vals.map((v, i) => {
        const x = pad + (i * (w - pad * 2)) / Math.max(1, vals.length - 1);
        const y = h - pad - ((v - min) / span) * (h - pad * 2);
        const m = months[i]!;
        const selected = m.key === selectedKey;
        return (
          <g key={m.key} style={{ cursor: "pointer" }} onClick={() => onSelect(m.key)}>
            <circle cx={x} cy={y} r={12} fill="transparent" />
            <circle
              cx={x}
              cy={y}
              r={selected ? 4.5 : 2.4}
              fill={selected ? "var(--hb-brand)" : "var(--hb-surface)"}
              stroke="var(--hb-brand)"
              strokeWidth="1.5"
            />
          </g>
        );
      })}
    </svg>
  );
}

/**
 * 帳號成效：同步貼文 → 聚合近月 KPI／圖表／結論與建議。
 * - 過去月份缺資料：整帳只真 API 補抓一次（past-once）
 * - 本月：面板開啟時每 5 分鐘真 API 刷新（singleflight 合併並發）
 * - 下方貼文列表依選中月份過濾
 */
export function InsightsPanel({
  accountId: accountIdProp,
  hideAccountSelect = false,
  showTitle = false,
}: Props) {
  const repos = useRepos();
  const { tick, refresh } = useData();
  const { t, locale } = useI18n();
  const numLoc = locale === "en" ? "en-US" : "zh-TW";

  const [accounts, setAccounts] = useState<ThreadsAccount[]>([]);
  const [localAccountId, setLocalAccountId] = useState("");
  const [posts, setPosts] = useState<OwnPost[]>([]);
  const [syncedAt, setSyncedAt] = useState<number | null>(null);
  const [metric, setMetric] = useState<"views" | "likes" | "replies" | "posts">("views");
  const [busy, setBusy] = useState("");
  const [message, setMessage] = useState("");
  const [analysisMonth, setAnalysisMonth] = useState(monthKeyFromDate());
  const [history, setHistory] = useState<AccountInsightsSnapshot[]>([]);
  const [historyTick, setHistoryTick] = useState(0);
  const bootstrappedRef = useRef<string>("");

  const accountId = accountIdProp || localAccountId;
  const currentMonthKey = monthKeyFromDate();

  const ops = useMemo(
    () => ({
      list: (id: string) => repos.ownPosts.list(id),
      sync: (id: string) => repos.ownPosts.sync(id),
    }),
    [repos.ownPosts],
  );

  const applyPosts = useCallback(
    async (list: OwnPost[], opts?: { quiet?: boolean }) => {
      setPosts(list);
      const last = await repos.ownPosts.lastSyncedAt().catch(() => null);
      setSyncedAt(last);
      setHistoryTick((n) => n + 1);
      if (!opts?.quiet) refresh();
    },
    [repos.ownPosts, refresh],
  );

  useEffect(() => {
    void (async () => {
      const acc = await repos.accounts.list();
      const usable = acc.filter((a) => a.is_usable);
      const list = usable.length ? usable : acc;
      setAccounts(list);
      setLocalAccountId((cur) => cur || list[0]?.id || "");
    })();
  }, [repos, tick]);

  // 進帳號：list → 必要時 past-once / 過期 current-ttl 真 sync（singleflight）
  useEffect(() => {
    if (!accountId) {
      setPosts([]);
      setSyncedAt(null);
      bootstrappedRef.current = "";
      return;
    }

    let cancelled = false;
    const runId = accountId;
    bootstrappedRef.current = "";

    void (async () => {
      setBusy("load");
      setMessage("");
      try {
        let list = await ops.list(accountId);
        if (cancelled) return;
        await applyPosts(list, { quiet: true });
        setAnalysisMonth(monthKeyFromDate());

        const report0 = buildAccountInsights(accountId, list, 6);
        const needPast = needsPastMonthBackfill(report0.months, currentMonthKey);

        // 過去月缺資料 → 真 API 補一次；否則本月過 5 分鐘才再抓
        setBusy("sync");
        const out = await syncOwnPostsGated(
          accountId,
          ops,
          needPast ? "past-once" : "current-ttl",
        );
        if (cancelled) return;
        if (out.fetched) {
          list = out.posts;
          await applyPosts(list);
          if (out.reason === "past-once") {
            setMessage(t("insights.pastBackfillDone", { n: list.length }));
          }
        }
        bootstrappedRef.current = runId;
      } catch (e) {
        if (!cancelled) {
          setPosts([]);
          setMessage(e instanceof Error ? e.message : t("insights.loadFail"));
        }
      } finally {
        if (!cancelled) setBusy("");
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [accountId, ops, applyPosts, currentMonthKey, t]);

  // 本月：每 5 分鐘真 API 更新（singleflight；面板卸載即停）
  useEffect(() => {
    if (!accountId) return;
    const timer = window.setInterval(() => {
      void (async () => {
        try {
          const out = await syncOwnPostsGated(accountId, ops, "current-ttl");
          if (out.fetched) {
            await applyPosts(out.posts);
            setMessage(t("insights.autoRefreshDone", { n: out.posts.length }));
          }
        } catch {
          /* 背景刷新失敗不打斷 UI */
        }
      })();
    }, OWN_POSTS_CURRENT_TTL_MS);
    return () => window.clearInterval(timer);
  }, [accountId, ops, applyPosts, t]);

  useEffect(() => {
    const onStore = () => refresh();
    window.addEventListener("harbor:store", onStore);
    return () => window.removeEventListener("harbor:store", onStore);
  }, [refresh]);

  const report: AccountInsightsReport | null = useMemo(() => {
    if (!accountId) return null;
    return buildAccountInsights(accountId, posts, 6);
  }, [accountId, posts]);

  useEffect(() => {
    if (!report) {
      setHistory([]);
      return;
    }
    // 本月覆寫分析；歷史月有資料才寫一次（ensure 內部會跳過已存在）
    const forceCurrent = analysisMonth === currentMonthKey || analysisMonth === report.current.key;
    const list = ensureInsightHistory(report, { forceCurrent });
    setHistory(list);
  }, [report, historyTick, analysisMonth, currentMonthKey]);

  const selectedSnap = useMemo(
    () => history.find((s) => s.month_key === analysisMonth) || history[0] || null,
    [history, analysisMonth],
  );

  const selectedMonthBucket = useMemo(() => {
    if (!report) return null;
    return report.months.find((m) => m.key === analysisMonth) || report.current;
  }, [report, analysisMonth]);

  const monthTopPosts = useMemo(
    () => topPostsForMonth(posts.filter((p) => !accountId || p.account_id === accountId), analysisMonth, 8),
    [posts, accountId, analysisMonth],
  );

  const selectedMonthPrev = useMemo(() => {
    if (!report) return null;
    const idx = report.months.findIndex((m) => m.key === analysisMonth);
    if (idx <= 0) return null;
    return report.months[idx - 1] || null;
  }, [report, analysisMonth]);

  const selectedDelta = useMemo(() => {
    if (!selectedMonthBucket || !selectedMonthPrev) {
      return { views: null as number | null, likes: null, replies: null, engagementRate: null };
    }
    const pct = (c: number, p: number) => {
      if (p <= 0 && c <= 0) return 0;
      if (p <= 0) return c > 0 ? 100 : null;
      return Math.round(((c - p) / p) * 1000) / 10;
    };
    return {
      views: pct(selectedMonthBucket.views, selectedMonthPrev.views),
      likes: pct(selectedMonthBucket.likes, selectedMonthPrev.likes),
      replies: pct(selectedMonthBucket.replies, selectedMonthPrev.replies),
      engagementRate: pct(
        selectedMonthBucket.engagementRate * 100,
        selectedMonthPrev.engagementRate * 100,
      ),
    };
  }, [selectedMonthBucket, selectedMonthPrev]);

  async function syncPosts() {
    if (!accountId) return;
    setBusy("sync");
    setMessage("");
    try {
      const out = await syncOwnPostsGated(accountId, ops, "manual");
      await applyPosts(out.posts);
      setMessage(t("insights.syncDone", { n: out.posts.length }));
    } catch (e) {
      setMessage(e instanceof Error ? e.message : t("insights.syncFail"));
    } finally {
      setBusy("");
    }
  }

  function selectMonth(key: string) {
    setAnalysisMonth(key);
  }

  const account =
    accounts.find((a) => a.id === accountId) ||
    (accountId
      ? ({ id: accountId, username: "", display_name: "" } as ThreadsAccount)
      : undefined);
  const hasPosts = (report?.totalPosts ?? 0) > 0;
  const zeroViews = hasPosts && posts.every((p) => (p.view_count || 0) === 0);
  const kpi = selectedMonthBucket || report?.current;
  const isCurrentSelected = analysisMonth === currentMonthKey;

  return (
    <div className={`hb-insights-panel${showTitle ? " is-page" : ""}`}>
      <div className="hb-insights-toolbar">
        {!hideAccountSelect ? (
          <Select
            label={t("insights.account")}
            value={accountId}
            onChange={(e) => setLocalAccountId(e.target.value)}
            disabled={!accounts.length || Boolean(accountIdProp)}
          >
            {accounts.length === 0 ? (
              <option value="">{t("insights.noAccount")}</option>
            ) : (
              accounts.map((a) => (
                <option key={a.id} value={a.id}>
                  @{a.username}
                  {a.display_name ? ` · ${a.display_name}` : ""}
                </option>
              ))
            )}
          </Select>
        ) : (
          <div className="hb-insights-toolbar__hint">
            <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-sm)" }}>
              {t("insights.panelHint")}
              {syncedAt ? (
                <>
                  {" · "}
                  {t("insights.lastSynced", { time: formatLocalDateTime(syncedAt) })}
                </>
              ) : (
                <> · {t("insights.neverSynced")}</>
              )}
            </p>
          </div>
        )}
        <div className="hb-insights-toolbar__actions">
          <Button
            type="button"
            disabled={Boolean(busy) || !accountId}
            onClick={() => void syncPosts()}
          >
            {busy === "sync" ? t("insights.syncing") : t("insights.syncPosts")}
          </Button>
          <Link to="/app/studio?tab=posts">
            <Button type="button" variant="ghost">
              {t("insights.myPosts")}
            </Button>
          </Link>
        </div>
      </div>

      {message ? (
        <p className="hb-banner-ok hb-insights-status" role="status">
          {message}
        </p>
      ) : null}

      {!accountId || !report ? (
        <EmptyState
          title={t("insights.pickAccount")}
          action={
            <Link to="/app/crew">
              <Button type="button">{t("insights.goAccounts")}</Button>
            </Link>
          }
        />
      ) : !hasPosts ? (
        <EmptyState
          title={t("insights.emptyTitle")}
          description={t("insights.emptyDesc")}
          action={
            <Button type="button" disabled={Boolean(busy)} onClick={() => void syncPosts()}>
              {busy === "sync" ? t("insights.syncing") : t("insights.syncPosts")}
            </Button>
          }
        />
      ) : (
        <div className="hb-stack">
          {zeroViews ? (
            <p className="hb-banner-warn hb-insights-status" role="status">
              {t("insights.zeroViewsHint")}
            </p>
          ) : null}

          <div
            className="hb-today-metrics hb-insights-kpis"
            role="group"
            aria-label={t("insights.kpiForMonth", {
              label: monthLabel(analysisMonth),
            })}
          >
            <div className="hb-today-metric">
              <span className="hb-today-metric__label">
                {isCurrentSelected ? t("insights.monthViews") : t("insights.metricViews")}
              </span>
              <span className="hb-today-metric__value">
                {(kpi?.views ?? 0).toLocaleString(numLoc)}
              </span>
              <span className="hb-today-metric__hint">
                {t("insights.vsPrev")} <DeltaBadge value={selectedDelta.views} />
              </span>
            </div>
            <div className="hb-today-metric">
              <span className="hb-today-metric__label">
                {isCurrentSelected ? t("insights.monthLikes") : t("insights.metricLikes")}
              </span>
              <span className="hb-today-metric__value">{kpi?.likes ?? 0}</span>
              <span className="hb-today-metric__hint">
                {t("insights.vsPrev")} <DeltaBadge value={selectedDelta.likes} />
              </span>
            </div>
            <div className="hb-today-metric">
              <span className="hb-today-metric__label">
                {isCurrentSelected ? t("insights.monthReplies") : t("insights.metricReplies")}
              </span>
              <span className="hb-today-metric__value">{kpi?.replies ?? 0}</span>
              <span className="hb-today-metric__hint">
                {t("insights.vsPrev")} <DeltaBadge value={selectedDelta.replies} />
              </span>
            </div>
            <div className="hb-today-metric">
              <span className="hb-today-metric__label">{t("insights.engRate")}</span>
              <span className="hb-today-metric__value">
                {fmtEngRate(kpi?.engagementRate ?? 0)}
              </span>
              <span className="hb-today-metric__hint">
                {t("insights.postsInMonth", { n: kpi?.posts ?? 0 })} ·{" "}
                <DeltaBadge value={selectedDelta.engagementRate} />
              </span>
            </div>
          </div>

          <Card title={t("insights.trendTitle", { user: account?.username || "—" })}>
            <div className="hb-stack">
              <Sparkline
                months={report.months}
                metric={metric === "likes" ? "likes" : "views"}
                selectedKey={analysisMonth}
                onSelect={selectMonth}
              />
              <div className="hb-tabs hb-tabs--sm" role="tablist" aria-label={t("insights.chartMetrics")}>
                {(["views", "likes", "replies", "posts"] as const).map((m) => (
                  <button
                    key={m}
                    type="button"
                    className={`hb-tab ${metric === m ? "is-active" : ""}`}
                    onClick={() => setMetric(m)}
                  >
                    {m === "views"
                      ? t("insights.metricViews")
                      : m === "likes"
                        ? t("insights.metricLikes")
                        : m === "replies"
                          ? t("insights.metricReplies")
                          : t("insights.metricPosts")}
                  </button>
                ))}
              </div>
              <MonthBars
                months={report.months}
                metric={metric}
                selectedKey={analysisMonth}
                onSelect={selectMonth}
              />
              {(kpi?.posts ?? 0) <= 0 ? (
                <p className="text-muted hb-insights-no-analysis" style={{ margin: 0 }}>
                  {t("insights.noDataNoAnalysis", { label: monthLabel(analysisMonth) })}
                </p>
              ) : selectedSnap &&
                (selectedSnap.analysis.length > 0 || selectedSnap.recommendations.length > 0) ? (
                <div className="hb-insights-snap-panel">
                  <div className="hb-insights-snap-meta">
                    <strong>{t("insights.analysisOf", { label: selectedSnap.month_label })}</strong>
                    <span className="text-muted" style={{ fontSize: "var(--hb-text-xs)" }}>
                      {t("insights.producedAt", { time: formatLocalDateTime(selectedSnap.analyzed_at) })}
                      {selectedSnap.delta.views != null
                        ? t("insights.viewsVsPrev", { delta: fmtDelta(selectedSnap.delta.views) })
                        : ""}
                    </span>
                    <div className="hb-insights-snap-metrics">
                      <span>
                        {t("insights.statPosts")} <strong>{selectedSnap.metrics.posts}</strong>
                      </span>
                      <span>
                        {t("insights.statViews")}{" "}
                        <strong>{selectedSnap.metrics.views.toLocaleString(numLoc)}</strong>
                      </span>
                      <span>
                        {t("insights.statLikes")} <strong>{selectedSnap.metrics.likes}</strong>
                      </span>
                      <span>
                        {t("insights.statReplies")} <strong>{selectedSnap.metrics.replies}</strong>
                      </span>
                      <span>
                        {t("insights.engRate")}{" "}
                        <strong>{fmtEngRate(selectedSnap.metrics.engagementRate)}</strong>
                      </span>
                    </div>
                  </div>
                  {selectedSnap.analysis.length > 0 ? (
                    <div>
                      <p className="hb-field__label" style={{ margin: "0 0 0.4rem" }}>
                        {t("insights.conclusions")}
                      </p>
                      <ul className="hb-insights-bullets">
                        {selectedSnap.analysis.map((line) => (
                          <li key={line}>{line}</li>
                        ))}
                      </ul>
                    </div>
                  ) : null}
                  {selectedSnap.recommendations.length > 0 ? (
                    <div>
                      <p className="hb-field__label" style={{ margin: "0 0 0.4rem" }}>
                        {t("insights.recommendations")}
                      </p>
                      <ul className="hb-insights-bullets hb-insights-bullets--action">
                        {selectedSnap.recommendations.map((line) => (
                          <li key={line}>{line}</li>
                        ))}
                      </ul>
                    </div>
                  ) : null}
                  {selectedSnap.top_highlights?.length ? (
                    <div>
                      <p className="hb-field__label" style={{ margin: "0 0 0.4rem" }}>
                        {t("insights.highlights")}
                      </p>
                      <ul className="hb-insights-bullets">
                        {selectedSnap.top_highlights.map((h) => (
                          <li key={h}>{h}</li>
                        ))}
                      </ul>
                    </div>
                  ) : null}
                  <div className="hb-wizard-actions">
                    <Link to="/app/studio?tab=inspire">
                      <Button type="button" variant="ghost">
                        {t("insights.findTopics")}
                      </Button>
                    </Link>
                    <Link to="/app/scout">
                      <Button type="button" variant="ghost">
                        {t("insights.goScout")}
                      </Button>
                    </Link>
                  </div>
                </div>
              ) : (
                <p className="text-muted" style={{ margin: 0 }}>
                  {t("insights.noAnalysisYet", { label: monthLabel(analysisMonth) })}
                </p>
              )}
            </div>
          </Card>

          <Card
            title={t("insights.topPostsOfMonth", {
              label: monthLabel(analysisMonth),
            })}
          >
            {monthTopPosts.length === 0 ? (
              <EmptyState
                title={t("insights.noPostsInMonth", { label: monthLabel(analysisMonth) })}
                description={
                  isCurrentSelected
                    ? t("insights.emptyDesc")
                    : t("insights.pastMonthEmptyHint")
                }
                action={
                  isCurrentSelected ? (
                    <Button type="button" onClick={() => void syncPosts()} disabled={Boolean(busy)}>
                      {busy === "sync" ? t("insights.syncing") : t("insights.syncPosts")}
                    </Button>
                  ) : undefined
                }
              />
            ) : (
              <ul className="hb-today-list">
                {monthTopPosts.map((p, i) => (
                  <li key={p.id}>
                    <div className="hb-today-list__item" style={{ cursor: "default" }}>
                      <span className="hb-today-list__meta">
                        <Badge tone={i === 0 ? "success" : "neutral"}>#{i + 1}</Badge>
                        {p.topic_tag ? <Badge tone="brand">{p.topic_tag}</Badge> : null}
                        <span>
                          {t("insights.postStats", {
                            views: p.view_count.toLocaleString(numLoc),
                            likes: p.like_count,
                            replies: p.reply_count,
                          })}
                        </span>
                        <span>{formatLocalDateTime(p.published_at)}</span>
                      </span>
                      <span className="hb-today-list__text">
                        {p.text.slice(0, 120)}
                        {p.text.length > 120 ? "…" : ""}
                      </span>
                      {p.insight || p.formula_summary ? (
                        <span className="text-muted" style={{ fontSize: "var(--hb-text-xs)" }}>
                          {p.insight || p.formula_summary}
                        </span>
                      ) : null}
                      {p.permalink ? (
                        <a href={p.permalink} target="_blank" rel="noreferrer" style={{ fontSize: "var(--hb-text-xs)" }}>
                          {t("insights.openThreads")}
                        </a>
                      ) : null}
                    </div>
                  </li>
                ))}
              </ul>
            )}
          </Card>
        </div>
      )}
    </div>
  );
}
