"use client";
import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { ResponsiveModal } from "@/components/ui/responsive-modal";
import { Plus, X, Trash2, GripVertical, ChevronDown, Check, ChevronsUpDown, Image as ImageIcon } from "lucide-react";
import { createCategory } from "@/app/actions/category";
import { createBrand } from "@/app/actions/brand";
import { toast } from "sonner";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { Checkbox } from "@/components/ui/checkbox";
import MediaManager from "@/components/media/media-manager";

// ────────────── Inline Category Creator ──────────────
export function InlineCategorySelect({
  categories, value, onChange,
}: { categories: any[]; value: string[]; onChange: (v: string[]) => void }) {
  const [all, setAll] = useState(categories);
  const [open, setOpen] = useState(false);
  const [newName, setNewName] = useState("");

  const toggle = (id: string) =>
    onChange(value.includes(id) ? value.filter((x) => x !== id) : [...value, id]);

  const handleCreate = async () => {
    if (!newName.trim()) return;
    const res = await createCategory({ name: newName.trim(), slug: "", description: "", parentId: null });
    if (res.success && res.category) {
      setAll((p) => [...p, res.category!]);
      toggle(res.category!.id);
      toast.success("دسته‌بندی ایجاد شد");
      setNewName("");
    }
  };

  // Build tree
  const buildTree = (parentId: string | null = null): any[] => {
    return all
      .filter((c) => c.parentId === parentId)
      .map((c) => ({ ...c, children: buildTree(c.id) }));
  };
  const tree = buildTree(null);

  const renderNode = (node: any, depth = 0) => (
    <div key={node.id} className="space-y-1">
      <label className="flex items-center gap-2 p-1.5 rounded hover:bg-muted cursor-pointer text-sm" style={{ paddingRight: `${depth * 16}px` }}>
        <Checkbox checked={value.includes(node.id)} onCheckedChange={() => toggle(node.id)} />
        <span>{node.name}</span>
      </label>
      {node.children && node.children.length > 0 && (
        <div className="space-y-1">
          {node.children.map((child: any) => renderNode(child, depth + 1))}
        </div>
      )}
    </div>
  );

  return (
    <div className="space-y-2">
      <div className="flex flex-wrap gap-2 border rounded-xl p-3 min-h-[44px] bg-muted/10">
        {value.length === 0 && <span className="text-xs text-muted-foreground">دسته‌بندی انتخاب نشده</span>}
        {value.map((id) => {
          const cat = all.find((c) => c.id === id);
          return cat ? (
            <Badge key={id} variant="secondary" className="gap-1">
              {cat.name}
              <button type="button" onClick={() => toggle(id)}><X className="w-3 h-3" /></button>
            </Badge>
          ) : null;
        })}
        <button type="button" onClick={() => setOpen(true)}
          className="text-xs text-indigo-600 hover:underline flex items-center gap-1">
          <Plus className="w-3 h-3" /> انتخاب / ایجاد
        </button>
      </div>
      <ResponsiveModal open={open} onOpenChange={setOpen} title="دسته‌بندی‌ها">
        <div className="p-4 space-y-3">
          <div className="flex gap-2">
            <Input placeholder="نام دسته جدید (اصلی)..." value={newName} onChange={(e) => setNewName(e.target.value)} />
            <Button type="button" size="sm" onClick={handleCreate}>ایجاد</Button>
          </div>
          <div className="max-h-64 overflow-y-auto space-y-1 border rounded-md p-2">
            {tree.map(node => renderNode(node, 0))}
            {all.length === 0 && <div className="text-center text-sm text-muted-foreground py-4">دسته‌بندی وجود ندارد.</div>}
          </div>
          <Button className="w-full" onClick={() => setOpen(false)}>تأیید</Button>
        </div>
      </ResponsiveModal>
    </div>
  );
}

// ────────────── Inline Brand Select ──────────────
export function InlineBrandSelect({
  brands, countries, value, onChange,
}: { brands: any[]; countries: any[]; value: string; onChange: (v: string, brand?: any) => void }) {
  const [all, setAll] = useState(brands);
  const [showCreate, setShowCreate] = useState(false);
  const [popoverOpen, setPopoverOpen] = useState(false);
  const [isMediaOpen, setIsMediaOpen] = useState(false);
  
  const [form, setForm] = useState({ name: "", description: "", slug: "", countryId: "", websiteUrl: "", mediaId: "", mediaUrl: "" });

  const handleCreate = async () => {
    if (!form.name.trim()) return toast.error("نام برند الزامی است.");
    const res = await createBrand(form);
    if (res.success && res.brand) {
      setAll((p) => [...p, res.brand!]);
      onChange(res.brand!.id, res.brand);
      toast.success("برند ایجاد شد");
      setForm({ name: "", description: "", slug: "", countryId: "", websiteUrl: "", mediaId: "", mediaUrl: "" });
      setShowCreate(false);
    } else {
      toast.error(res.error);
    }
  };

  return (
    <div className="space-y-2">
      <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
        <PopoverTrigger asChild>
          <Button variant="outline" role="combobox" aria-expanded={popoverOpen} className={cn("w-full justify-between font-normal", !value && "text-muted-foreground")}>
            {value ? (
              <div className="flex items-center gap-2">
                {all.find(b => b.id === value)?.logoMedia?.url && (
                  <img src={all.find(b => b.id === value)?.logoMedia.url} className="w-5 h-5 object-contain rounded-sm" />
                )}
                <span>{all.find(b => b.id === value)?.name}</span>
              </div>
            ) : "انتخاب برند..."}
            <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-[300px] p-0" dir="rtl">
          <Command>
            <CommandInput placeholder="جستجوی برند..." />
            <CommandList>
              <CommandEmpty>برندی یافت نشد.</CommandEmpty>
              <CommandGroup>
                <CommandItem value="none" onSelect={() => {
                  onChange("", null as any);
                  setPopoverOpen(false);
                }}>
                  <div className="flex items-center gap-2 mr-2 text-muted-foreground">بدون برند</div>
                </CommandItem>
                {all.map((b) => (
                  <CommandItem key={b.id} value={b.name} onSelect={() => {
                    onChange(b.id, b);
                    setPopoverOpen(false);
                  }}>
                    <Check className={cn("mr-2 h-4 w-4 shrink-0", value === b.id ? "opacity-100" : "opacity-0")} />
                    <div className="flex items-center gap-2 mr-2">
                      {b.logoMedia?.url && <img src={b.logoMedia.url} className="w-5 h-5 object-contain rounded-sm" />}
                      <span>{b.name}</span>
                    </div>
                  </CommandItem>
                ))}
              </CommandGroup>
            </CommandList>
          </Command>
        </PopoverContent>
      </Popover>
      <button type="button" onClick={() => setShowCreate(true)}
        className="text-xs text-indigo-600 hover:underline flex items-center gap-1">
        <Plus className="w-3 h-3" /> ایجاد برند جدید
      </button>

      <ResponsiveModal open={showCreate} onOpenChange={setShowCreate} title="برند جدید">
        <div className="p-4 space-y-4 max-h-[80vh] overflow-y-auto">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1 space-y-2">
              <Label>نام برند *</Label>
              <Input value={form.name} onChange={e => setForm(p => ({ ...p, name: e.target.value }))} placeholder="مثال: سامسونگ" required />
            </div>
            <div className="flex-1 space-y-2">
              <Label>لینک سایت اصلی</Label>
              <Input dir="ltr" className="text-left font-sans" value={form.websiteUrl} onChange={e => setForm(p => ({ ...p, websiteUrl: e.target.value }))} placeholder="https://samsung.com" />
            </div>
          </div>

          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1 space-y-2">
              <Label>کشور سازنده</Label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button variant="outline" role="combobox" className={cn("w-full justify-between", !form.countryId && "text-muted-foreground")}>
                    {form.countryId ? (
                      <div className="flex items-center gap-2">
                        {countries.find(c => c.id === form.countryId)?.media && (
                          <img src={countries.find(c => c.id === form.countryId)?.media?.url} alt="" className="w-5 h-4 object-cover rounded-sm" />
                        )}
                        <span>{countries.find(c => c.id === form.countryId)?.name}</span>
                      </div>
                    ) : "انتخاب کشور سازنده..."}
                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[300px] p-0" dir="rtl">
                  <Command>
                    <CommandInput placeholder="جستجوی کشور..." />
                    <CommandList>
                      <CommandEmpty>کشوری یافت نشد.</CommandEmpty>
                      <CommandGroup>
                        {countries.map(c => (
                          <CommandItem key={c.id} value={c.name} onSelect={() => setForm(p => ({ ...p, countryId: c.id }))}>
                            <Check className={cn("mr-2 h-4 w-4", form.countryId === c.id ? "opacity-100" : "opacity-0")} />
                            <div className="flex items-center gap-2 mr-2">
                               {c.media && <img src={c.media.url} alt="" className="w-5 h-4 object-cover rounded-sm" />}
                               <span>{c.name}</span>
                            </div>
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </CommandList>
                  </Command>
                </PopoverContent>
              </Popover>
            </div>
          </div>

          <div className="space-y-2">
            <Label>تصویر برند</Label>
            <div className="flex items-center gap-3">
              <MediaManager 
                mode="single" 
                title="انتخاب تصویر برند" 
                value={form.mediaUrl ? { url: form.mediaUrl, id: form.mediaId } : null}
                open={isMediaOpen}
                onOpenChange={setIsMediaOpen}
                trigger={<Button type="button" variant="outline" className="flex-1 justify-start text-muted-foreground"><ImageIcon className="w-4 h-4 ml-2" /> انتخاب تصویر از رسانه...</Button>}
                onChange={(m: any) => { setForm(p => ({ ...p, mediaId: m?.id || "", mediaUrl: m?.url || "" })); setIsMediaOpen(false); }}
              />
              {form.mediaUrl && <img src={form.mediaUrl} alt="brand" className="w-10 h-10 object-contain rounded border bg-white" />}
            </div>
          </div>

          <div className="flex gap-2 pt-4 border-t">
            <Button type="button" onClick={handleCreate} className="flex-1">ایجاد برند</Button>
            <Button type="button" variant="ghost" onClick={() => setShowCreate(false)}>لغو</Button>
          </div>
        </div>
      </ResponsiveModal>
    </div>
  );
}

// ────────────── Variant Manager ──────────────
export interface Variant {
  id: string;
  title: string;
  price: number;
  salePrice?: number;
  sku: string;
  stock: number;
  imageUrl?: string;
  attributes: Record<string, string>;
}

export interface AttributeValueObj { name: string; imageUrl?: string; }
interface AttributeGroup { name: string; values: AttributeValueObj[] }

export function VariantManager({
  variants, onChange, attributeGroups, onGroupsChange, globalAttributes = [],
}: {
  variants: Variant[];
  onChange: (v: Variant[]) => void;
  attributeGroups: AttributeGroup[];
  onGroupsChange: (g: AttributeGroup[]) => void;
  globalAttributes?: any[];
}) {
  const [newGroupName, setNewGroupName] = useState("");
  const [newValues, setNewValues] = useState<Record<number, string>>({});

  const addGroup = () => {
    if (!newGroupName.trim()) return;
    onGroupsChange([...attributeGroups, { name: newGroupName.trim(), values: [] }]);
    setNewGroupName("");
  };

  const addValue = (gi: number) => {
    const val = newValues[gi]?.trim();
    if (!val) return;
    const groups = [...attributeGroups];
    groups[gi] = { ...groups[gi], values: [...groups[gi].values, { name: val }] };
    onGroupsChange(groups);
    setNewValues((p) => ({ ...p, [gi]: "" }));
  };

  const updateValueImage = (gi: number, vi: number, url: string) => {
    const groups = [...attributeGroups];
    groups[gi] = {
      ...groups[gi],
      values: groups[gi].values.map((v, i) => i === vi ? { ...v, imageUrl: url } : v)
    };
    onGroupsChange(groups);
  };

  const removeGroup = (gi: number) => {
    onGroupsChange(attributeGroups.filter((_, i) => i !== gi));
  };

  const removeValue = (gi: number, vi: number) => {
    const groups = [...attributeGroups];
    groups[gi] = { ...groups[gi], values: groups[gi].values.filter((_, i) => i !== vi) };
    onGroupsChange(groups);
  };

  const generateVariants = () => {
    if (!attributeGroups.length) return;
    const combos = attributeGroups.reduce<Record<string, string>[]>((acc, group) => {
      if (!group.values.length) return acc;
      if (!acc.length) return group.values.map((v) => ({ [group.name]: v.name }));
      return acc.flatMap((combo) => group.values.map((v) => ({ ...combo, [group.name]: v.name })));
    }, []);
    const generated: Variant[] = combos.map((attrs, i) => {
      let imageUrl: string | undefined = undefined;
      // Find if any attribute value has an image
      for (const groupName of Object.keys(attrs)) {
          const valName = attrs[groupName];
          const group = attributeGroups.find(g => g.name === groupName);
          const valObj = group?.values.find(v => v.name === valName);
          if (valObj?.imageUrl) {
              imageUrl = valObj.imageUrl;
              break; // use the first found image
          }
      }
      return {
          id: `var-${Date.now()}-${i}`,
          title: Object.values(attrs).join(" / "),
          price: 0,
          sku: "",
          stock: 0,
          imageUrl,
          attributes: attrs,
      };
    });
    onChange(generated);
    toast.success(`${generated.length} واریانت ایجاد شد`);
  };

  const updateVariant = (id: string, key: keyof Variant, val: any) => {
    onChange(variants.map((v) => v.id === id ? { ...v, [key]: val } : v));
  };

  const removeVariant = (id: string) => onChange(variants.filter((v) => v.id !== id));

  return (
    <div className="space-y-5">
      {/* Attribute Groups */}
      <div className="space-y-3">
        <Label className="font-bold text-sm">ویژگی‌های واریانت‌ساز</Label>
        {attributeGroups.map((group, gi) => (
          <div key={gi} className="border rounded-xl p-4 space-y-2 bg-muted/10">
            <div className="flex items-center justify-between">
              <span className="font-semibold text-sm">{group.name}</span>
              <Button type="button" variant="ghost" size="icon" className="h-7 w-7 text-rose-500" onClick={() => removeGroup(gi)}>
                <Trash2 className="w-3.5 h-3.5" />
              </Button>
            </div>
            <div className="flex flex-wrap gap-2">
              {group.values.map((val, vi) => (
                <div key={vi} className="flex flex-col gap-1 items-center bg-background border rounded-lg p-1.5 min-w-[80px]">
                  <div className="flex items-center gap-1 w-full justify-between">
                    <span className="text-sm font-semibold px-1">{val.name}</span>
                    <button type="button" className="text-rose-500 hover:bg-rose-50 rounded" onClick={() => removeValue(gi, vi)}><X className="w-3 h-3" /></button>
                  </div>
                  <MediaManager
                      mode="single"
                      value={val.imageUrl ? { id: "", url: val.imageUrl } as any : null}
                      onChange={(m) => updateValueImage(gi, vi, m ? (m as any).url : "")}
                      triggerLabel={val.imageUrl ? "تغییر عکس" : "انتخاب عکس"}
                      triggerClassName="w-full h-7 text-[10px] px-1"
                  />
                  {val.imageUrl && <img src={val.imageUrl} className="w-8 h-8 object-cover rounded mt-1 border" />}
                </div>
              ))}
              <div className="flex flex-col gap-2 mt-2 pt-2 border-t border-dashed border-border/50 w-full">
                {globalAttributes?.find(a => a.name === group.name)?.values && globalAttributes.find(a => a.name === group.name)!.values.length > 0 && (
                  <div className="flex flex-wrap gap-1.5 mb-1">
                    {globalAttributes.find(a => a.name === group.name)!.values.map((v: any) => (
                      <button 
                        key={v.id} 
                        type="button" 
                        onClick={() => {
                          if (!group.values.some(existing => existing.name === v.value)) {
                            const newGroups = [...attributeGroups];
                            newGroups[gi].values.push({ name: v.value });
                            onGroupsChange(newGroups);
                          }
                        }}
                        disabled={group.values.some(existing => existing.name === v.value)}
                        className="text-xs px-2 py-1 bg-muted/50 hover:bg-muted rounded border border-border/50 disabled:opacity-50 transition-colors"
                      >
                        + {v.value}
                      </button>
                    ))}
                  </div>
                )}
                <div className="flex gap-1 items-start">
                  <Input
                    className="h-8 w-40 text-xs"
                    placeholder="مقدار جدید..."
                    value={newValues[gi] || ""}
                    onChange={(e) => setNewValues((p) => ({ ...p, [gi]: e.target.value }))}
                    onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addValue(gi))}
                  />
                  <Button type="button" size="icon" className="h-8 w-8" onClick={() => addValue(gi)}>
                    <Plus className="w-3 h-3" />
                  </Button>
                </div>
              </div>
            </div>
          </div>
        ))}
          <div className="flex flex-wrap gap-2 mb-2 w-full">
            {globalAttributes?.filter(a => a.isVariantable).map((a) => (
              <Button 
                key={a.id} 
                type="button" 
                variant="outline" 
                size="sm" 
                onClick={() => onGroupsChange([...attributeGroups, { name: a.name, values: [] }])}
                disabled={attributeGroups.some(g => g.name === a.name)}
                className="gap-1 border-dashed"
              >
                <Plus className="w-3.5 h-3.5" /> {a.name}
              </Button>
            ))}
          </div>
          <div className="flex w-full max-w-sm gap-2">
            <Input
              placeholder="یا ویژگی جدید بنویسید..."
              value={newGroupName}
              onChange={(e) => setNewGroupName(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addGroup())}
              className="flex-1"
            />
            <Button type="button" variant="outline" onClick={addGroup} className="shrink-0 gap-1 border-dashed">
              <Plus className="w-4 h-4" /> افزودن
            </Button>
          </div>
        {attributeGroups.length > 0 && (
          <Button type="button" className="w-full bg-indigo-600 hover:bg-indigo-700" onClick={generateVariants}>
            ایجاد خودکار واریانت‌ها از ویژگی‌ها
          </Button>
        )}
      </div>

      {/* Variants List */}
      {variants.length > 0 && (
        <div className="space-y-3">
          <Label className="font-bold text-sm">واریانت‌ها ({variants.length})</Label>
          <div className="space-y-2 max-h-[500px] overflow-y-auto pr-1">
            {variants.map((variant) => (
              <div key={variant.id} className="border rounded-xl p-4 space-y-3 bg-card">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <GripVertical className="w-4 h-4 text-muted-foreground" />
                    <span className="font-semibold text-sm">{variant.title}</span>
                    {Object.entries(variant.attributes || {}).map(([k, v]) => (
                      <Badge key={k} variant="secondary" className="text-xs">{k}: {v as string}</Badge>
                    ))}
                  </div>
                  <Button type="button" variant="ghost" size="icon" className="h-7 w-7 text-rose-500" onClick={() => removeVariant(variant.id)}>
                    <Trash2 className="w-3.5 h-3.5" />
                  </Button>
                </div>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                  <div className="space-y-1">
                    <Label className="text-xs">قیمت (تومان)</Label>
                    <Input type="number" dir="ltr" className="h-8 text-sm font-sans"
                      value={variant.price || ""} onChange={(e) => updateVariant(variant.id, "price", parseInt(e.target.value) || 0)} />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs">قیمت با تخفیف</Label>
                    <Input type="number" dir="ltr" className="h-8 text-sm font-sans"
                      value={variant.salePrice || ""} onChange={(e) => updateVariant(variant.id, "salePrice", parseInt(e.target.value) || undefined)} />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs">SKU</Label>
                    <Input dir="ltr" className="h-8 text-sm font-sans"
                      value={variant.sku} onChange={(e) => updateVariant(variant.id, "sku", e.target.value)} />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs">موجودی</Label>
                    <Input type="number" dir="ltr" className="h-8 text-sm font-sans"
                      value={variant.stock} onChange={(e) => updateVariant(variant.id, "stock", parseInt(e.target.value) || 0)} />
                  </div>
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">تصویر اختصاصی (اختیاری)</Label>
                  <MediaManager
                      mode="single"
                      value={variant.imageUrl ? { id: "", url: variant.imageUrl } as any : null}
                      onChange={(m) => updateVariant(variant.id, "imageUrl", m ? (m as any).url : "")}
                      triggerLabel={variant.imageUrl ? "تغییر تصویر" : "انتخاب تصویر"}
                      triggerClassName="w-full h-8 text-xs"
                  />
                  {variant.imageUrl && (
                      <img src={variant.imageUrl} className="mt-2 h-16 w-16 object-contain rounded border" />
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ────────────── Custom Attributes (مشخصات فنی) ──────────────
export interface CustomAttr { key: string; value: string }

export function CustomAttributesEditor({ attrs, onChange, globalAttributes = [] }: { attrs: CustomAttr[]; onChange: (v: CustomAttr[]) => void; globalAttributes?: any[] }) {
  const add = () => onChange([...attrs, { key: "", value: "" }]);
  const remove = (i: number) => onChange(attrs.filter((_, idx) => idx !== i));
  const update = (i: number, field: "key" | "value", val: string) =>
    onChange(attrs.map((a, idx) => idx === i ? { ...a, [field]: val } : a));

  return (
    <div className="space-y-3">
      {attrs.map((attr, i) => (
        <div key={i} className="flex gap-2 items-center">
          <Input placeholder="نام مشخصه (مثل: جنس بدنه)" value={attr.key} onChange={(e) => update(i, "key", e.target.value)} className="flex-1" />
          <Input placeholder="مقدار (مثل: فلزی)" value={attr.value} onChange={(e) => update(i, "value", e.target.value)} className="flex-1" />
          <Button type="button" variant="ghost" size="icon" className="h-9 w-9 text-rose-500 shrink-0" onClick={() => remove(i)}>
            <Trash2 className="w-4 h-4" />
          </Button>
        </div>
      ))}
      <div className="flex flex-wrap gap-2 mt-4 pt-4 border-t w-full">
         {globalAttributes?.filter(a => !a.isVariantable).map(a => (
           <Button 
             key={a.id}
             type="button" 
             variant="outline" 
             size="sm"
             onClick={() => onChange([...attrs, { key: a.name, value: "" }])}
             className="gap-1 border-dashed text-xs h-8"
           >
             <Plus className="w-3 h-3" /> {a.name}
           </Button>
         ))}
      </div>
      <div className="flex items-center gap-2 mt-2">
        <Button type="button" variant="outline" onClick={add} className="shrink-0 gap-2 border-dashed h-8 text-xs">
          <Plus className="w-3 h-3" /> افزودن مشخصه سفارشی
        </Button>
      </div>
    </div>
  );
}

// ────────────── SEO Preview ──────────────
export function SeoPreview({ title, description, slug }: { title: string; description: string; slug: string }) {
  const domain = "myshop.com";
  const displayTitle = title || "عنوان محصول";
  const displayDesc = description || "توضیحات متا برای این محصول در اینجا نمایش داده می‌شود...";
  const displaySlug = slug || "product-slug";

  return (
    <div className="border rounded-xl p-4 bg-white dark:bg-zinc-900 space-y-1 font-sans" dir="ltr">
      <p className="text-xs text-muted-foreground mb-2 font-bold text-right" dir="rtl">پیش‌نمایش در گوگل:</p>
      <div className="flex items-center gap-2 mb-1">
        <div className="w-5 h-5 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600" />
        <div>
          <p className="text-xs text-muted-foreground">{domain}</p>
          <p className="text-[10px] text-muted-foreground">› {displaySlug}</p>
        </div>
      </div>
      <h3 className="text-blue-600 dark:text-blue-400 text-lg font-normal hover:underline cursor-pointer leading-snug line-clamp-1">
        {displayTitle.slice(0, 60)}
      </h3>
      <p className="text-sm text-muted-foreground leading-relaxed line-clamp-2">{displayDesc.slice(0, 160)}</p>
      <div className="mt-2 pt-2 border-t flex gap-2 text-xs text-muted-foreground">
        <span className={displayTitle.length > 60 ? "text-rose-500" : "text-emerald-600"}>عنوان: {displayTitle.length}/60</span>
        <span className={displayDesc.length > 160 ? "text-rose-500" : "text-emerald-600"}>توضیحات: {displayDesc.length}/160</span>
      </div>
    </div>
  );
}
