import { useState } from "react";
import type { CSSProperties, FormEvent, KeyboardEvent } from "react";
import { ArrowLeft } from "lucide-react";
import type { Asset, Product, Project } from "../types";
import type { Page } from "./route-config";
import { Drawer } from "../components/overlays";
import "../product-create-page.css";

type ProductPayload = {
  title?: string;
  brand?: string;
  category?: string;
  target_audience?: string;
  description?: string;
  specs?: Record<string, unknown>;
  selling_points?: Array<{ title: string; detail: string; sort_order: number }>;
};

// 复刻 mock-media productFor:按商品名关键词映射商品图
function productCover(name: string): string {
  const t = name.replace(/\s+/g, "");
  if (/蓝牙|耳机|南卡/.test(t)) return "product-earbuds.png";
  if (/速食|牛肉面|泡面|面条/.test(t)) return "product-noodle.png";
  if (/防晒/.test(t)) return "product-sunscreen.png";
  if (/咖啡|冻干/.test(t)) return "product-coffee.png";
  if (/空气炸锅|小熊/.test(t)) return "product-air-fryer.png";
  if (/瑜伽裤|露露/.test(t)) return "product-yoga-pants.png";
  if (/收纳|北欧/.test(t)) return "product-storage.png";
  if (/面膜|补水|玻尿酸|透真/.test(t)) return "product-mask.png";
  return "";
}
const prodMock = (file: string): CSSProperties => ({ ["--mock-media-url"]: `url(/exact/assets/mock/${file})` } as CSSProperties);

export function ProductsPage({ products, navigate, openProduct, onCreate }: {
  products: Product[];
  navigate: (page: Page) => void;
  openProduct: (productId: string) => void;
  onCreate: (payload: ProductPayload) => Promise<unknown> | void;
}) {
  const [query, setQuery] = useState("");
  const [drawer, setDrawer] = useState(false);
  const [title, setTitle] = useState("");
  const [brand, setBrand] = useState("");
  const [point, setPoint] = useState("");

  const filtered = products.filter((product) => `${product.title} ${product.brand}`.toLowerCase().includes(query.toLowerCase()));

  function submit(event: FormEvent) {
    event.preventDefault();
    onCreate({
      title,
      brand,
      category: "电商商品",
      target_audience: "泛人群",
      description: point,
      selling_points: [{ title: point || "核心卖点", detail: point || "待补充", sort_order: 0 }]
    });
    setDrawer(false);
    setTitle("");
    setBrand("");
    setPoint("");
  }

  return (
    <section className="products-page">
      <div className="page-head">
        <div>
          <h1>商品库</h1>
          <div className="sub"><span className="mono">// <span id="sku-count">{products.length}</span> SKU</span> · 商品信息会作为脚本和资产生成的素材</div>
        </div>
        <div className="actions">
          <button className="btn btn-edit-toggle" type="button" id="edit-toggle-btn">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="m3 7 2 2 4-4" /><path d="m3 17 2 2 4-4" /><path d="M13 6h8" /><path d="M13 12h8" /><path d="M13 18h8" /></svg>
            <span className="btn-edit-label">管理商品</span>
          </button>
          <button className="btn btn-primary btn-create" type="button" id="open-new-product" onClick={() => setDrawer(true)}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22V12" /><path d="M16 17h6" /><path d="M19 14v6" /><path d="M21 10.5V8a2 2 0 0 0-1-1.7l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.7l7 4a2 2 0 0 0 2 0l1.7-1" /><path d="m3.3 7 8.7 5 8.7-5" /><path d="m7.5 4.3 9 5.1" /></svg>
            新建商品
          </button>
        </div>
      </div>

      <div className="products-main">
        <div className="toolbar">
          <div className="search-inline">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
            <input className="input" id="search-input" placeholder="搜索商品名称、品牌" value={query} onChange={(event) => setQuery(event.target.value)} />
          </div>
          <div className="chip-wrap" data-key="cat"><button className="chip" type="button"><span className="chip-label">商品分类</span> <svg className="caret" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 6l4 4 4-4" /></svg></button></div>
          <div className="chip-wrap" data-key="date"><button className="chip" type="button"><span className="chip-label">创建时间</span> <svg className="caret" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 6l4 4 4-4" /></svg></button></div>
        </div>

        <div className="result-meta" id="result-meta">
          <span>// 显示 <span className="count">{filtered.length}</span> / {products.length} 个商品</span>
        </div>

        <div className="product-grid-wrap">
          <div className="product-grid" id="product-grid">
            {filtered.map((product) => <ProductCard key={product.id} product={product} onOpen={() => openProduct(product.id)} />)}
          </div>
        </div>
      </div>

      <Drawer title="新建商品" open={drawer} close={() => setDrawer(false)}>
        <form onSubmit={submit}>
          <div className="field"><label className="field-label">商品名称<span className="req">*</span></label><input className="input" value={title} onChange={(event) => setTitle(event.target.value)} required /></div>
          <div className="field"><label className="field-label">品牌</label><input className="input" value={brand} onChange={(event) => setBrand(event.target.value)} /></div>
          <div className="field"><label className="field-label">核心卖点<span className="req">*</span></label><textarea className="textarea" value={point} onChange={(event) => setPoint(event.target.value)} /></div>
          <div className="drawer-actions"><button className="btn btn-ghost" type="button" onClick={() => setDrawer(false)}>取消</button><button className="btn btn-primary" type="submit">创建商品</button></div>
        </form>
      </Drawer>
    </section>
  );
}

export function ProductCard({ product, onOpen }: { product: Product; onOpen: () => void }) {
  const cover = productCover(product.title);
  const assetCount = product.images?.length || 0;
  return (
    <div className="product-card" data-cat={product.category} data-name={product.title} role="button" tabIndex={0} onClick={onOpen} onKeyDown={(event) => event.key === "Enter" && onOpen()}>
      <span className="card-check" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="3 8 7 12 13 4" /></svg></span>
      <button className="card-del-btn" type="button" title="删除商品" onClick={(event) => event.stopPropagation()}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18" /><path d="M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2" /><path d="M19 6l-1.5 14a2 2 0 01-2 1.8H8.5a2 2 0 01-2-1.8L5 6" /></svg></button>
      <div className={`placeholder product-thumb${cover ? " has-mock-media" : ""}`} style={cover ? prodMock(cover) : undefined}><span className="ph-frame">{product.title} · 1200×800</span></div>
      <div className="product-body">
        <div className="product-name">{product.title}</div>
        <div className="product-cat">{product.category || "未分类"}</div>
        <div className="product-date">{(product.created_at || "").slice(0, 10)} 创建</div>
      </div>
      <div className="product-footer">
        <span className="stat">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" /><circle cx="9" cy="10" r="2" /><path d="M21 17l-5-5-9 9" /></svg>
          素材 <b>{assetCount}</b>
        </span>
        <span className="sep">·</span>
        <span className="stat">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="6" width="14" height="12" rx="2" /><path d="M16 10l6-3v10l-6-3z" /></svg>
          视频 <b>0</b>
        </span>
      </div>
    </div>
  );
}

const PC_PHOTO_SLOTS = ["主图", "细节 02", "细节 03", "细节 04", "细节 05"];
const PC_CAT_OPTIONS = ["美妆个护", "服饰内衣", "食品饮料", "家居家电", "数码 3C", "个护清洁", "运动户外", "母婴亲子"];

export function ProductCreateUploadPage({ onCreate, onBack }: { onCreate: (payload: ProductPayload) => Promise<unknown> | void; onBack: () => void }) {
  const [title, setTitle] = useState("");
  const [category, setCategory] = useState("");
  const [price, setPrice] = useState("");
  const [audience, setAudience] = useState("");
  const [points, setPoints] = useState<string[]>([]);
  const [pointDraft, setPointDraft] = useState("");

  const ready = title.trim().length > 0 && category.length > 0;
  const missing: string[] = [];
  if (title.trim().length === 0) missing.push("商品名");
  if (category.length === 0) missing.push("品类");
  missing.push("≥1 张图");

  function addPoint(event: KeyboardEvent<HTMLInputElement>) {
    if (event.key !== "Enter") return;
    event.preventDefault();
    const value = pointDraft.trim();
    if (!value) return;
    setPoints((list) => [...list, value]);
    setPointDraft("");
  }
  function removePoint(index: number) {
    setPoints((list) => list.filter((_, position) => position !== index));
  }

  function submit(event: FormEvent) {
    event.preventDefault();
    if (!ready) return;
    onCreate({
      title,
      category,
      target_audience: audience,
      specs: { source: "product-create-upload", ...(price ? { price } : {}) },
      selling_points: points.map((item, index) => ({ title: item, detail: item, sort_order: index }))
    });
  }

  return (
    <section className="product-create-page">
      <div className="page-head">
        <div>
          <h1>新建商品</h1>
          <div className="sub"><span className="mono">// 上传原图 + 填写基本信息</span> · 保存后可在工作台逐步丰富素材</div>
        </div>
        <div className="actions">
          <button className="btn btn-ghost" type="button" onClick={onBack}><ArrowLeft size={14} />返回商品库</button>
        </div>
      </div>

      <form onSubmit={submit}>
        <div className="form-grid">

          {/* 左:商品原图 */}
          <div className="form-card">
            <div className="card-h">
              <h3>商品原图</h3>
              <span className="req-tag">必填</span>
            </div>
            <div className="card-sub">// 1-5 张 · 这是后续所有 AI 生成的源材料</div>
            <div className="photo-grid">
              <div className="photo-slot photo-slot-add" role="button" tabIndex={0} title="上传图片">
                <span className="plus">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14" /></svg>
                </span>
                <span>添加</span>
              </div>
              {PC_PHOTO_SLOTS.slice(1).map((label) => (
                <div className="photo-slot" key={label}><span className="slot-label">{label}</span></div>
              ))}
            </div>
            <div className="upload-tip">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9" /><path d="M12 8v4M12 16h.01" /></svg>
              <span>建议上传 <strong>正面 / 侧面 / 细节 / 包装</strong> 4 张,后续在工作台生成的<strong>白底三视图</strong>更准确。</span>
            </div>
          </div>

          {/* 右:基本信息 */}
          <div className="form-card">
            <div className="card-h">
              <h3>基本信息</h3>
              <span className="req-tag">必填</span>
            </div>
            <div className="field">
              <label className="field-label">商品名称<span className="req">*</span></label>
              <input className="input" value={title} onChange={(event) => setTitle(event.target.value)} placeholder="例: 透真玻尿酸补水面膜" required />
            </div>
            <div className="field">
              <label className="field-label">品类<span className="req">*</span></label>
              <select className="select" value={category} onChange={(event) => setCategory(event.target.value)} required>
                <option value="">— 选择品类 —</option>
                {PC_CAT_OPTIONS.map((option) => <option key={option}>{option}</option>)}
              </select>
            </div>
            <div className="field field-last">
              <label className="field-label">价格(元)</label>
              <input className="input" type="number" value={price} onChange={(event) => setPrice(event.target.value)} placeholder="选填 · 仅用于素材生成参考" />
            </div>
          </div>

        </div>

        {/* 卖点 & 人群 */}
        <div className="form-card form-card-wide">
          <div className="card-h">
            <h3>卖点 & 人群</h3>
            <span className="opt-tag">选填 · 推荐</span>
          </div>
          <div className="ai-tip">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3l1.8 4.2L18 9l-4.2 1.8L12 15l-1.8-4.2L6 9l4.2-1.8L12 3z" /></svg>
            <span>填上这两项,后续 AI 生脚本(<strong>痛点种草 / 剧情带货</strong> 等模板)质量明显更高 —— 系统会用卖点构造钩子,用人群定语气。现在不填也可以,做视频项目时仍可补。</span>
          </div>

          <div className="field">
            <label className="field-label">核心卖点</label>
            <div className="field-hint">3-5 条要点,回车添加</div>
            <ul className="bullet-list">
              {points.map((point, index) => (
                <li className="bl-item" key={index}>
                  <span className="num">{index + 1}</span>
                  <span className="bl-text">{point}</span>
                  <button className="bl-x" type="button" aria-label="删除" onClick={() => removePoint(index)}>
                    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M4 4l8 8M12 4l-8 8" /></svg>
                  </button>
                </li>
              ))}
              <li className="bl-add">
                <span className="num">+</span>
                <input className="bl-input" value={pointDraft} onChange={(event) => setPointDraft(event.target.value)} onKeyDown={addPoint} placeholder="例: 玻尿酸双效保湿,4 小时持久水润" />
              </li>
            </ul>
          </div>
          <div className="field field-last">
            <label className="field-label">目标人群</label>
            <input className="input" value={audience} onChange={(event) => setAudience(event.target.value)} placeholder="例: 22-32 岁女性、敏感肌、办公室通勤" />
          </div>
        </div>

        {/* 底部操作 */}
        <div className="form-foot">
          <span className="req-info">
            {ready
              ? <>// 必填检查:<span className="ok">已全部完成 ✓</span> · 可进入工作台</>
              : <>// 必填检查:<span className="miss">{missing.join(" / ")}</span> 未完成</>}
          </span>
          <div className="foot-actions">
            <button className="btn" type="button" onClick={onBack}>取消</button>
            <button className="btn btn-primary" type="submit" disabled={!ready}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12l5 5L20 6" /></svg>
              保存并进入工作台
            </button>
          </div>
        </div>
      </form>
    </section>
  );
}

// 商品详情页 · 从 public/exact/product-detail.html 忠实转写。
// 名称 / 品类 / 目标人群 / 卖点 来自 product;商品图网格 / AI 素材卡 / 视频项目卡
// 已接入真实数据(product.images + 团队 assets + 该商品 projects),保持设计稿像素布局。
const PD_ASSET_STATUS_LABEL: Record<"pass" | "fail" | "archive", string> = { pass: "通过", fail: "不通过", archive: "归档" };

const PD_CAT_OPTIONS = ["美妆个护 / 精华液", "美妆个护", "服饰内衣", "食品饮料", "家居家电", "数码 3C", "个护清洁", "运动户外", "母婴亲子"];

// 取一个 Asset 的预览图(优先主文件,其次首文件)
function pdAssetPreview(asset?: Asset): string {
  if (!asset) return "";
  return asset.files?.find((file) => file.is_primary)?.preview_url || asset.files?.[0]?.preview_url || "";
}
// AI 素材分类 → 中文类型标签(用于缩图左上角 type-pill)
const PD_ASSET_TYPE_LABEL: Record<string, string> = {
  product_image: "商品图", person: "模特上身图", scene: "平台套图", tri_view: "三视图", background: "背景图"
};
function pdAssetTypeLabel(asset: Asset): string {
  return PD_ASSET_TYPE_LABEL[asset.category] || PD_ASSET_TYPE_LABEL[asset.asset_type] || asset.category || "素材";
}
// 项目状态 → 分桶 / 友好标签 / pill 类(对齐 projects.tsx 语义,组件内自洽)
function pdProjBucket(project: Project) { return project.status === "completed" ? "done" : project.status === "failed" ? "fail" : "wip"; }
function pdProjStatusLabel(project: Project) {
  return ({ draft: "脚本待生成", scripting: "脚本生成中", asseting: "基础资产生成中", storyboarding: "故事板生成中", videoing: "视频片段生成中", exporting: "导出中", completed: "已完成", failed: "失败" } as Record<string, string>)[project.status] || "进行中";
}
function pdProjPillClass(project: Project) { return project.status === "completed" ? "ok" : project.status === "failed" ? "err" : "info"; }

export function ProductDetailPage({ product, projects, assets, navigate, onUpdate }: {
  product: Product;
  projects: Project[];
  assets: Asset[];
  navigate: (page: Page) => void;
  onUpdate: (payload: Partial<Product>) => Promise<unknown> | void;
}) {
  const [tab, setTab] = useState<"assets" | "videos">("assets");
  const [editing, setEditing] = useState(false);
  const [triOpen, setTriOpen] = useState(false);

  // 商品图网格 · 用 product.images 的 asset id 在团队 assets 里查到真图;再叠加 cover_asset(去重)
  const assetById = new Map(assets.map((asset) => [asset.id, asset]));
  const imageRefs = [...(product.images || [])].sort((a, b) => a.sort_order - b.sort_order);
  const imageIds = imageRefs.map((ref) => ref.asset);
  if (product.cover_asset && !imageIds.includes(product.cover_asset)) imageIds.unshift(product.cover_asset);
  const productImages = imageIds
    .map((id) => ({ id, url: pdAssetPreview(assetById.get(id)) }));

  // AI 生成素材 · 团队资产中筛与该商品相关的类别(模特/场景/三视图/商品图/背景),取真图;无则回退到全部图片资产
  const AI_CATS = new Set(["product_image", "person", "scene", "tri_view", "background"]);
  const aiSource = assets.filter((asset) => AI_CATS.has(asset.category) || AI_CATS.has(asset.asset_type));
  const imageAssets = (aiSource.length ? aiSource : assets.filter((asset) => asset.asset_type === "image"))
    .slice()
    .sort((a, b) => (b.created_at || "").localeCompare(a.created_at || ""));
  const assetCount = imageAssets.length;

  // 视频项目 · 用传入的该商品 projects 渲染真实项目名 / 状态 / 阶段
  const videoProjects = projects;

  // 真实字段 · 缺省时回退到设计稿镜像默认值(对齐 api-bridge setField 行为)
  const realName = product.title || "补水保湿精华液";
  const realCat = product.category || "美妆个护 / 精华液";
  const realTarget = product.target_audience || "22-32 岁女性、敏感肌、办公室通勤";
  const realBullets = product.selling_points.length
    ? product.selling_points.map((point) => point.title)
    : ["透明质酸 + B5,敷完不黏不闷", "30g 大容量精华液", "0 香精 0 酒精,敏感肌可用"];

  const [name, setName] = useState(realName);
  const [cat, setCat] = useState(realCat);
  const [target, setTarget] = useState(realTarget);

  function save() {
    void onUpdate({ title: name, category: cat, target_audience: target });
    setEditing(false);
  }
  function cancel() {
    setName(realName);
    setCat(realCat);
    setTarget(realTarget);
    setEditing(false);
  }

  return (
    <section className="product-detail-page">

      {/* 顶部 标题 + 状态 */}
      <div className="pd-title">
        <h1 id="pd-name">{realName}</h1>
      </div>

      {/* 商品信息(含图片) + 快速操作 · 主辅两栏 */}
      <div className="pd-overview">

        <div className={`ov-card ov-main${editing ? " editing" : ""}`} id="ov-main-card">
          <div className="ov-h">
            <span className="ti">商品信息</span>
            {/* AI 生成三视图 · 按钮 + 弹出 panel(view 模式可见) */}
            <div className="ov-tri-wrap">
              <button className={`ov-edit ov-tri-trigger${triOpen ? " is-open" : ""}`} type="button" id="ov-tri-btn" title="AI 生成商品三视图" aria-haspopup="dialog" aria-expanded={triOpen} onClick={() => setTriOpen((value) => !value)}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3l1.8 4.2L18 9l-4.2 1.8L12 15l-1.8-4.2L6 9l4.2-1.8L12 3z" /><path d="M19 14l.9 2.1L22 17l-2.1.9L19 20l-.9-2.1L16 17l2.1-.9L19 14z" /></svg>
                AI 生成三视图
              </button>
              <div className={`ov-tri-pop${triOpen ? " show" : ""}`} id="ov-tri-pop" role="dialog" aria-label="AI 生成三视图">
                <button className="ov-tri-close" type="button" id="ov-tri-close" aria-label="关闭" onClick={() => setTriOpen(false)}>
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18M6 6l12 12" /></svg>
                </button>
                <div className="prod-preview-h">// 三视图预览 · <span id="ov-tri-status">待生成</span></div>
                <div className="placeholder prod-preview-img" id="ov-tri-img"><span className="ph-frame">// 尚未生成 · 点击下方按钮开始</span></div>
                <div className="prod-preview-foot" id="ov-tri-foot">
                  <button className="ov-edit primary" type="button" id="ov-tri-start" style={{ height: "28px" }}>
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3l1.8 4.2L18 9l-4.2 1.8L12 15l-1.8-4.2L6 9l4.2-1.8L12 3z" /></svg>
                    生成
                  </button>
                  <span style={{ flex: 1 }}></span>
                  <span className="mono" style={{ fontSize: "11px", color: "var(--black-alpha-56)" }}>~¥0.30 / 次</span>
                </div>
                <div className="prod-preview-history" id="ov-tri-history">
                  <div className="h-lbl">// 历史版本 · <span className="ct" id="ov-tri-history-count">0</span> 版</div>
                  <div className="h-row" id="ov-tri-history-row"></div>
                </div>
              </div>
            </div>
            {/* view 模式: 单个 [编辑信息] */}
            <button className="ov-edit ov-edit-single" type="button" id="ov-edit-btn" title="编辑商品信息" onClick={() => setEditing(true)}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20h9" /><path d="M16.5 3.5a2.12 2.12 0 013 3L7 19l-4 1 1-4L16.5 3.5z" /></svg>
              编辑信息
            </button>
            {/* edit 模式: [重置] [取消] [保存] */}
            <div className="ov-edit-group">
              <button className="ov-edit" type="button" id="ov-reset-btn" title="重置为修改前" onClick={cancel}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7" /><path d="M3 4v5h5" /></svg>
                重置
              </button>
              <button className="ov-edit" type="button" id="ov-cancel-btn" onClick={cancel}>取消</button>
              <button className="ov-edit primary" type="button" id="ov-save-btn" onClick={save}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12l5 5L20 6" /></svg>
                保存
              </button>
            </div>
          </div>

          <div className="ov-main-grid">

            <div className="ov-info">
              <div className="row" data-field="name">
                <div className="k">商品名称</div>
                <div className="v">
                  <span className="v-static">{realName}</span>
                  <input className="v-edit v-input" type="text" value={name} maxLength={100} onChange={(event) => setName(event.target.value)} />
                </div>
              </div>
              <div className="row" data-field="cat">
                <div className="k">品类</div>
                <div className="v">
                  <span className="v-static">{realCat}</span>
                  <select className="v-edit v-select" value={cat} onChange={(event) => setCat(event.target.value)}>
                    {PD_CAT_OPTIONS.map((option) => <option key={option}>{option}</option>)}
                  </select>
                </div>
              </div>
              <div className="row" data-field="target">
                <div className="k">目标人群</div>
                <div className="v">
                  <span className="v-static">{realTarget}</span>
                  <input className="v-edit v-input" type="text" value={target} onChange={(event) => setTarget(event.target.value)} />
                </div>
              </div>
              <div className="row" data-field="bullets">
                <div className="k">核心卖点</div>
                <div className="v">
                  <div className="v-static">
                    {realBullets.map((bullet, index) => <span className="bullet" key={index}>{bullet}</span>)}
                  </div>
                  <ul className="v-edit v-bullet-list" id="v-bullets-list">
                    {realBullets.map((bullet, index) => (
                      <li className="bl-item" key={index}><span className="num">{index + 1}</span><span className="bl-text">{bullet}</span></li>
                    ))}
                  </ul>
                </div>
              </div>
            </div>

            <div className="ov-images-sub">
              <div className="sub-h">
                <span className="ti">商品图片</span>
                <span className="ct">({productImages.length})</span>
              </div>
              <div className="grid" id="ov-images-grid">
                {productImages.map((image) => (
                  <div className="thumb placeholder" key={image.id}>
                    {image.url ? <img src={image.url} alt={realName} loading="lazy" /> : <span className="ph-frame">1:1</span>}
                  </div>
                ))}
                <div className="img-upload" id="ov-img-add" title="上传图片">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14" /></svg>
                </div>
              </div>
            </div>

          </div>
        </div>

        <div className="ov-card ov-actions">
          <div className="ov-h"><span className="ti">快速操作</span></div>
          <div className="qa-section">
            <div className="qa-section-h">// 图片生成</div>
            <div className="qa-row-3">
              <div className="qa-item" data-go="model-photo" role="button" tabIndex={0} onClick={() => navigate("modelPhoto")}>
                <span className="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4" /><path d="M4 21v-2a4 4 0 014-4h8a4 4 0 014 4v2" /></svg></span>
                模特上身图
              </div>
              <div className="qa-item" data-go="platform-cover" role="button" tabIndex={0} onClick={() => navigate("platformCover")}>
                <span className="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" /><path d="M3 9h18M9 3v18" /></svg></span>
                平台套图
              </div>
              <div className="qa-item" data-go="image-optimize" role="button" tabIndex={0} onClick={() => navigate("imageOptimize")}>
                <span className="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v18M3 12h18M5 5l14 14M5 19l14-14" /></svg></span>
                图片创作
              </div>
            </div>
          </div>
          <div className="qa-section">
            <div className="qa-section-h">// 视频生成</div>
            <div className="qa-row-1">
              <div className="qa-item primary" data-go="projects-new" role="button" tabIndex={0} onClick={() => navigate("projectWizard")}>
                <span className="ic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="6" width="14" height="12" rx="2" /><path d="M16 10l6-3v10l-6-3z" /></svg></span>
                生成视频
              </div>
            </div>
          </div>
        </div>

      </div>

      {/* Tabs */}
      <div className="pd-tabs">
        <button className={`tab${tab === "assets" ? " active" : ""}`} type="button" data-tab="assets" onClick={() => setTab("assets")}>AI 生成素材</button>
        <button className={`tab${tab === "videos" ? " active" : ""}`} type="button" data-tab="videos" onClick={() => setTab("videos")}>视频项目</button>
        <button className="tab" type="button" data-tab="tasks" hidden>任务记录</button>
      </div>

      {/* ===== AI 生成素材 ===== */}
      <div className={`tab-pane${tab === "assets" ? " active" : ""}`} data-pane="assets">

        <div className="pd-toolbar">
          <div className="total">全部 AI 素材 <span className="ct">({assetCount})</span></div>
          <button className="filter" type="button" data-key="type">
            全部类型
            <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 6l4 4 4-4" /></svg>
          </button>
          <button className="filter" type="button" data-key="status">
            通过
            <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 6l4 4 4-4" /></svg>
          </button>
          <div className="right">
            <div className="view-tog">
              <button type="button" className="active" title="网格视图">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="7" height="7" /><rect x="14" y="3" width="7" height="7" /><rect x="3" y="14" width="7" height="7" /><rect x="14" y="14" width="7" height="7" /></svg>
              </button>
              <button type="button" title="列表视图">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 6h18M3 12h18M3 18h18" /></svg>
              </button>
            </div>
            <button className="filter" type="button" data-key="sort">
              最新生成
              <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 6l4 4 4-4" /></svg>
            </button>
          </div>
        </div>

        <div className="asset-grid">
          {imageAssets.map((asset) => {
            const url = pdAssetPreview(asset);
            const status: "pass" | "fail" | "archive" = "pass";
            return (
              <div className="asset-card" key={asset.id}>
                <div className="thumb placeholder">
                  {url ? <img src={url} alt={asset.name} loading="lazy" /> : null}
                  <span className="type-pill">{pdAssetTypeLabel(asset)}</span>
                  {url ? null : <span className="ph-frame">3:4</span>}
                </div>
                <div className="meta"><span className={`pill ${status}`} data-status={status}>{PD_ASSET_STATUS_LABEL[status]}</span><span className="date">{(asset.created_at || "").slice(0, 10)}</span></div>
              </div>
            );
          })}
        </div>

        <div className="pd-more"><button type="button">加载更多</button></div>
      </div>

      {/* ===== 视频项目 ===== */}
      <div className={`tab-pane${tab === "videos" ? " active" : ""}`} data-pane="videos">
        <div className="pd-toolbar">
          <div className="total">该商品视频项目 <span className="ct">({videoProjects.length})</span></div>
          <div className="right">
            <button className="filter" type="button" data-key="sort">
              最新导出
              <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 6l4 4 4-4" /></svg>
            </button>
          </div>
        </div>

        <div className="asset-grid">
          {videoProjects.map((project) => (
            <div className="asset-card" data-proj-status={pdProjBucket(project)} key={project.id}>
              <div className="thumb placeholder" style={{ aspectRatio: "9/16" }}><span className="type-pill">视频 · 9:16</span><span className="ph-frame">{project.name}</span></div>
              <div className="meta"><span className={`pill ${pdProjPillClass(project)}`}><span className="dot"></span>{pdProjStatusLabel(project)}</span><span className="date">{(project.updated_at || "").slice(0, 10)}</span></div>
            </div>
          ))}
        </div>

        <div className="pd-more"><button type="button">加载更多</button></div>
      </div>

    </section>
  );
}
