// Content Management — 商品刊登 / 徵稿 / 動態

const STATUS_META = {
  published: { label: "公開中", tone: "success" },
  hidden:    { label: "隱藏中", tone: "warn" },
  takedown:  { label: "已下架", tone: "danger" },
};

const StatusBadge = ({ status }) => {
  const m = STATUS_META[status] || STATUS_META.published;
  return <Badge tone={m.tone} size="sm" dot>{m.label}</Badge>;
};

const DATE_FILTER_OPTIONS = [
  { value: "all", label: "所有時間" },
  { value: "7d",  label: "7 日內" },
  { value: "30d", label: "30 日內" },
  { value: "90d", label: "90 日內" },
];

function applyDateFilter(items, dateFilter) {
  if (dateFilter === "all") return items;
  const days = { "7d": 7, "30d": 30, "90d": 90 }[dateFilter];
  if (!days) return items;
  const cutoff = new Date();
  cutoff.setDate(cutoff.getDate() - days);
  const cutoffStr = cutoff.toISOString().slice(0, 10);
  return items.filter(p => (p.createdAt ?? "") >= cutoffStr);
}

// ── Products tab ──────────────────────────────────────────────────────────────

const ProductsTab = ({ onSelect, onRemoveRef, onUpdateRef, exportRef, refreshRef }) => {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  if (onRemoveRef) onRemoveRef.current = id => setItems(prev => prev.filter(p => p.id !== id));
  if (onUpdateRef) onUpdateRef.current = (id, status) => setItems(prev => prev.map(p => p.id === id ? { ...p, status } : p));
  const [query, setQuery] = useState("");
  const [typeFilter, setTypeFilter] = useState("all");
  const [dateFilter, setDateFilter] = useState("all");
  const [page, setPage] = useState(0);

  const load = () => {
    setLoading(true);
    fetch("/api/admin/content?type=products")
      .then(r => r.ok ? r.json() : [])
      .then(d => { if (Array.isArray(d)) setItems(d); })
      .catch(() => {})
      .finally(() => setLoading(false));
  };
  if (refreshRef) refreshRef.current = load;
  useEffect(() => { load(); }, []);

  useEffect(() => { setPage(0); }, [query, typeFilter, dateFilter]);

  const filtered = applyDateFilter(items, dateFilter).filter(p => {
    if (typeFilter === "auction" && p.type !== "auction") return false;
    if (typeFilter === "commission" && p.type !== "commission") return false;
    if (query) {
      const q = query.toLowerCase();
      if (!p.name.toLowerCase().includes(q) && !p.artistName.toLowerCase().includes(q)) return false;
    }
    return true;
  });
  if (exportRef) exportRef.current = () => csvDownload(`products_${Date.now()}.csv`,
    ["ID","名稱","創作者","類型","價格","售出","庫存","狀態","建立時間"],
    filtered.map(p => [p.id, p.name, p.artistName, p.type, p.price, p.salesCount, p.stock, p.status, p.createdAt])
  );

  const PAGE = 15;

  return (
    <div>
      <div style={{ display: "flex", gap: 10, marginBottom: 14 }}>
        <div style={{ flex: 1, maxWidth: 320 }}>
          <Input icon="search" placeholder="商品名稱、創作者…" value={query} onChange={e => setQuery(e.target.value)}/>
        </div>
        <Select value={typeFilter} onChange={setTypeFilter} icon="order" options={[
          { value: "all", label: "所有類型" },
          { value: "auction", label: "繪圖" },
          { value: "commission", label: "文集" },
        ]}/>
        <Select value={dateFilter} onChange={setDateFilter} icon="calendar" options={DATE_FILTER_OPTIONS}/>
        <div style={{ flex: 1 }}/>
        <div style={{ fontSize: 12, color: "var(--ink-3)", alignSelf: "center" }}>{filtered.length} 件商品</div>
      </div>
      {loading ? (
        <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>載入中…</div>
      ) : filtered.length === 0 ? (
        <div style={{ padding: 60, textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>目前沒有符合條件的商品</div>
      ) : (
        <>
          <Table
            onRowClick={onSelect}
            columns={[
              { title: "商品", render: p => (
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <div style={{
                    width: 38, height: 38, borderRadius: 8, flexShrink: 0, overflow: "hidden",
                    background: p.image ? "#000" : `oklch(82% 0.10 ${(p.id.charCodeAt(0) * 47) % 360})`,
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}>
                    {p.image
                      ? <img src={p.image} style={{ width: "100%", height: "100%", objectFit: "cover" }} onError={e => { e.target.style.display = "none"; }}/>
                      : <Icon name="palette" size={16} style={{ color: "rgba(255,255,255,0.6)" }}/>}
                  </div>
                  <div>
                    <div style={{ fontSize: 13.5, fontWeight: 500 }}>{p.name}</div>
                    <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 1 }}>
                      {(p.tags ?? []).slice(0, 3).map(t => (
                        <span key={t} style={{ marginRight: 4 }}>#{t}</span>
                      ))}
                    </div>
                  </div>
                </div>
              )},
              { title: "創作者", render: p => (
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  {p.artistAvatar && !p.artistAvatar.includes("avatar-default")
                    ? <img src={p.artistAvatar} style={{ width: 24, height: 24, borderRadius: "50%", objectFit: "cover" }}/>
                    : <Avatar hue={200} glyph={p.artistName?.[0] ?? "?"} size={24}/>}
                  <span style={{ fontSize: 13 }}>{p.artistName}</span>
                </div>
              )},
              { title: "類型", render: p => (
                <Badge tone={p.type === "auction" ? "accent" : "info"} size="sm">
                  {p.type === "auction" ? "繪圖" : p.type === "commission" ? "文集" : p.type || "—"}
                </Badge>
              )},
              { title: "售出", align: "right", render: p => <span className="mono" style={{ fontSize: 13 }}>{p.salesCount}</span> },
              { title: "價格", align: "right", render: p => <span className="mono" style={{ fontWeight: 500 }}>{p.price ? `NT$ ${fmtNum(p.price)}` : p.priceLabel || "—"}</span> },
              { title: "狀態", render: p => <StatusBadge status={p.status}/> },
              { title: "建立時間", render: p => <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{p.createdAt}</span> },
            ]}
            rows={filtered.slice(page * PAGE, (page + 1) * PAGE)}
          />
          <Pagination total={filtered.length} pageSize={PAGE} page={page} onPageChange={setPage}/>
        </>
      )}
    </div>
  );
};

// ── Solicits tab ──────────────────────────────────────────────────────────────

const SolicitTab = ({ onSelect, onRemoveRef, onUpdateRef, exportRef, refreshRef }) => {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  if (onRemoveRef) onRemoveRef.current = id => setItems(prev => prev.filter(p => p.id !== id));
  if (onUpdateRef) onUpdateRef.current = (id, status) => setItems(prev => prev.map(p => p.id === id ? { ...p, status } : p));
  const [query, setQuery] = useState("");
  const [dateFilter, setDateFilter] = useState("all");
  const [page, setPage] = useState(0);

  const load = () => {
    setLoading(true);
    fetch("/api/admin/content?type=solicits")
      .then(r => r.ok ? r.json() : [])
      .then(d => { if (Array.isArray(d)) setItems(d); })
      .catch(() => {})
      .finally(() => setLoading(false));
  };
  if (refreshRef) refreshRef.current = load;
  useEffect(() => { load(); }, []);

  useEffect(() => { setPage(0); }, [query, dateFilter]);

  const filtered = applyDateFilter(items, dateFilter).filter(p => {
    if (!query) return true;
    const q = query.toLowerCase();
    return p.title.toLowerCase().includes(q) || p.authorName.toLowerCase().includes(q);
  });
  if (exportRef) exportRef.current = () => csvDownload(`solicits_${Date.now()}.csv`,
    ["ID","標題","委託人","預算","截止日","狀態","發布時間"],
    filtered.map(p => [p.id, p.title, p.authorName, p.budget, p.deadline, p.status, p.createdAt])
  );

  const PAGE = 15;

  return (
    <div>
      <div style={{ display: "flex", gap: 10, marginBottom: 14 }}>
        <div style={{ flex: 1, maxWidth: 320 }}>
          <Input icon="search" placeholder="徵稿標題、委託人…" value={query} onChange={e => setQuery(e.target.value)}/>
        </div>
        <Select value={dateFilter} onChange={setDateFilter} icon="calendar" options={DATE_FILTER_OPTIONS}/>
        <div style={{ flex: 1 }}/>
        <div style={{ fontSize: 12, color: "var(--ink-3)", alignSelf: "center" }}>{filtered.length} 則徵稿</div>
      </div>
      {loading ? (
        <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>載入中…</div>
      ) : filtered.length === 0 ? (
        <div style={{ padding: 60, textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>目前沒有徵稿資料</div>
      ) : (
        <>
          <Table
            onRowClick={onSelect}
            columns={[
              { title: "標題", render: p => (
                <div>
                  <div style={{ fontSize: 13.5, fontWeight: 500 }}>{p.title}</div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 1 }}>
                    {(p.tags ?? []).slice(0, 3).map(t => (
                      <span key={t} style={{ marginRight: 4 }}>#{t}</span>
                    ))}
                  </div>
                </div>
              )},
              { title: "委託人", render: p => (
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  {p.authorAvatar && !p.authorAvatar.includes("avatar-default")
                    ? <img src={p.authorAvatar} style={{ width: 24, height: 24, borderRadius: "50%", objectFit: "cover" }}/>
                    : <Avatar hue={30} glyph={p.authorName?.[0] ?? "?"} size={24}/>}
                  <span style={{ fontSize: 13 }}>{p.authorName}</span>
                </div>
              )},
              { title: "預算", align: "right", render: p => <span className="mono" style={{ fontWeight: 500 }}>{p.budget ? `NT$ ${fmtNum(p.budget)}` : "—"}</span> },
              { title: "截止日", render: p => <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{p.deadline || "—"}</span> },
              { title: "圖片", align: "right", render: p => <span className="mono" style={{ fontSize: 13, color: "var(--ink-3)" }}>{(p.images ?? []).length} 張</span> },
              { title: "狀態", render: p => <StatusBadge status={p.status}/> },
              { title: "發布時間", render: p => <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{p.createdAt}</span> },
            ]}
            rows={filtered.slice(page * PAGE, (page + 1) * PAGE)}
          />
          <Pagination total={filtered.length} pageSize={PAGE} page={page} onPageChange={setPage}/>
        </>
      )}
    </div>
  );
};

// ── Posts tab ─────────────────────────────────────────────────────────────────

const PostsTab = ({ onSelect, onRemoveRef, onUpdateRef, exportRef, refreshRef }) => {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  if (onRemoveRef) onRemoveRef.current = id => setItems(prev => prev.filter(p => p.id !== id));
  if (onUpdateRef) onUpdateRef.current = (id, status) => setItems(prev => prev.map(p => p.id === id ? { ...p, status } : p));
  const [query, setQuery] = useState("");
  const [dateFilter, setDateFilter] = useState("all");
  const [page, setPage] = useState(0);

  const load = () => {
    setLoading(true);
    fetch("/api/admin/content?type=posts")
      .then(r => r.ok ? r.json() : [])
      .then(d => { if (Array.isArray(d)) setItems(d); })
      .catch(() => {})
      .finally(() => setLoading(false));
  };
  if (refreshRef) refreshRef.current = load;
  useEffect(() => { load(); }, []);

  useEffect(() => { setPage(0); }, [query, dateFilter]);

  const filtered = applyDateFilter(items, dateFilter).filter(p => {
    if (!query) return true;
    const q = query.toLowerCase();
    return p.content.toLowerCase().includes(q) || p.authorName.toLowerCase().includes(q);
  });
  if (exportRef) exportRef.current = () => csvDownload(`posts_${Date.now()}.csv`,
    ["ID","作者","內容","按讚","留言","狀態","發布時間"],
    filtered.map(p => [p.id, p.authorName, p.content.slice(0,100), p.likeCount, p.commentCount, p.status, p.createdAt])
  );

  const PAGE = 15;

  return (
    <div>
      <div style={{ display: "flex", gap: 10, marginBottom: 14 }}>
        <div style={{ flex: 1, maxWidth: 320 }}>
          <Input icon="search" placeholder="內容、作者…" value={query} onChange={e => setQuery(e.target.value)}/>
        </div>
        <Select value={dateFilter} onChange={setDateFilter} icon="calendar" options={DATE_FILTER_OPTIONS}/>
        <div style={{ flex: 1 }}/>
        <div style={{ fontSize: 12, color: "var(--ink-3)", alignSelf: "center" }}>{filtered.length} 則動態</div>
      </div>
      {loading ? (
        <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>載入中…</div>
      ) : filtered.length === 0 ? (
        <div style={{ padding: 60, textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>目前沒有動態資料</div>
      ) : (
        <>
          <Table
            onRowClick={onSelect}
            columns={[
              { title: "內容", render: p => (
                <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
                  {(p.images ?? []).length > 0 && (
                    <div style={{
                      width: 38, height: 38, borderRadius: 8, flexShrink: 0, overflow: "hidden",
                      background: "#000",
                    }}>
                      <img src={p.images[0]} style={{ width: "100%", height: "100%", objectFit: "cover" }} onError={e => { e.target.style.display = "none"; }}/>
                    </div>
                  )}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontSize: 13.5, fontWeight: 400, lineHeight: 1.5,
                      overflow: "hidden", display: "-webkit-box",
                      WebkitLineClamp: 2, WebkitBoxOrient: "vertical",
                      color: "var(--ink-2)",
                    }}>
                      {p.content || <span style={{ color: "var(--ink-4)", fontStyle: "italic" }}>（無文字）</span>}
                    </div>
                    <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>
                      {(p.tags ?? []).slice(0, 3).map(t => (
                        <span key={t} style={{ marginRight: 4 }}>#{t}</span>
                      ))}
                    </div>
                  </div>
                </div>
              )},
              { title: "作者", render: p => (
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  {p.authorAvatar && !p.authorAvatar.includes("avatar-default")
                    ? <img src={p.authorAvatar} style={{ width: 24, height: 24, borderRadius: "50%", objectFit: "cover" }}/>
                    : <Avatar hue={200} glyph={p.authorName?.[0] ?? "?"} size={24}/>}
                  <span style={{ fontSize: 13 }}>{p.authorName}</span>
                </div>
              )},
              { title: "圖片", align: "right", render: p => <span className="mono" style={{ fontSize: 13, color: "var(--ink-3)" }}>{(p.images ?? []).length} 張</span> },
              { title: "按讚", align: "right", render: p => <span className="mono" style={{ fontSize: 13 }}>{fmtNum(p.likeCount)}</span> },
              { title: "留言", align: "right", render: p => <span className="mono" style={{ fontSize: 13 }}>{fmtNum(p.commentCount)}</span> },
              { title: "狀態", render: p => <StatusBadge status={p.status}/> },
              { title: "發布時間", render: p => <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{p.createdAt}</span> },
            ]}
            rows={filtered.slice(page * PAGE, (page + 1) * PAGE)}
          />
          <Pagination total={filtered.length} pageSize={PAGE} page={page} onPageChange={setPage}/>
        </>
      )}
    </div>
  );
};

// ── Hot tab ───────────────────────────────────────────────────────────────────

const HotTab = ({ onSelect, onRemoveRef, onUpdateRef, exportRef, refreshRef }) => {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  if (onRemoveRef) onRemoveRef.current = id => setItems(prev => prev.filter(p => p.id !== id));
  if (onUpdateRef) onUpdateRef.current = (id, status) => setItems(prev => prev.map(p => p.id === id ? { ...p, status } : p));
  const [query, setQuery] = useState("");
  const [dateFilter, setDateFilter] = useState("all");
  const [page, setPage] = useState(0);

  const load = () => {
    setLoading(true);
    fetch("/api/admin/content?type=hot")
      .then(r => r.ok ? r.json() : [])
      .then(d => { if (Array.isArray(d)) setItems(d); })
      .catch(() => {})
      .finally(() => setLoading(false));
  };
  if (refreshRef) refreshRef.current = load;
  useEffect(() => { load(); }, []);

  useEffect(() => { setPage(0); }, [query, dateFilter]);

  const filtered = applyDateFilter(items, dateFilter).filter(p => {
    if (!query) return true;
    const q = query.toLowerCase();
    return p.content.toLowerCase().includes(q) || p.authorName.toLowerCase().includes(q);
  });
  if (exportRef) exportRef.current = () => csvDownload(`hot_${Date.now()}.csv`,
    ["ID","作者","內容","按讚","留言","狀態","發布時間"],
    filtered.map(p => [p.id, p.authorName, p.content.slice(0,100), p.likeCount, p.commentCount, p.status, p.createdAt])
  );

  const PAGE = 15;

  return (
    <div>
      <div style={{ display: "flex", gap: 10, marginBottom: 14 }}>
        <div style={{ flex: 1, maxWidth: 320 }}>
          <Input icon="search" placeholder="內容、作者…" value={query} onChange={e => setQuery(e.target.value)}/>
        </div>
        <Select value={dateFilter} onChange={setDateFilter} icon="calendar" options={DATE_FILTER_OPTIONS}/>
        <div style={{ flex: 1 }}/>
        <div style={{ fontSize: 12, color: "var(--ink-3)", alignSelf: "center" }}>{filtered.length} 則熱門</div>
      </div>
      {loading ? (
        <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)" }}>載入中…</div>
      ) : filtered.length === 0 ? (
        <div style={{ padding: 60, textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>目前沒有熱門資料</div>
      ) : (
        <>
          <Table
            onRowClick={onSelect}
            columns={[
              { title: "#", width: 44, render: (p, i) => (
                <span className="mono" style={{ fontSize: 13, fontWeight: 700, color: i < 3 ? "var(--accent)" : "var(--ink-3)" }}>
                  {page * PAGE + i + 1}
                </span>
              )},
              { title: "內容", render: p => (
                <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
                  {(p.images ?? []).length > 0 && (
                    <div style={{
                      width: 38, height: 38, borderRadius: 8, flexShrink: 0, overflow: "hidden",
                      background: "#000",
                    }}>
                      <img src={p.images[0]} style={{ width: "100%", height: "100%", objectFit: "cover" }} onError={e => { e.target.style.display = "none"; }}/>
                    </div>
                  )}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontSize: 13.5, fontWeight: 400, lineHeight: 1.5,
                      overflow: "hidden", display: "-webkit-box",
                      WebkitLineClamp: 2, WebkitBoxOrient: "vertical",
                      color: "var(--ink-2)",
                    }}>
                      {p.content || <span style={{ color: "var(--ink-4)", fontStyle: "italic" }}>（圖片貼文）</span>}
                    </div>
                  </div>
                </div>
              )},
              { title: "作者", render: p => (
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  {p.authorAvatar && !p.authorAvatar.includes("avatar-default")
                    ? <img src={p.authorAvatar} style={{ width: 24, height: 24, borderRadius: "50%", objectFit: "cover" }}/>
                    : <Avatar hue={200} glyph={p.authorName?.[0] ?? "?"} size={24}/>}
                  <span style={{ fontSize: 13 }}>{p.authorName}</span>
                </div>
              )},
              { title: "按讚", align: "right", render: p => (
                <span className="mono" style={{ fontSize: 13, fontWeight: 600, color: "var(--accent)" }}>{fmtNum(p.likeCount)}</span>
              )},
              { title: "留言", align: "right", render: p => <span className="mono" style={{ fontSize: 13 }}>{fmtNum(p.commentCount)}</span> },
              { title: "狀態", render: p => <StatusBadge status={p.status}/> },
              { title: "發布時間", render: p => <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{p.createdAt}</span> },
            ]}
            rows={filtered.slice(page * PAGE, (page + 1) * PAGE)}
          />
          <Pagination total={filtered.length} pageSize={PAGE} page={page} onPageChange={setPage}/>
        </>
      )}
    </div>
  );
};

// ── Detail drawer (shared) ────────────────────────────────────────────────────

const ContentDetailDrawer = ({ item, tabType, onClose, onRemove, onUpdate }) => {
  const toast = useToast();
  const [acting, setActing] = useState(null);
  const [confirmDelete, setConfirmDelete] = useState(false);
  if (!item) return null;

  const isProduct = tabType === "products";
  const isSolicit = tabType === "solicits";
  const isPost    = tabType === "posts" || tabType === "hot";
  const apiType   = tabType === "hot" ? "posts" : tabType;
  const currentStatus = item.status ?? "published";
  const isActive   = currentStatus === "published";

  const previewUrl = isProduct
    ? `/product/${item.id}`
    : isSolicit
    ? `/solicit/${item.id}`
    : `/feed/${item.id}`;

  async function doAction(action) {
    setActing(action);
    try {
      const url = `/api/admin/content/${item.id}?type=${apiType}`;
      let res;
      if (action === "delete") {
        res = await fetch(url, { method: "DELETE" });
      } else {
        const statusMap = { hide: "hidden", takedown: "takedown", restore: "restore" };
        res = await fetch(url, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ status: statusMap[action] }),
        });
      }
      if (!res.ok) throw new Error(await res.text());
      const titles = { hide: "隱藏成功", takedown: "下架成功", restore: "已復原", delete: "刪除成功" };
      const msgs = {
        hide:     "內容已停止公開，作者端仍可查看",
        takedown: "內容已全面下架，作者已收到通知",
        restore:  "內容已恢復公開",
        delete:   "內容已永久刪除，無法復原",
      };
      toast({ title: titles[action], message: msgs[action], icon: "check" });
      if (action === "delete") {
        onRemove?.(item.id);
        onClose();
      } else {
        const newStatus = { hide: "hidden", takedown: "takedown", restore: "published" }[action];
        onUpdate?.(item.id, newStatus);
        onClose();
      }
    } catch (e) {
      toast({ title: "操作失敗", message: String(e), icon: "x" });
    } finally {
      setActing(null);
      setConfirmDelete(false);
    }
  }

  return (
    <Drawer open={!!item} onClose={onClose} width={520}>
      <div style={{ padding: "18px 24px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 12 }}>
        <button onClick={onClose} style={{ padding: 4, color: "var(--ink-3)" }}><Icon name="x" size={18}/></button>
        <div style={{ fontSize: 13, color: "var(--ink-3)" }}>
          {isProduct ? "商品詳情" : isSolicit ? "徵稿詳情" : "動態詳情"}
        </div>
        <StatusBadge status={currentStatus}/>
        <div style={{ flex: 1 }}/>
        <a href={previewUrl} target="_blank" rel="noopener noreferrer" style={{ textDecoration: "none" }}>
          <Button variant="ghost" size="sm" icon="external">前台預覽</Button>
        </a>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: "22px 24px 120px" }}>
        {/* Product */}
        {isProduct && (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {item.image && (
              <div style={{ borderRadius: 10, overflow: "hidden", aspectRatio: "16/9", background: "#000" }}>
                <img src={item.image} style={{ width: "100%", height: "100%", objectFit: "cover" }}
                  onError={e => { e.target.style.display = "none"; }}/>
              </div>
            )}
            <div>
              <div style={{ fontSize: 21, fontWeight: 600 }}>{item.name}</div>
              <div style={{ marginTop: 8, display: "flex", gap: 8, flexWrap: "wrap" }}>
                <Badge tone={item.type === "auction" ? "accent" : "info"} size="sm">
                  {item.type === "auction" ? "繪圖" : "文集"}
                </Badge>
                {(item.tags ?? []).map(t => <Badge key={t} tone="default" size="sm">{t}</Badge>)}
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              {[
                { label: "創作者", value: item.artistName },
                { label: "價格", value: item.price ? `NT$ ${fmtNum(item.price)}` : item.priceLabel || "—" },
                { label: "售出", value: `${item.salesCount} 件` },
                { label: "庫存", value: `${item.stock} 件` },
                { label: "建立時間", value: item.createdAt },
              ].map(m => (
                <div key={m.label}>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{m.label}</div>
                  <div style={{ fontSize: 14, fontWeight: 500, marginTop: 2 }}>{m.value}</div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Solicit */}
        {isSolicit && (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div>
              <div style={{ fontSize: 21, fontWeight: 600 }}>{item.title}</div>
              <div style={{ marginTop: 8, display: "flex", gap: 8, flexWrap: "wrap" }}>
                {(item.tags ?? []).map(t => <Badge key={t} tone="default" size="sm">{t}</Badge>)}
              </div>
            </div>
            {item.description && (
              <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.65, whiteSpace: "pre-wrap", padding: "12px 14px", background: "var(--surface-2)", borderRadius: 8 }}>
                {item.description}
              </div>
            )}
            {(item.images ?? []).length > 0 && (
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {item.images.map((src, i) => (
                  <div key={i} style={{ width: 80, height: 80, borderRadius: 8, overflow: "hidden", background: "var(--surface-2)" }}>
                    <img src={src} style={{ width: "100%", height: "100%", objectFit: "cover" }} onError={e => { e.target.style.display = "none"; }}/>
                  </div>
                ))}
              </div>
            )}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              {[
                { label: "委託人", value: item.authorName },
                { label: "預算", value: item.budget ? `NT$ ${fmtNum(item.budget)}` : "—" },
                { label: "截止日", value: item.deadline || "—" },
                { label: "發布時間", value: item.createdAt },
              ].map(m => (
                <div key={m.label}>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{m.label}</div>
                  <div style={{ fontSize: 14, fontWeight: 500, marginTop: 2 }}>{m.value}</div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Post */}
        {isPost && (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              {item.authorAvatar && !item.authorAvatar.includes("avatar-default")
                ? <img src={item.authorAvatar} style={{ width: 36, height: 36, borderRadius: "50%", objectFit: "cover" }}/>
                : <Avatar hue={200} glyph={item.authorName?.[0] ?? "?"} size={36}/>}
              <div>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{item.authorName}</div>
                <div className="mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{item.createdAt}</div>
              </div>
            </div>
            {item.content && (
              <div style={{ fontSize: 14, lineHeight: 1.7, whiteSpace: "pre-wrap", color: "var(--ink-2)" }}>{item.content}</div>
            )}
            {(item.images ?? []).length > 0 && (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(120px, 1fr))", gap: 8 }}>
                {item.images.map((src, i) => (
                  <div key={i} style={{ borderRadius: 8, overflow: "hidden", aspectRatio: "1", background: "var(--surface-2)" }}>
                    <img src={src} style={{ width: "100%", height: "100%", objectFit: "cover" }} onError={e => { e.target.style.display = "none"; }}/>
                  </div>
                ))}
              </div>
            )}
            <div style={{ display: "flex", gap: 20, fontSize: 13, color: "var(--ink-3)" }}>
              <span><Icon name="heart" size={13} style={{ marginRight: 4, verticalAlign: -1 }}/>{fmtNum(item.likeCount)} 個讚</span>
              <span><Icon name="chat" size={13} style={{ marginRight: 4, verticalAlign: -1 }}/>{fmtNum(item.commentCount)} 則留言</span>
            </div>
            {(item.tags ?? []).length > 0 && (
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {item.tags.map(t => <Badge key={t} tone="default" size="sm">{t}</Badge>)}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Footer actions */}
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: 0,
        padding: "14px 24px 16px", borderTop: "1px solid var(--border)",
        background: "var(--surface)",
      }}>
        <div style={{ display: "flex", gap: 8 }}>
          {/* 復原：只在隱藏/下架時顯示 */}
          {!isActive && (
            <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 4 }}>
              <Button variant="secondary" icon="check" style={{ width: "100%", color: "var(--success)" }}
                disabled={!!acting} onClick={() => { setConfirmDelete(false); doAction("restore"); }}>
                {acting === "restore" ? "處理中…" : "復原"}
              </Button>
              <div style={{ fontSize: 10.5, color: "var(--ink-4)", textAlign: "center", lineHeight: 1.3 }}>
                恢復公開
              </div>
            </div>
          )}

          {/* 隱藏：只在公開時顯示 */}
          {isActive && (
            <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 4 }}>
              <Button variant="secondary" icon="eye-off" style={{ width: "100%" }}
                disabled={!!acting} onClick={() => { setConfirmDelete(false); doAction("hide"); }}>
                {acting === "hide" ? "處理中…" : "隱藏"}
              </Button>
              <div style={{ fontSize: 10.5, color: "var(--ink-4)", textAlign: "center", lineHeight: 1.3 }}>
                停止公開<br/>作者仍可見
              </div>
            </div>
          )}

          {/* 下架：只在公開時顯示 */}
          {isActive && (
            <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 4 }}>
              <Button variant="secondary" style={{ width: "100%", color: "var(--warn)" }}
                disabled={!!acting} onClick={() => { setConfirmDelete(false); doAction("takedown"); }}>
                <Icon name="ban" size={15} style={{ marginRight: 4 }}/>{acting === "takedown" ? "處理中…" : "下架"}
              </Button>
              <div style={{ fontSize: 10.5, color: "var(--ink-4)", textAlign: "center", lineHeight: 1.3 }}>
                全面下架<br/>通知作者
              </div>
            </div>
          )}

          {/* 刪除：永久，需二次確認，永遠顯示 */}
          <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 4 }}>
            {confirmDelete ? (
              <Button variant="danger" icon="trash" style={{ width: "100%" }}
                disabled={!!acting} onClick={() => doAction("delete")}>
                {acting === "delete" ? "處理中…" : "確認刪除？"}
              </Button>
            ) : (
              <Button variant="secondary" icon="trash" style={{ width: "100%", color: "var(--danger)" }}
                disabled={!!acting} onClick={() => setConfirmDelete(true)}>
                刪除
              </Button>
            )}
            <div style={{ fontSize: 10.5, color: confirmDelete ? "var(--danger)" : "var(--ink-4)", textAlign: "center", lineHeight: 1.3, fontWeight: confirmDelete ? 500 : 400 }}>
              {confirmDelete ? "⚠ 無法復原" : "永久刪除"}<br/>{confirmDelete ? "再按一次確認" : "無法復原"}
            </div>
          </div>
        </div>
      </div>
    </Drawer>
  );
};

// ── Main page ─────────────────────────────────────────────────────────────────

const ContentPage = () => {
  const [tab, setTab] = useState("products");
  const [selected, setSelected] = useState(null);
  const removeRef = React.useRef(null);
  const updateRef = React.useRef(null);
  const exportRef = React.useRef(null);
  const refreshRef = React.useRef(null);

  function handleRemove(id) {
    removeRef.current?.(id);
    setSelected(null);
  }

  function handleUpdate(id, status) {
    updateRef.current?.(id, status);
    setSelected(prev => prev?.id === id ? { ...prev, status } : prev);
  }

  return (
    <div className="fade-in">
      <PageHeader
        title="內容管理"
        subtitle="瀏覽及管理平台上的商品刊登、徵稿、動態與熱門"
        actions={<>
          <Button variant="secondary" icon="refresh" onClick={() => refreshRef.current?.()}>重新整理</Button>
          <Button variant="secondary" icon="download" onClick={() => exportRef.current?.()}>匯出</Button>
        </>}
      />

      <div style={{ marginBottom: 16 }}>
        <Tabs
          active={tab}
          onChange={t => { setTab(t); setSelected(null); }}
          tabs={[
            { value: "products", label: "商品刊登" },
            { value: "solicits", label: "徵稿" },
            { value: "posts",    label: "動態" },
            { value: "hot",      label: "熱門" },
          ]}
        />
      </div>

      {tab === "products" && <ProductsTab onSelect={setSelected} onRemoveRef={removeRef} onUpdateRef={updateRef} exportRef={exportRef} refreshRef={refreshRef}/>}
      {tab === "solicits" && <SolicitTab  onSelect={setSelected} onRemoveRef={removeRef} onUpdateRef={updateRef} exportRef={exportRef} refreshRef={refreshRef}/>}
      {tab === "posts"    && <PostsTab    onSelect={setSelected} onRemoveRef={removeRef} onUpdateRef={updateRef} exportRef={exportRef} refreshRef={refreshRef}/>}
      {tab === "hot"      && <HotTab      onSelect={setSelected} onRemoveRef={removeRef} onUpdateRef={updateRef} exportRef={exportRef} refreshRef={refreshRef}/>}

      <ContentDetailDrawer
        item={selected}
        tabType={tab}
        onClose={() => setSelected(null)}
        onRemove={handleRemove}
        onUpdate={handleUpdate}
      />
    </div>
  );
};

window.ContentPage = ContentPage;
