/* productdetail.jsx — App Store-style detail (real data) + CARTO AI positioning */

function Stars({ value, s = 14, gap = 2 }) {
  const v = Number(value) || 0;
  return (
    <div style={{ display: "inline-flex", gap }}>
      {[0, 1, 2, 3, 4].map(i => {
        const fill = v - i;
        const f = fill >= 1 ? 1 : fill <= 0 ? 0 : fill;
        return (
          <svg key={i} width={s} height={s} viewBox="0 0 24 24">
            <defs><linearGradient id={`st${i}-${s}`}><stop offset={`${f * 100}%`} stopColor="var(--n-amber)" /><stop offset={`${f * 100}%`} stopColor="rgba(255,255,255,.14)" /></linearGradient></defs>
            <path d="M12 2.5l2.9 6 6.6.9-4.8 4.6 1.2 6.5L12 17.4 6.1 20.5l1.2-6.5L2.5 9.4l6.6-.9L12 2.5Z" fill={`url(#st${i}-${s})`} />
          </svg>
        );
      })}
    </div>
  );
}

function PDSection({ title, action, children, style }) {
  return (
    <div style={{ padding: "26px 0", borderTop: "1px solid var(--line)", ...style }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 16 }}>
        <h2 style={{ margin: 0, fontSize: 19, color: "var(--t-hi)", fontWeight: 600 }}>{title}</h2>
        {action}
      </div>
      {children}
    </div>
  );
}

function MetaChip({ k, v, sub }) {
  return (
    <div style={{ flex: "none", padding: "0 22px", borderRight: "1px solid var(--line)", textAlign: "center", minWidth: 92 }}>
      <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 7 }}>{k}</div>
      <div style={{ color: "var(--t-hi)", fontSize: 17, fontWeight: 600, fontFamily: "var(--mono)", display: "flex", alignItems: "center", justifyContent: "center", gap: 4 }}>{v}</div>
      {sub && <div style={{ color: "var(--t-faint)", fontSize: 10.5, marginTop: 5, whiteSpace: "nowrap" }}>{sub}</div>}
    </div>
  );
}

function RouteStack({ stack }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
      {stack.map((s, i) => {
        const last = i === stack.length - 1;
        const link = !!s.go && !last;
        return (
          <React.Fragment key={i}>
            {i > 0 && <span style={{ color: "var(--t-faint)", display: "inline-flex" }}><Icon name="chev" s={11} /></span>}
            <span onClick={link ? s.go : undefined}
              onMouseEnter={e => { if (link) { e.currentTarget.style.color = "var(--t-hi)"; e.currentTarget.style.background = "var(--hover)"; } }}
              onMouseLeave={e => { if (link) { e.currentTarget.style.color = "var(--t-dim)"; e.currentTarget.style.background = "var(--panel-2)"; } }}
              style={{ fontFamily: "var(--mono)", fontSize: 11.5, padding: "4px 9px", borderRadius: 6, whiteSpace: "nowrap",
                cursor: link ? "pointer" : "default",
                color: last ? "var(--acc-hi)" : "var(--t-dim)",
                background: last ? "var(--acc-soft)" : "var(--panel-2)",
                border: `1px solid ${last ? "rgba(139,124,246,.3)" : "var(--line)"}`,
                transition: "color .15s, background .15s" }}>{s.label}</span>
          </React.Fragment>
        );
      })}
    </div>
  );
}

/* small muted placeholder note for fields the public App Store API does not expose */
function Placeholder({ children }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "14px 16px", borderRadius: "var(--r)", border: "1px dashed var(--line-2)", background: "var(--panel-2)", color: "var(--t-dim)", fontSize: 12.5 }}>
      <Icon name="layers" s={14} c="var(--t-faint)" />
      <span>{children}</span>
    </div>
  );
}

/* 预览视频卡：海报 + 播放角标，点击就地用 hls.js 播放 App Store 的 m3u8 预览 */
function VideoPreview({ src, poster, w = 158 }) {
  const [playing, setPlaying] = useState(false);
  const videoRef = useRef(null);

  useEffect(() => {
    if (!playing) return;
    const v = videoRef.current;
    if (!v) return;
    let hls;
    const tryPlay = () => { if (v.play) v.play().catch(() => {}); };
    // 优先 hls.js（Chrome 的 canPlayType 会谎报支持 HLS，实际放不了）
    if (window.Hls && window.Hls.isSupported()) {
      hls = new window.Hls({ enableWorker: true });
      hls.loadSource(src);
      hls.attachMedia(v);
      hls.on(window.Hls.Events.MANIFEST_PARSED, tryPlay);
    } else if (v.canPlayType("application/vnd.apple.mpegurl")) {
      v.src = src;                              // Safari 原生 HLS
      v.addEventListener("loadedmetadata", tryPlay, { once: true });
    } else {
      v.src = src;
      tryPlay();
    }
    return () => { if (hls) hls.destroy(); };
  }, [playing, src]);

  const h = Math.round(w * 2.04);
  return (
    <div style={{ position: "relative", borderRadius: 18, overflow: "hidden", width: w, height: h, background: "#000", boxShadow: "0 12px 30px -12px rgba(0,0,0,.6)" }}>
      {playing
        ? <video ref={videoRef} controls playsInline style={{ width: "100%", height: "100%", objectFit: "cover", display: "block", background: "#000" }} />
        : <React.Fragment>
            {poster
              ? <img src={poster} alt="" draggable={false} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
              : <div style={{ width: "100%", height: "100%", background: "var(--panel-2)" }} />}
            <div onClick={() => setPlaying(true)} style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", cursor: "pointer", background: "rgba(0,0,0,.18)" }}>
              <div style={{ width: 46, height: 46, borderRadius: "50%", background: "rgba(10,10,12,.6)", backdropFilter: "blur(4px)", border: "1px solid rgba(255,255,255,.4)", display: "grid", placeItems: "center" }}>
                <Icon name="play" s={18} c="#fff" />
              </div>
              <span style={{ position: "absolute", top: 10, left: 10, padding: "3px 8px", borderRadius: 6, background: "rgba(10,10,12,.6)", color: "#fff", fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: ".1em" }}>预览视频</span>
            </div>
          </React.Fragment>}
    </div>
  );
}

function ProductDetail({ detail, from, onHome, onOpenMap, onAnalyze, theme, toggleTheme, readOnly }) {
  const app = detail.app;
  const status = detail.status;
  const done = status === "done";   // 有页面地图可展示
  const stats = detail.stats || { screens: 0, paths: 0, elements: 0 };
  const aiStatus = detail.aiStatus;
  const aiPending = aiStatus === "running" || aiStatus === "queued";
  const aiFailed = aiStatus === "error" || aiStatus === "unavailable";

  // 唯一的主操作：有地图就「查看地图」（可点），没有则「地图待采集」（禁用占位）。
  const cta = done
    ? <button className="btn btn-primary" style={{ height: 36 }} onClick={onOpenMap}>查看地图<Icon name="arrow" s={15} c="#fff" /></button>
    : <button className="btn" disabled style={{ height: 36 }} title="该 App 暂无页面地图">地图待采集</button>;

  const statusChip = done
    ? <span style={{ display: "flex", alignItems: "center", gap: 6, color: "var(--ok)", fontFamily: "var(--mono)", fontSize: 12, whiteSpace: "nowrap", flex: "none" }}><span style={{ width: 6, height: 6, borderRadius: 99, background: "var(--ok)", boxShadow: "0 0 6px var(--ok)" }} />已测绘</span>
    : <span style={{ display: "flex", alignItems: "center", gap: 6, color: "var(--t-dim)", fontFamily: "var(--mono)", fontSize: 12, whiteSpace: "nowrap", flex: "none" }}><span style={{ width: 6, height: 6, borderRadius: 99, background: "var(--t-faint)" }} />无地图</span>;

  const crumbs = [{ label: "首页", go: onHome }, { label: app.name, go: null }, { label: "详情", go: null }];
  const previews = app.previews || [];

  return (
    <div style={{ height: "100vh", display: "flex", flexDirection: "column" }}>
      <MiniTop onHome={onHome} crumb={<RouteStack stack={crumbs} />} right={<div className="icon-btn" onClick={toggleTheme}><Icon name="sun" s={15} /></div>} />

      <div style={{ flex: 1, overflowY: "auto" }}>
        <div className="fade-in" style={{ maxWidth: 1040, margin: "0 auto", padding: "20px 40px 70px" }}>
          {from === "import" && (
            <div style={{ display: "flex", justifyContent: "flex-end", padding: "4px 0 18px" }}><Pipeline step={1} /></div>
          )}

          {/* header */}
          <div style={{ display: "flex", gap: 28, alignItems: "center" }}>
            <AppIcon icon={app.icon || {}} s={116} radius={0.22} style={{ boxShadow: "inset 0 0 0 1px rgba(255,255,255,.14), 0 16px 40px -14px rgba(0,0,0,.6)" }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <h1 style={{ margin: 0, fontSize: 30, color: "var(--t-hi)", fontWeight: 600, letterSpacing: "-0.01em" }}>{app.name}</h1>
              <div style={{ color: "var(--t-dim)", fontSize: 15, marginTop: 4 }}>{app.sub}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 14, flexWrap: "wrap" }}>
                <span style={{ color: "var(--acc-hi)", fontSize: 13.5, fontFamily: "var(--mono)", whiteSpace: "nowrap" }}>{app.publisher}</span>
                <span className="pill" style={{ height: 22 }}>{app.platform}</span>
                {statusChip}
                {app.storeUrl && <a href={app.storeUrl} target="_blank" rel="noreferrer" style={{ color: "var(--t-dim)", fontSize: 12, fontFamily: "var(--mono)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="link" s={12} c="var(--t-dim)" />App Store</a>}
              </div>
            </div>
            {cta}
          </div>

          {/* meta strip */}
          <div style={{ display: "flex", overflowX: "auto", marginTop: 26, padding: "18px 0", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
            <div style={{ paddingLeft: 0 }}><MetaChip k="评分" v={<><span>{app.rating}</span><Icon name="star" s={13} c="var(--n-amber)" /></>} sub={`${app.ratingCount} 评分`} /></div>
            <MetaChip k="年龄" v={app.age} sub="分级" />
            <MetaChip k="排行" v={app.rank || "—"} sub={app.rank ? "" : "接口未提供"} />
            <MetaChip k="大小" v={(app.size || "—").replace(" MB", "")} sub="MB" />
            <MetaChip k="语言" v={(app.info.find(([k]) => k === "语言") || [, "—"])[1].replace(" 种", "+")} sub="种界面" />
            <div style={{ borderRight: "none" }}><MetaChip k="价格" v={(app.price || "—").includes("免费") || /free/i.test(app.price || "") ? "免费" : app.price} sub={(app.price || "").includes("内购") ? "含内购" : ""} /></div>
          </div>

          {/* preview gallery — real screenshots + video */}
          <PDSection title="预览" action={<span className="eyebrow" style={{ color: "var(--t-faint)" }}>{previews.length} 项{previews.some(p => p.video) ? " · 含视频" : ""}</span>}>
            <div style={{ display: "flex", gap: 16, overflowX: "auto", paddingBottom: 8 }}>
              {previews.map((p, i) => (
                <div key={i} style={{ flex: "none", display: "flex", flexDirection: "column", gap: 10 }}>
                  {p.video
                    ? <VideoPreview src={p.video} poster={p.url} w={158} />
                    : <div style={{ position: "relative", borderRadius: 18, overflow: "hidden", boxShadow: "0 12px 30px -12px rgba(0,0,0,.6)" }}>
                        {p.url
                          ? <img src={p.url} alt="" draggable={false} style={{ height: 322, display: "block", borderRadius: 18 }} />
                          : <Phone arch={p.arch} accent={p.accent} w={158} />}
                      </div>}
                  {p.cap && <span style={{ fontSize: 12, color: "var(--t-dim)", textAlign: "center", maxWidth: 158 }}>{p.cap}</span>}
                </div>
              ))}
            </div>
          </PDSection>

          {/* CARTO AI positioning */}
          <div style={{ marginTop: 26, padding: "24px 26px", borderRadius: "var(--r-lg)", border: "1px solid rgba(139,124,246,.28)", background: "linear-gradient(180deg, var(--acc-soft), transparent)" }}>
            <div className="eyebrow" style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--acc-hi)", marginBottom: 14 }}>
              <Icon name="sparkle" s={13} c="var(--acc)" />CARTO · AI 定位分析
              {aiPending && <span style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "var(--acc-hi)", textTransform: "none", letterSpacing: 0 }}><span className="spin" style={{ width: 10, height: 10, border: "1.5px solid var(--acc-soft)", borderTopColor: "var(--acc-hi)", borderRadius: "50%" }} />AI 分析中…</span>}
            </div>
            {app.positioning ? (
              <React.Fragment>
                <p style={{ margin: 0, fontSize: 15, lineHeight: 1.75, color: "var(--t)" }}>{app.positioning}</p>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8, margin: "16px 0 20px" }}>
                  {(app.tags || []).map(t => <span key={t} className="pill" style={{ height: 24, fontSize: 11, color: "var(--acc-hi)", borderColor: "rgba(139,124,246,.3)", background: "var(--acc-soft)" }}>{t}</span>)}
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18, paddingTop: 18, borderTop: "1px solid var(--line)" }}>
                  <div><div className="eyebrow" style={{ marginBottom: 7 }}>目标人群</div><div style={{ fontSize: 13, color: "var(--t)", lineHeight: 1.55 }}>{app.audience || "—"}</div></div>
                  <div><div className="eyebrow" style={{ marginBottom: 7 }}>商业模式</div><div style={{ fontSize: 13, color: "var(--t)", lineHeight: 1.55 }}>{app.model || "—"}</div></div>
                  <div><div className="eyebrow" style={{ marginBottom: 7 }}>核心循环</div><div style={{ fontSize: 13, color: "var(--t)", lineHeight: 1.55 }}>{app.hooks && app.hooks[0] ? app.hooks[0].v : "—"}</div></div>
                </div>
              </React.Fragment>
            ) : aiPending ? (
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {[1, 0.9, 0.7].map((w, i) => <div key={i} className="shimmer" style={{ height: 13, width: `${w * 100}%`, borderRadius: 5, background: "var(--raised)" }} />)}
                <div style={{ fontSize: 12.5, color: "var(--t-dim)", marginTop: 6 }}>正在基于 App Store 信息生成 AI 定位分析，完成后将自动刷新。</div>
              </div>
            ) : readOnly ? (
              <div style={{ fontSize: 13, color: "var(--t-dim)", lineHeight: 1.6 }}>该 App 暂无 AI 定位分析。</div>
            ) : (
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
                <div style={{ flex: 1, minWidth: 220, fontSize: 13, color: "var(--t-dim)", lineHeight: 1.6 }}>
                  {aiStatus === "unavailable"
                    ? "未配置 AI（CHARABOARD_API_KEY），AI 定位分析暂不可用。"
                    : aiStatus === "error"
                    ? "上次分析未能完成，可重新触发。"
                    : "尚未生成 AI 定位分析。"}
                </div>
                <button className="btn btn-primary" style={{ height: 36 }} onClick={onAnalyze}>
                  <Icon name="sparkle" s={13} c="#fff" />{aiFailed ? "重新分析" : "开始分析"}
                </button>
              </div>
            )}
          </div>

          {/* description */}
          <PDSection title="简介">
            {app.description
              ? <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>{app.description.map((p, i) => <p key={i} style={{ margin: 0, fontSize: 14.5, lineHeight: 1.75, color: "var(--t)" }}>{p}</p>)}</div>
              : <Placeholder>该 App 未在 App Store 提供简介。</Placeholder>}
          </PDSection>

          {/* what's new */}
          <PDSection title="新功能" action={app.whatsNew && app.whatsNew.version ? <span className="num" style={{ color: "var(--t-faint)", fontSize: 12 }}>v{app.whatsNew.version} · {app.whatsNew.date}</span> : null}>
            {app.whatsNew && app.whatsNew.notes && app.whatsNew.notes.length
              ? <ul style={{ margin: 0, paddingLeft: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 9 }}>
                  {app.whatsNew.notes.map((n, i) => (
                    <li key={i} style={{ display: "flex", gap: 10, fontSize: 14, color: "var(--t)", lineHeight: 1.55 }}>
                      <span style={{ marginTop: 6, width: 4, height: 4, borderRadius: 99, background: "var(--acc)", flex: "none" }} />{n}
                    </li>
                  ))}
                </ul>
              : <Placeholder>该版本未提供更新说明。</Placeholder>}
          </PDSection>

          {/* information */}
          <PDSection title="信息">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 40px" }}>
              {app.info.map(([k, v], i) => (
                <div key={i} style={{ display: "flex", justifyContent: "space-between", gap: 16, padding: "11px 0", borderBottom: "1px solid var(--line)" }}>
                  <span className="eyebrow" style={{ fontSize: 11, color: "var(--t-dim)", letterSpacing: ".05em" }}>{k}</span>
                  <span style={{ fontSize: 13, color: "var(--t-hi)", textAlign: "right" }}>{v}</span>
                </div>
              ))}
            </div>
          </PDSection>

          {/* supported languages */}
          <PDSection title="支持语言">
            {app.langs
              ? <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>{app.langs.map(l => <span key={l} className="pill" style={{ height: 24 }}>{l}</span>)}</div>
              : <Placeholder>未获取到语言信息。</Placeholder>}
            {app.compat && <div style={{ color: "var(--t-faint)", fontSize: 12, marginTop: 16, lineHeight: 1.55 }}>{app.compat}</div>}
          </PDSection>

        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ProductDetail, Stars });
