import { useEffect, useMemo, useState } from "react";
import {
  ArrowLeft,
  ArrowRight,
  Bookmark,
  Check,
  ChevronDown,
  Download,
  Grid2X2,
  ImagePlus,
  LayoutGrid,
  List,
  MoreHorizontal,
  Plus,
  Quote,
  RefreshCw,
  Search,
  Sparkles,
  Trash2,
  WandSparkles,
  X
} from "lucide-react";
import type { AITask, Asset, ModelConfig, Product } from "../types";
import type { Page } from "./route-config";
import { statusPill } from "./stage-config";
import "../ai-tools-page.css";

const TASK_TYPE_LABEL: Record<string, string> = {
  model: "模特上身图",
  platform: "平台套图",
  image: "图片创作",
  model_photo: "模特上身图",
  platform_cover: "平台套图",
  image_optimize: "图片创作"
};

const STATUS_LABEL: Record<string, string> = {
  succeeded: "已完成",
  completed: "已完成",
  done: "已完成",
  ok: "已完成",
  skipped: "已跳过",
  failed: "失败",
  error: "失败",
  running: "生成中",
  queued: "排队中",
  polling: "生成中",
  needs_review: "待确认"
};

function statusText(status: string) {
  return STATUS_LABEL[status] || status;
}

export function AssetFactoryPage({ navigate, aiTasks }: { navigate: (page: Page) => void; aiTasks: AITask[] }) {
  const cards = [
    {
      page: "modelPhoto" as Page,
      tag: "[ MODEL · TRY-ON ]",
      title: "模特上身图",
      desc: "选择模特，AI 生成商品模特上身效果图",
      cost: "≈ ¥0.30 / 张"
    },
    {
      page: "platformCover" as Page,
      tag: "[ PLATFORM · KIT ]",
      title: "平台套图",
      desc: "选择平台模板，AI 生成电商平台套图",
      cost: "≈ ¥0.50 / 张"
    },
    {
      page: "imageOptimize" as Page,
      tag: "[ IMAGE · STUDIO ]",
      title: "图片创作",
      desc: "自由创作 AI 图片，适用于详情图 / 海报 / 灵感速写",
      cost: "≈ ¥0.40 / 组"
    }
  ];

  const counts = useMemo(() => {
    const acc = { gen: 0, ok: 0, err: 0 };
    for (const task of aiTasks) {
      const pill = statusPill(task.status);
      if (pill === "ok") acc.ok += 1;
      else if (pill === "err") acc.err += 1;
      else if (pill === "info") acc.gen += 1;
    }
    return acc;
  }, [aiTasks]);

  const visible = aiTasks.slice(0, 8);

  return (
    <div className="asset-factory">
      <div className="page-head">
        <div>
          <h1>图片生成</h1>
          <div className="sub">
            <span className="mono">// 一键生成</span>
            <span>·</span>
            <span>电商视觉素材，提升内容制作效率</span>
          </div>
        </div>
      </div>

      <div className="factory-hero">
        {cards.map((card) => (
          <article className="factory-card with-corners" key={card.title}>
            <span className="corner-tr" aria-hidden />
            <span className="corner-bl" aria-hidden />
            <div className="factory-body">
              <div className="factory-text">
                <span className="factory-tag">{card.tag}</span>
                <div className="factory-title">{card.title}</div>
                <div className="factory-desc">{card.desc}</div>
              </div>
              <div className="factory-cta">
                <button className="btn btn-primary btn-lg" type="button" onClick={() => navigate(card.page)}>
                  开始生成
                  <ArrowRight size={13} />
                </button>
                <span className="cost">[ {card.cost} ]</span>
              </div>
            </div>
          </article>
        ))}
      </div>

      <div className="section-h">
        <h2>任务中心</h2>
        <span className="sub-mono">
          // {aiTasks.length} 个 · {counts.gen} 生成中 · {counts.ok} 已完成 · {counts.err} 失败
        </span>
      </div>

      <div className="toolbar">
        <div className="search-inline">
          <Search size={14} />
          <input className="input" placeholder="搜索任务名" />
        </div>
        <span className="spacer" />
        <div className="view-toggle">
          <button type="button" className="active">
            <List size={13} />
            列表
          </button>
          <button type="button">
            <Grid2X2 size={13} />
            网格
          </button>
        </div>
      </div>

      <div className="result-meta">
        // 显示 {visible.length} / {aiTasks.length} 个任务
      </div>

      {aiTasks.length === 0 ? (
        <div className="task-empty">
          <div className="mono">// NO TASKS YET</div>
          <div>还没有任务，去上方选一个工序开始生成吧</div>
        </div>
      ) : (
        <div className="task-list-view">
          <table className="t">
            <thead>
              <tr>
                <th style={{ width: "42%" }}>任务</th>
                <th style={{ width: 160 }}>进度</th>
                <th>状态</th>
                <th style={{ width: 140 }}>任务 ID</th>
              </tr>
            </thead>
            <tbody>
              {visible.map((task) => {
                const pill = statusPill(task.status);
                const typeLabel = TASK_TYPE_LABEL[task.task_type] || task.task_type;
                return (
                  <tr key={task.id}>
                    <td>
                      <div className="task-name-cell">
                        <div className="placeholder task-thumb">
                          <span className="ph-frame">{task.id.slice(0, 4)}</span>
                        </div>
                        <div>
                          <div className="task-name">{typeLabel}</div>
                          <div className="task-sub">// {task.task_type}</div>
                        </div>
                      </div>
                    </td>
                    <td>
                      {pill === "info" ? (
                        <div className="task-list-prog">
                          <div className="bar">
                            <span style={{ width: "60%" }} />
                          </div>
                          <span className="pct">60%</span>
                        </div>
                      ) : (
                        <span className="muted-2 mono" style={{ fontSize: 11 }}>
                          {pill === "ok" ? "已完成" : "—"}
                        </span>
                      )}
                    </td>
                    <td>
                      <span className={`pill ${pill}`}>
                        <span className="dot" />
                        {statusText(task.status)}
                      </span>
                    </td>
                    <td className="muted-2">{task.id.slice(0, 8)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

type WorkMode = "image" | "model" | "cover";

const MODE_META: Record<
  WorkMode,
  {
    title: string;
    tag: string;
    desc: string;
    ratio: string;
    promptTemplate: (productTitle: string) => string;
  }
> = {
  image: {
    title: "图片创作",
    tag: "[ IMAGE · STUDIO ]",
    desc: "自由创作 AI 图片，适用于详情图 / 海报 / 灵感速写。",
    ratio: "1:1",
    promptTemplate: (title) => `${title}，电商高转化视觉，干净背景，商品主体清晰`
  },
  model: {
    title: "模特上身图",
    tag: "[ MODEL · TRY-ON ]",
    desc: "选择模特和商品，生成电商模特上身图。",
    ratio: "3:4",
    promptTemplate: (title) => `${title}，模特上身展示，自然光，真实质感，电商主图`
  },
  cover: {
    title: "平台套图",
    tag: "[ PLATFORM · KIT ]",
    desc: "选择平台模板，一键生成主图 / 封面 / 详情套图。",
    ratio: "4:5",
    promptTemplate: (title) => `${title}，电商平台套图，统一视觉，主图 + 详情排版`
  }
};

const RATIO_OPTIONS = ["1:1", "3:4", "4:5", "9:16", "16:9"];
const COUNT_OPTIONS = ["1", "2", "4"];
const MODEL_RATIO_OPTIONS = ["1:1", "3:4", "9:16"];
const MODEL_COUNT_OPTIONS = ["4", "8", "12"];
const COVER_COUNT_OPTIONS = ["4", "8", "12"];

/* 图片创作 · 空态提示词建议 chip(基线 image-optimize EXAMPLES) */
const IMAGE_SUGGESTIONS = [
  "一只穿着宇航服的橘猫，漂浮在霓虹色星云中，赛博朋克风",
  "极简北欧风格的茶杯，白底，自然柔光，产品摄影",
  "国风水墨海报，主体一只白鹤立于水边，留白构图",
  "电影感都市夜景，街道湿漉漉反射霓虹，4K 高清"
];

/* 图片创作 · 风格胶囊(基线 image-optimize STYLES) */
const STYLE_OPTIONS = [
  { id: "auto", label: "默认" },
  { id: "realistic", label: "写实" },
  { id: "cinematic", label: "电影感" },
  { id: "anime", label: "动漫" },
  { id: "oil", label: "油画" },
  { id: "cn-ink", label: "国风水墨" }
];

/* 模特上身图 · 真人模特默认占位卡(基线 model-photo Ava/Luna/Mia/Zoe) */
const FALLBACK_MODELS = [
  { id: "m1", name: "Ava", tag: "亚洲·25岁·清新" },
  { id: "m2", name: "Luna", tag: "亚洲·22岁·学生" },
  { id: "m3", name: "Mia", tag: "混血·28岁·OL" },
  { id: "m4", name: "Zoe", tag: "亚洲·30岁·健身" }
];

/* 平台套图 · 平台卡(基线 platform-cover · logo 配色用 token 化 className) */
const PLATFORM_OPTIONS = [
  { id: "dy", name: "抖音电商", logo: "抖" },
  { id: "tb", name: "淘宝", logo: "淘" },
  { id: "tm", name: "天猫", logo: "猫" },
  { id: "jd", name: "京东", logo: "京" },
  { id: "pdd", name: "拼多多", logo: "拼" },
  { id: "xhs", name: "小红书", logo: "红" },
  { id: "ks", name: "快手", logo: "快" },
  { id: "sph", name: "视频号", logo: "视" },
  { id: "amz", name: "亚马逊", logo: "a" },
  { id: "al", name: "1688", logo: "阿" }
];

export function ImageWorkbenchPage({
  mode,
  products,
  assets,
  modelConfigs,
  onBack,
  navigate,
  onGenerate
}: {
  mode: WorkMode;
  products: Product[];
  assets: Asset[];
  modelConfigs: ModelConfig[];
  onBack: () => void;
  navigate?: (page: Page) => void;
  onGenerate: (payload: { prompt: string; mode?: "image" | "model" | "cover"; count?: number }) => Promise<{ assets: Asset[] } | null>;
}) {
  const meta = MODE_META[mode];
  const [productId, setProductId] = useState(products[0]?.id || "");
  const product = products.find((item) => item.id === productId) || products[0];
  const [prompt, setPrompt] = useState(meta.promptTemplate(products[0]?.title || "商品"));
  const [ratio, setRatio] = useState(meta.ratio);
  const [style, setStyle] = useState("auto");
  const [count, setCount] = useState(mode === "image" ? "4" : "4");
  const [pickedIds, setPickedIds] = useState<string[]>([]);
  const [generating, setGenerating] = useState(false);
  const [results, setResults] = useState<Asset[] | null>(null);

  const imageModels = modelConfigs.filter((model) => model.capability.includes("image"));

  /* 模特卡数据来源:assets 中 category==='person' 的真资产(显真图 preview_url + name);
     无则回退到基线占位模特卡 Ava/Luna/Mia/Zoe */
  const personAssets = useMemo(() => assets.filter((item) => item.category === "person"), [assets]);

  useEffect(() => {
    if (product) setPrompt(meta.promptTemplate(product.title));
    // mode 或商品切换都重置 prompt 与默认比例
    setRatio(meta.ratio);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [productId, mode]);

  function togglePick(id: string) {
    setPickedIds((prev) => (prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]));
  }

  const ratioVar = ratio.replace(":", " / ");
  const candidateCount = Math.max(1, Number(count) || 4);
  const canGenerate = prompt.trim().length > 0 && !generating;

  async function runGenerate() {
    if (!canGenerate) return;
    setGenerating(true);
    try {
      const result = await onGenerate({ prompt: prompt.trim(), mode, count: candidateCount });
      // 成功:渲染真图;失败(null):保留原占位,不改 results
      if (result?.assets) setResults(result.assets);
    } finally {
      setGenerating(false);
    }
  }

  const hasResults = !!(results && results.length > 0);

  /* ── 共享:生成结果网格(§4.18 .gen-card · 三 mode 统一渲染真图)── */
  function renderResultGrid() {
    const cols = (results?.length ?? candidateCount) >= 4 ? 4 : 2;
    return (
      <div
        className="gen-images"
        style={{ "--cols": cols, "--ratio": ratioVar } as React.CSSProperties}
      >
        {(hasResults
          ? results!.map((asset, index) => ({ key: asset.id, index, url: asset.files?.[0]?.preview_url }))
          : Array.from({ length: candidateCount }).map((_, index) => ({ key: `ph-${index}`, index, url: undefined as string | undefined }))
        ).map(({ key, index, url }) => (
          <div className={`gen-image ${generating && !url ? "gen" : ""}`} key={key}>
            {url ? (
              <img className="gen-image-img" src={url} alt={`${meta.title} #${index + 1}`} loading="lazy" />
            ) : (
              <div className="placeholder">
                <span className="ph-frame">
                  {generating ? "生成中…" : `${ratio} · #${index + 1}`}
                </span>
              </div>
            )}
            <div className="gen-image-actions">
              <button className="gen-img-btn" type="button" title="重跑">
                <RefreshCw size={14} />
              </button>
              <button className="gen-img-btn" type="button" title="下载">
                <Download size={14} />
              </button>
              <button className="gen-img-btn" type="button" title="更多">
                <MoreHorizontal size={14} />
              </button>
            </div>
          </div>
        ))}
      </div>
    );
  }

  /* ════════════════════════════════════════════════
     mode === "image" → 对话流形态(基线 image-optimize · design.md §4.13)
     左会话列表 + 中央 hero/对话流 + 底部 chat 输入栏
     ════════════════════════════════════════════════ */
  if (mode === "image") {
    return (
      <div className="image-workbench iw-chat">
        {/* 左 · 会话列表 */}
        <aside className="ic-side">
          <div className="ic-side-h">
            <button className="back-pill" type="button" onClick={onBack}>
              <ArrowLeft size={14} />
              返回
            </button>
          </div>
          <button className="ic-new-conv" type="button">
            <Plus size={13} />
            新对话
          </button>
          <div className="ic-side-sec">默认</div>
          <div className="ic-conv-list">
            <div className="ic-conv-item active">
              <div className="thumb default">
                <ImagePlus size={13} />
              </div>
              <span className="nm">默认创作</span>
            </div>
          </div>
          <div className="ic-side-sec">最近</div>
          <div className="ic-conv-list">
            <div className="ic-conv-empty">
              还没有最近会话
              <br />
              <span className="mono">// NO HISTORY</span>
            </div>
          </div>
        </aside>

        {/* 右 · 对话流 + 底部输入栏 */}
        <section className="ic-main">
          <div className="ic-stream">
            {hasResults ? (
              <div className="ic-stream-inner">
                <div className="ic-msg">
                  <div className="ic-msg-prompt">
                    <span className="quote">
                      <Quote size={13} />
                    </span>
                    <div className="pt">
                      <div className="pt-text">{prompt}</div>
                      <div className="pt-tags">
                        <span className="meta-chip">{ratio}</span>
                        <span className="sep">·</span>
                        <span className="meta-chip">{count} 张</span>
                        <span className="sep">·</span>
                        <span className="meta-chip">{STYLE_OPTIONS.find((s) => s.id === style)?.label || "默认"}</span>
                      </div>
                    </div>
                  </div>
                  <div className="gen-card">{renderResultGrid()}</div>
                  <div className="gen-card-actions">
                    <button className="btn btn-sm" type="button">
                      <RefreshCw size={13} />
                      重新编辑
                    </button>
                    <button className="btn btn-sm" type="button">
                      <Check size={13} />
                      全部加入资产库
                    </button>
                    <button className="btn btn-sm btn-ghost" type="button" title="更多">
                      <MoreHorizontal size={13} />
                    </button>
                  </div>
                </div>
              </div>
            ) : (
              <div className="ic-empty">
                <div className="ic">
                  <Sparkles size={28} />
                </div>
                <div className="badge">// IMAGE · STUDIO</div>
                <h2>开始你的创作</h2>
                <p>输入想法、剧本或上传参考，和 Agent 一起把灵感变成电商视觉素材。</p>
                <div className="examples">
                  {IMAGE_SUGGESTIONS.map((text) => (
                    <button className="ex" type="button" key={text} onClick={() => setPrompt(text)}>
                      {text}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* 底部 · chat 输入栏(textarea + 比例/风格/张数 + 发送) */}
          <div className="ic-input-wrap">
            <div className="ic-input">
              <div className="ic-input-top">
                <button className="add-btn" type="button" title="上传参考图">
                  <Plus size={22} />
                </button>
              </div>
              <textarea
                className="ic-input-text"
                value={prompt}
                onChange={(event) => setPrompt(event.target.value)}
                placeholder="输入想法、剧本或上传参考，和 Agent 一起创作"
              />
              <div className="ic-input-bottom">
                <Pill
                  label="比例"
                  value={ratio}
                  options={RATIO_OPTIONS.map((value) => ({ id: value, label: value }))}
                  onSelect={setRatio}
                />
                <Pill
                  label="风格"
                  value={STYLE_OPTIONS.find((s) => s.id === style)?.label || "默认"}
                  options={STYLE_OPTIONS}
                  onSelect={setStyle}
                />
                <Pill
                  label="张数"
                  value={count}
                  options={COUNT_OPTIONS.map((value) => ({ id: value, label: value }))}
                  onSelect={setCount}
                />
                <span className="right-meta">
                  预估 <span className="val">¥{(candidateCount * 0.1).toFixed(2)}</span>
                </span>
                <button className="send-btn" type="button" onClick={runGenerate} disabled={!canGenerate} title="生成">
                  {generating ? <span className="spinner" aria-hidden /> : <ArrowRight size={15} />}
                </button>
              </div>
            </div>
          </div>
        </section>
      </div>
    );
  }

  /* ════════════════════════════════════════════════
     mode === "model" / "cover" → 商品列表栏 + 表单 + 预览
     (基线 model-photo / platform-cover)
     ════════════════════════════════════════════════ */
  const ratioOptions = mode === "model" ? MODEL_RATIO_OPTIONS : RATIO_OPTIONS;
  const countOptions = mode === "model" ? MODEL_COUNT_OPTIONS : COVER_COUNT_OPTIONS;

  return (
    <div className="image-workbench iw-prod">
      <div className="iw-layout">
        {/* 最左 · 商品空间 */}
        <aside className="iw-prod-space">
          <div className="iw-side-top">
            <button className="back-pill" type="button" onClick={onBack}>
              <ArrowLeft size={14} />
              返回
            </button>
          </div>
          <div className="iw-ps-search">
            <Search size={13} />
            <input placeholder="搜索商品 / 分类" />
          </div>
          <div className="iw-list-h">
            <span className="mono">// 商品空间</span>
          </div>
          <div className="iw-ps-list">
            {products.length === 0 ? (
              <div className="iw-ps-empty">
                还没有商品
                <br />
                // NO PRODUCTS
              </div>
            ) : (
              products.slice(0, 12).map((item) => (
                <button
                  className={`iw-prod-item ${productId === item.id ? "active" : ""}`}
                  type="button"
                  key={item.id}
                  onClick={() => setProductId(item.id)}
                >
                  <div className="placeholder thumb">
                    <span className="ph-frame">{item.title.slice(0, 2)}</span>
                  </div>
                  <div className="body">
                    <div className="nm">{item.title}</div>
                    <div className="sub">// {item.category || "未分类"}</div>
                  </div>
                </button>
              ))
            )}
          </div>
        </aside>

        {/* 主区 · 头部 + 参数/结果双栏 */}
        <section className="iw-main">
          <div className="iw-main-h">
            <div className="cur-title">
              <span className="crumb">// 商品空间</span>
              <span className={`nm ${product ? "" : "placeholder"}`}>
                {product?.title || "未选择 · 请在左侧商品空间选一个"}
              </span>
            </div>
            <span className="spacer" />
            <button className="search-btn" type="button" title="搜索">
              <Search size={14} />
            </button>
            {mode === "model" && navigate && (
              <button className="tb-chip" type="button" onClick={() => navigate("modelPhotoDemoA")}>
                方案 A
              </button>
            )}
          </div>

          <div className="iw-main-body">
            {/* 左 · 参数表单 */}
            <div className="iw-form">
              {mode === "model" ? (
                <div className="iw-step">
                  <div className="iw-step-h">
                    <span className="num">1</span>
                    <span className="title">选择模特</span>
                    <span className="right">全部模特 →</span>
                  </div>
                  <div className="model-grid">
                    {personAssets.length > 0
                      ? personAssets.slice(0, 6).map((item) => {
                          const url = item.files?.[0]?.preview_url;
                          return (
                            <button
                              type="button"
                              key={item.id}
                              className={`model-card ${pickedIds.includes(item.id) ? "selected" : ""}`}
                              onClick={() => togglePick(item.id)}
                            >
                              <span className="m-check">
                                <Check size={11} />
                              </span>
                              <div className="m-thumb">
                                {url ? (
                                  <img className="m-thumb-img" src={url} alt={item.name} loading="lazy" />
                                ) : (
                                  <div className="placeholder">
                                    <span className="ph-frame">{item.name.slice(0, 4)}</span>
                                  </div>
                                )}
                              </div>
                              <div className="m-name">{item.name}</div>
                              <div className="m-tag">// 真人模特</div>
                            </button>
                          );
                        })
                      : FALLBACK_MODELS.map((item) => (
                          <button
                            type="button"
                            key={item.id}
                            className={`model-card ${pickedIds.includes(item.id) ? "selected" : ""}`}
                            onClick={() => togglePick(item.id)}
                          >
                            <span className="m-check">
                              <Check size={11} />
                            </span>
                            <div className="placeholder m-thumb">
                              <span className="ph-frame">{item.name}</span>
                            </div>
                            <div className="m-name">{item.name}</div>
                            <div className="m-tag">{item.tag}</div>
                          </button>
                        ))}
                  </div>
                </div>
              ) : (
                <div className="iw-step">
                  <div className="iw-step-h">
                    <span className="num">1</span>
                    <span className="title">选择平台</span>
                  </div>
                  <div className="platform-grid">
                    {PLATFORM_OPTIONS.map((item) => (
                      <button
                        type="button"
                        key={item.id}
                        className={`platform-card ${pickedIds.includes(item.id) ? "selected" : ""}`}
                        onClick={() => togglePick(item.id)}
                      >
                        <span className="p-check" />
                        <span className={`p-logo p-logo-${item.id}`}>{item.logo}</span>
                        <span className="p-name">{item.name}</span>
                      </button>
                    ))}
                  </div>
                </div>
              )}

              <div className="iw-step">
                <div className="iw-step-h">
                  <span className="num">2</span>
                  <span className="title">生成设置</span>
                </div>
                <div className="iw-sub">
                  <div className="iw-sub-h">// 生成数量{mode === "model" ? " (每模特)" : ""}</div>
                  <div className="pill-row">
                    {countOptions.map((value) => (
                      <button
                        type="button"
                        key={value}
                        className={`opt ${count === value ? "active" : ""}`}
                        onClick={() => setCount(value)}
                      >
                        {value} 张
                      </button>
                    ))}
                  </div>
                </div>
                {mode === "model" && (
                  <div className="iw-sub">
                    <div className="iw-sub-h">// 图片比例</div>
                    <div className="pill-row">
                      {ratioOptions.map((value) => (
                        <button
                          type="button"
                          key={value}
                          className={`opt ${ratio === value ? "active" : ""}`}
                          onClick={() => setRatio(value)}
                        >
                          {value}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              <div className="iw-cta">
                <button className="btn btn-primary" type="button" onClick={runGenerate} disabled={!canGenerate}>
                  {generating ? <span className="spinner" aria-hidden /> : <WandSparkles size={13} />}
                  {generating ? "生成中…" : `立即生成 (预估 ¥${(candidateCount * (mode === "model" ? 0.3 : 0.5)).toFixed(2)})`}
                </button>
                <div className="iw-cta-hint">// 采用即扣费并入对应商品 AI 素材 · 未采用不扣</div>
              </div>
            </div>

            {/* 右 · 结果预览 */}
            <div className="iw-preview">
              {!hasResults && !generating ? (
                <div className="iw-pv-empty">
                  <div className="mono">// EMPTY STATE</div>
                  <div className="title">还没有生成结果</div>
                  <div className="hint">
                    先选商品、选{mode === "model" ? "模特" : "平台"}，点击 <b>立即生成</b> 后，效果图会出现在这里
                  </div>
                </div>
              ) : (
                <>
                  <div className="iw-pv-h">
                    <Quote className="quote-icon" />
                    <div className="pv-meta">
                      <b>{count} 张</b>
                      {mode === "model" ? ` · ${ratio}` : ""}
                    </div>
                    <div className="pv-line">
                      <span className="k">商品</span>
                      <span className="v">{product?.title || "未选择"}</span>
                    </div>
                    {mode === "cover" && (
                      <div className="pv-line">
                        <span className="k">平台</span>
                        <span className="v">
                          {pickedIds.length
                            ? PLATFORM_OPTIONS.filter((p) => pickedIds.includes(p.id))
                                .map((p) => p.name)
                                .join("、")
                            : "未选择"}
                        </span>
                      </div>
                    )}
                  </div>
                  <div className="gen-card">{renderResultGrid()}</div>
                  <div className="gen-card-actions">
                    <button className="btn btn-sm" type="button">
                      <RefreshCw size={13} />
                      重跑
                    </button>
                    <button className="btn btn-sm" type="button">
                      <Check size={13} />
                      采用并入资产库
                    </button>
                    <button className="btn btn-sm btn-ghost" type="button" title="更多">
                      <MoreHorizontal size={13} />
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        </section>
      </div>
    </div>
  );
}

/* 底部 chat 输入栏 · 参数胶囊(基线 image-optimize .param + 下拉气泡) */
function Pill({
  label,
  value,
  options,
  onSelect
}: {
  label: string;
  value: string;
  options: Array<{ id: string; label: string }>;
  onSelect: (id: string) => void;
}) {
  const [open, setOpen] = useState(false);
  return (
    <div
      className={`ic-param ${open ? "open" : ""}`}
      tabIndex={0}
      onBlur={() => setOpen(false)}
    >
      <button className="ic-param-btn" type="button" onClick={() => setOpen((prev) => !prev)}>
        <span className="lbl-mono">{label}</span>
        <span>{value}</span>
        <ChevronDown size={10} />
      </button>
      <div className="ic-param-menu">
        {options.map((opt) => (
          <button
            type="button"
            key={opt.id}
            className={`mi ${opt.label === value || opt.id === value ? "selected" : ""}`}
            onMouseDown={(event) => {
              event.preventDefault();
              onSelect(opt.id);
              setOpen(false);
            }}
          >
            {opt.label}
            <Check className="mi-check" size={12} />
          </button>
        ))}
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════
   模特图方案对比 Demo(纯静态展示 · 像素还原)
   variant="A" → public/exact/model-photo-demo-a.html
   variant="B" → public/exact/model-photo-demo-b.html
   左栏 = 商品空间(搜索 + 最近 6 条 + 全部入口),由真 products 填充,空则回退基线占位。
   主区为静态方案展示(A:参数面板 + 结果双栏;B:任务流 + 底部 fixed 参数栏)。
   ════════════════════════════════════════════════ */

/* 基线左栏占位商品(无真 products 时兜底) */
const DEMO_SIDE_PRODUCTS = [
  { id: "d1", title: "透真补水面膜", category: "美妆个护", batches: 6 },
  { id: "d2", title: "透真清透防晒霜", category: "美妆个护", batches: 3 },
  { id: "d3", title: "南卡 Lite Pro 蓝牙耳机", category: "数码 3C", batches: 2 },
  { id: "d4", title: "滋啦速食牛肉面", category: "食品饮料", batches: 1 },
  { id: "d5", title: "三顿半同款冻干咖啡", category: "食品饮料", batches: 1 },
  { id: "d6", title: "小熊 4L 可视空气炸锅", category: "家居家电", batches: 0 }
];

export function ModelPhotoDemoPage({ variant, products, onBack }: { variant: "A" | "B"; products: Product[]; onBack: () => void }) {
  // 左栏商品空间:优先真 products(最近 6 条),空则回退基线占位
  const sideProducts =
    products.length > 0
      ? products.slice(0, 6).map((item, index) => ({
          id: item.id,
          title: item.title,
          category: item.category || "未分类",
          batches: DEMO_SIDE_PRODUCTS[index % DEMO_SIDE_PRODUCTS.length].batches
        }))
      : DEMO_SIDE_PRODUCTS;

  const [activeId, setActiveId] = useState(sideProducts[0].id);
  const active = sideProducts.find((item) => item.id === activeId) || sideProducts[0];
  const totalCount = products.length > 0 ? products.length : 24;

  // 共享左栏(两版一致)
  const side = (
    <aside className="dm-side">
      <div className="dm-side-h">
        <div className="ti-row">
          <span className="ti">商品空间</span>
          <button className="add" type="button" title="新建商品">
            <Plus size={11} />
          </button>
        </div>
        <div className="dm-search">
          <Search size={13} />
          <input type="text" placeholder="搜索商品 / 分类" />
        </div>
      </div>

      <div className="dm-prod-list">
        {sideProducts.map((item) => (
          <button
            type="button"
            key={item.id}
            className={`dm-prod ${item.id === active.id ? "active" : ""}`}
            onClick={() => setActiveId(item.id)}
          >
            <div className="thumb">主图</div>
            <div className="body">
              <div className="nm">{item.title}</div>
              <div className="sub">// {item.category} · {item.batches} 批</div>
            </div>
          </button>
        ))}
      </div>

      <button className="dm-all" type="button">
        <LayoutGrid size={12} />
        全部商品
        <span className="ct">{totalCount} 个</span>
        <ArrowRight className="arrow" size={12} />
      </button>
    </aside>
  );

  // ── 返回(基线无,挂在主区头部,保留 onBack)──
  const backBtn = (
    <button className="dm-back" type="button" onClick={onBack}>
      <ArrowLeft size={14} />
      返回模特图
    </button>
  );

  if (variant === "A") {
    return (
      <div className="model-demo dm-a">
        <div className="dm-banner">
          // DEMO · 方案 A · <b>商品 = 项目空间</b>。左栏仅商品空间:搜索 + 最近 6 条 + <b>全部商品</b>兜底入口;
          历史任务已挪进主区。主区:模特卡 + 张数 + 比例 + 立即生成,生成结果自动绑定到当前商品。
        </div>

        <div className="dm-grid">
          {side}

          <section className="dm-main">
            {/* 顶部 · 商品名 + 统计 */}
            <div className="dm-main-h">
              <div className="cur">
                <div className="crumb">// 商品空间</div>
                <h2>{active.title}</h2>
              </div>
              <div className="stats">
                <span>本商品 <b>6</b> 批</span>
                <span className="sep">·</span>
                <span>累计 <b>22</b> 张图</span>
                <span className="sep">·</span>
                <span>最近 <b>3 分钟前</b></span>
              </div>
              {backBtn}
            </div>

            {/* 参数面板 + 结果双栏 */}
            <div className="dm-body">
              {/* 左 · 参数面板 */}
              <div className="dm-form">
                <div className="dm-form-scroll">
                  <div className="dm-field">
                    <div className="dm-field-h">
                      选择模特<span className="opt">(已锁定商品 · {active.title})</span>
                    </div>
                    <div className="dm-models">
                      {["Ava", "Zoe", "Ben", "Lin", "Mia"].map((name, index) => (
                        <div className={`dm-model ${index === 0 ? "selected" : ""}`} key={name}>
                          <div className="ph">{name} · 3:4</div>
                          <div className="nm">{name}</div>
                        </div>
                      ))}
                      <div className="dm-model add">
                        <Plus size={18} />
                      </div>
                    </div>
                  </div>

                  <div className="dm-field">
                    <div className="dm-field-h">生成张数</div>
                    <div className="dm-chip-row">
                      {["1 张", "2 张", "4 张", "8 张"].map((label) => (
                        <button type="button" key={label} className={`dm-chip ${label === "4 张" ? "active" : ""}`}>
                          {label}
                        </button>
                      ))}
                    </div>
                  </div>

                  <div className="dm-field">
                    <div className="dm-field-h">画面比例</div>
                    <div className="dm-chip-row">
                      {["1:1", "3:4", "9:16", "16:9"].map((label) => (
                        <button type="button" key={label} className={`dm-chip ${label === "3:4" ? "active" : ""}`}>
                          {label}
                        </button>
                      ))}
                    </div>
                  </div>

                  <div className="dm-field">
                    <div className="dm-field-h">补充提示词<span className="opt">(选填)</span></div>
                    <textarea className="dm-textarea" placeholder="例:户外阳光、敷面膜的特写、白底产品摄影" />
                  </div>
                </div>

                <div className="dm-form-cta">
                  <div className="dm-cost">
                    <span>预估扣费 <span className="v">≈ ¥1.20</span></span>
                    <span>余额 ¥327.40</span>
                  </div>
                  <button className="dm-gen" type="button">
                    <Sparkles size={15} />
                    立即生成 · {active.title} × Ava
                  </button>
                </div>
              </div>

              {/* 右 · 结果(当前商品全部批次) */}
              <div className="dm-result">
                <div className="dm-result-h">
                  <span className="ti">最近批次 · Ava × 4 张</span>
                  <span className="sub">// 3 分钟前 · 已完成</span>
                </div>

                {/* 批次 1 */}
                <div className="dm-batch">
                  <div className="dm-batch-h">
                    <div className="pic">4×</div>
                    <div className="meta">
                      <div className="nm">Ava × 4 张</div>
                      <div className="info">
                        {active.title} <span className="sep">·</span> 3:4 <span className="sep">·</span> 3 分钟前{" "}
                        <span className="sep">·</span> ¥1.20
                      </div>
                    </div>
                    <div className="ops">
                      <button type="button" title="全部重跑"><RefreshCw size={13} /></button>
                      <button type="button" title="全部下载"><Download size={13} /></button>
                      <button type="button" title="加入资产库"><Bookmark size={13} /></button>
                    </div>
                  </div>
                  <div className="dm-batch-grid">
                    {[1, 2, 3, 4].map((n) => (
                      <div className="dm-cell" key={n}>
                        <div className="ph">Ava · #{n}</div>
                        <span className="tag">3:4</span>
                      </div>
                    ))}
                  </div>
                </div>

                {/* 批次 2 */}
                <div className="dm-batch">
                  <div className="dm-batch-h">
                    <div className="pic">4×</div>
                    <div className="meta">
                      <div className="nm">Zoe × 4 张</div>
                      <div className="info">
                        {active.title} <span className="sep">·</span> 3:4 <span className="sep">·</span> 12 分钟前{" "}
                        <span className="sep">·</span> ¥1.20
                      </div>
                    </div>
                    <div className="ops">
                      <button type="button" title="全部重跑"><RefreshCw size={13} /></button>
                      <button type="button" title="全部下载"><Download size={13} /></button>
                      <button type="button" title="加入资产库"><Bookmark size={13} /></button>
                    </div>
                  </div>
                  <div className="dm-batch-grid">
                    {[1, 2, 3, 4].map((n) => (
                      <div className="dm-cell" key={n}>
                        <div className="ph">Zoe · #{n}</div>
                        <span className="tag">3:4</span>
                      </div>
                    ))}
                  </div>
                </div>

                {/* 批次 3 · 生成中 */}
                <div className="dm-batch">
                  <div className="dm-batch-h">
                    <div className="pic">2×</div>
                    <div className="meta">
                      <div className="nm">Ben × 2 张</div>
                      <div className="info">
                        {active.title} <span className="sep">·</span> 3:4 <span className="sep">·</span> 刚刚{" "}
                        <span className="sep">·</span> 生成中
                      </div>
                    </div>
                    <div className="ops">
                      <button type="button" title="取消"><X size={13} /></button>
                    </div>
                  </div>
                  <div className="dm-batch-grid">
                    <div className="dm-cell"><div className="ph">生成中…</div></div>
                    <div className="dm-cell"><div className="ph">生成中…</div></div>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
    );
  }

  // ── variant === "B" · v2:任务流主区 + 底部 fixed 参数栏 ──
  return (
    <div className="model-demo dm-b">
      <div className="dm-banner">
        // DEMO v2 · 方案 A · <b>商品空间 + 任务流主区</b>。左栏只保留商品空间(搜索+最近6条+全部入口),
        任务列表搬到主区,筛选放主区顶部 toolbar,参数面板底部 fixed 化(类 image-optimize)。
      </div>

      <div className="dm-grid">
        {side}

        <section className="dm-main">
          {/* 顶部 标题 + stats + toolbar */}
          <div className="dm-main-h">
            <div className="crumb">// 商品空间 · 模特上身图</div>
            <div className="title-row">
              <h2>{active.title}</h2>
              {backBtn}
            </div>
            <div className="row">
              <div className="stats">
                <span>{active.category}</span><span className="sep">·</span>
                <span>本商品 <b>6</b> 批</span><span className="sep">·</span>
                <span>累计 <b>22</b> 张图</span><span className="sep">·</span>
                <span>最近 <b>3 分钟前</b></span>
              </div>
              <span className="spacer" />
              <div className="dm-tb">
                <button className="icbtn" type="button" title="搜索批次"><Search size={13} /></button>
                <button className="chip" type="button">时间 <ChevronDown size={10} /></button>
                <button className="chip" type="button">状态 <ChevronDown size={10} /></button>
                <button className="chip" type="button">模特 <ChevronDown size={10} /></button>
              </div>
            </div>
          </div>

          {/* 任务流 */}
          <div className="dm-stream">
            <div className="dm-day-h">
              <span>今天</span>
              <span className="ct">3 批 · 10 张</span>
            </div>

            {/* 批次 1 */}
            <div className="dm-batch">
              <div className="dm-batch-h">
                <div className="pic">4×</div>
                <div className="meta">
                  <div className="nm">Ava × 4 张 <span className="pill ok stat-pill"><span className="dot" />已完成</span></div>
                  <div className="info">
                    <span>3:4</span><span className="sep">·</span>
                    <span>3 分钟前</span><span className="sep">·</span>
                    <span>¥1.20</span>
                  </div>
                </div>
                <div className="ops">
                  <button type="button" title="全部重跑"><RefreshCw size={13} /></button>
                  <button type="button" title="全部下载"><Download size={13} /></button>
                  <button type="button" title="加入资产库"><Bookmark size={13} /></button>
                </div>
              </div>
              <div className="dm-batch-grid">
                {[1, 2, 3, 4].map((n) => (
                  <div className="dm-cell" key={n}><div className="ph">Ava · #{n}</div><span className="tag">3:4</span></div>
                ))}
              </div>
            </div>

            {/* 批次 2 */}
            <div className="dm-batch">
              <div className="dm-batch-h">
                <div className="pic">4×</div>
                <div className="meta">
                  <div className="nm">Zoe × 4 张 <span className="pill ok stat-pill"><span className="dot" />已完成</span></div>
                  <div className="info">
                    <span>3:4</span><span className="sep">·</span>
                    <span>12 分钟前</span><span className="sep">·</span>
                    <span>¥1.20</span>
                  </div>
                </div>
                <div className="ops">
                  <button type="button" title="全部重跑"><RefreshCw size={13} /></button>
                  <button type="button" title="全部下载"><Download size={13} /></button>
                  <button type="button" title="加入资产库"><Bookmark size={13} /></button>
                </div>
              </div>
              <div className="dm-batch-grid">
                {[1, 2, 3, 4].map((n) => (
                  <div className="dm-cell" key={n}><div className="ph">Zoe · #{n}</div><span className="tag">3:4</span></div>
                ))}
              </div>
            </div>

            {/* 批次 3 · 生成中 */}
            <div className="dm-batch">
              <div className="dm-batch-h">
                <div className="pic">2×</div>
                <div className="meta">
                  <div className="nm">Ben × 2 张 <span className="pill info stat-pill"><span className="dot" />生成中</span></div>
                  <div className="info">
                    <span>3:4</span><span className="sep">·</span>
                    <span>刚刚</span><span className="sep">·</span>
                    <span>¥0.60</span>
                  </div>
                </div>
                <div className="ops">
                  <button type="button" title="取消"><X size={13} /></button>
                </div>
              </div>
              <div className="dm-batch-grid">
                <div className="dm-cell gen"><div className="ph">生成中…</div></div>
                <div className="dm-cell gen"><div className="ph">生成中…</div></div>
              </div>
            </div>

            {/* 昨天 */}
            <div className="dm-day-h">
              <span>昨天</span>
              <span className="ct">2 批 · 8 张</span>
            </div>

            <div className="dm-batch">
              <div className="dm-batch-h">
                <div className="pic">4×</div>
                <div className="meta">
                  <div className="nm">Lin × 4 张 <span className="pill ok stat-pill"><span className="dot" />已完成</span></div>
                  <div className="info">
                    <span>3:4</span><span className="sep">·</span>
                    <span>昨天 18:24</span><span className="sep">·</span>
                    <span>¥1.20</span>
                  </div>
                </div>
                <div className="ops">
                  <button type="button" title="全部重跑"><RefreshCw size={13} /></button>
                  <button type="button" title="全部下载"><Download size={13} /></button>
                  <button type="button" title="加入资产库"><Bookmark size={13} /></button>
                </div>
              </div>
              <div className="dm-batch-grid">
                {[1, 2, 3, 4].map((n) => (
                  <div className="dm-cell" key={n}><div className="ph">Lin · #{n}</div><span className="tag">3:4</span></div>
                ))}
              </div>
            </div>

            {/* 更早 */}
            <div className="dm-day-h">
              <span>更早</span>
              <span className="ct">1 批 · 2 张 · 含 1 失败</span>
            </div>

            <div className="dm-batch">
              <div className="dm-batch-h">
                <div className="pic">2×</div>
                <div className="meta">
                  <div className="nm">Ava × 2 张 <span className="pill err stat-pill"><span className="dot" />失败</span></div>
                  <div className="info">
                    <span>3:4</span><span className="sep">·</span>
                    <span>2 天前</span>
                  </div>
                </div>
                <div className="ops">
                  <button type="button" title="全部重跑"><RefreshCw size={13} /></button>
                  <button type="button" title="删除"><Trash2 size={13} /></button>
                </div>
              </div>
              <div className="dm-batch-grid">
                <div className="dm-cell err"><div className="ph">失败 · 点重跑</div></div>
                <div className="dm-cell err"><div className="ph">失败 · 点重跑</div></div>
              </div>
            </div>
          </div>

          {/* 底部 fixed 参数面板 */}
          <div className="dm-param-wrap">
            <div className="dm-param">
              <button className="pchip active" type="button">
                <span className="lbl-mono">模特</span>
                <span>Ava</span>
                <ChevronDown size={10} />
              </button>
              <button className="pchip" type="button">
                <span className="lbl-mono">张数</span>
                <span>4</span>
                <ChevronDown size={10} />
              </button>
              <button className="pchip" type="button">
                <span className="lbl-mono">比例</span>
                <span>3:4</span>
                <ChevronDown size={10} />
              </button>
              <button className="pchip" type="button">
                <span className="lbl-mono">补充提示词</span>
                <span className="muted">+ 添加</span>
              </button>
              <span className="spacer" />
              <span className="meta-right">预估 <span className="v">¥1.20</span> · 余额 <span className="v">¥327.40</span></span>
              <button className="gen-btn" type="button">
                <Sparkles size={14} />
                生成 · {active.title} × Ava
              </button>
            </div>
          </div>
        </section>
      </div>
    </div>
  );
}
