/**
 * View Component: PostDetail
 * Right drawer showing full post content with A/B version toggle.
 *
 * Props:
 *   post: post object or null
 *   open: boolean
 *   onClose: () => void
 *   onToggleFav: (id) => void
 */

function CloseIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="6" x2="6" y2="18"></line>
      <line x1="6" y1="6" x2="18" y2="18"></line>
    </svg>
  );
}

function CopyIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
    </svg>
  );
}

function DownloadIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
      <polyline points="7 10 12 15 17 10"></polyline>
      <line x1="12" y1="15" x2="12" y2="3"></line>
    </svg>
  );
}

function HeartSmallIcon({ filled }) {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24"
      fill={filled ? 'currentColor' : 'none'}
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round">
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
    </svg>
  );
}

function PostDetail({ post, open, onClose, onToggleFav }) {
  const [copied, setCopied] = React.useState(false);
  const [downloading, setDownloading] = React.useState(null); // 正在下载的版本号 A/B/C
  const [toastMsg, setToastMsg] = React.useState('');
  const [sheet, setSheet] = React.useState(null); // 多方案保存面板 { ver, url }

  // 华为 / 鸿蒙浏览器：a[download]+blob 链路会被拦截，面板内隐藏直接下载
  // （渲染时直读 UA，保证环境检测始终新鲜）
  const huaweiEnv = CoverDownload.isHuawei();

  // 当前环境是否支持系统级文件分享（iOS 分享面板可直接「存储图像」）
  const canShareCover = React.useMemo(
    () => CoverDownload.canShareFiles(new Blob([new Uint8Array([1])], { type: 'image/jpeg' })),
    []
  );

  const [activeVersion, setActiveVersion] = React.useState('A');

  const toastTimer = React.useRef(null);
  const showToast = (msg) => {
    setToastMsg(msg);
    if (toastTimer.current) clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToastMsg(''), 2600);
  };

  // Reset to version A when post changes
  React.useEffect(() => {
    setActiveVersion('A');
  }, [post && post.id]);

  // Get version data safely
  const getVersionData = (post, ver) => {
    if (!post) return null;
    if (post.versions && post.versions[ver]) return post.versions[ver];
    return post;
  };

  const hasAB = post && post.versions && Object.keys(post.versions).length > 1;
  const versionKeys = post && post.versions ? Object.keys(post.versions).sort() : [];
  const versionData = getVersionData(post, activeVersion);
  // Cover switches with the active version; falls back to the post-level cover
  const detailCoverUrl = (versionData && versionData.coverUrl) || (post && post.coverUrl) || '';

  // Tags are appended to the end of the body text (hashtag style);
  // the merged word count includes tag characters.
  const tagsList = (versionData && versionData.tags) || [];
  const tagsLine = tagsList.map(tag => `#${tag}`).join(' ');
  const tagCharCount = tagsList.reduce((sum, tag) => sum + tag.length, 0);
  const totalWordCount = ((versionData && versionData.wordCount) || 0) + tagCharCount;

  /**
   * 保存指定版本的封面（A/B/C 均可独立保存）。
   * 触屏设备（含华为/鸿蒙、微信/飞书 webview）：直接弹「多方案保存面板」——
   * 长按保存为主，系统分享/直接下载/复制链接/浏览器打开兜底，
   * 彻底绕开华为浏览器上被拦截的 a[download]+blob 链路。
   * 桌面：保留一键直接下载。
   */
  const fileNameFor = (ver) =>
    `${(post && post.book ? post.book : '封面').replace(/[\\/:*?"<>|]/g, '')}-${ver}版-封面.jpg`;

  const handleSaveCover = async (ver) => {
    const vData = getVersionData(post, ver);
    const url = (vData && vData.coverUrl) || (post && post.coverUrl);
    if (!url || downloading) return;

    // 触屏：多方案保存面板（不先尝试下载——华为/鸿蒙上必失败或被静默拦截）
    if (CoverDownload.isTouch()) {
      setSheet({ ver, url });
      return;
    }

    // 桌面：一键直接下载（jpg 直取文件 blob，svg 经 canvas）
    setDownloading(ver);
    try {
      const mode = await CoverDownload.download(url, fileNameFor(ver));
      if (mode === 'shared') {
        showToast('已调起系统分享，选择「存储图像」即可保存');
      } else if (mode === 'webview-anchor') {
        setSheet({ ver, url });
      } else if (mode !== 'cancel') {
        showToast('已开始下载封面，若未成功可长按封面图保存');
      }
    } catch (e) {
      setSheet({ ver, url });
    } finally {
      setDownloading(null);
    }
  };

  const handleSheetShare = async () => {
    if (!sheet) return;
    try {
      const blob = await CoverDownload.toJpegBlob(sheet.url);
      const ok = await CoverDownload.shareBlob(blob, fileNameFor(sheet.ver));
      if (!ok) showToast('当前环境不支持系统分享，请长按图片保存');
    } catch (e) {
      showToast('当前环境不支持系统分享，请长按图片保存');
    }
  };

  // 面板内「直接下载」：仅非华为环境展示（华为/鸿蒙浏览器该链路会被拦截）
  const handleSheetDownload = async () => {
    if (!sheet || downloading) return;
    setDownloading(sheet.ver);
    try {
      const mode = await CoverDownload.download(sheet.url, fileNameFor(sheet.ver));
      if (mode === 'shared') showToast('已调起系统分享，选择「存储图像」即可保存');
      else if (mode !== 'cancel') showToast('已尝试下载，若未成功请长按图片保存');
    } catch (e) {
      showToast('直接下载不可用，请长按图片保存');
    } finally {
      setDownloading(null);
    }
  };

  const handleSheetCopyLink = async () => {
    if (!sheet) return;
    const ok = await CoverDownload.copyLink(sheet.url);
    showToast(ok
      ? '图片链接已复制，可在浏览器打开链接后长按保存'
      : '复制失败，请长按图片保存');
  };

  const sheetOpenUrl = sheet ? new URL(sheet.url, window.location.href).href : '';

  const handleCopy = () => {
    if (!post || !versionData) return;
    const text = `${versionData.title}\n\n${versionData.body}${tagsLine ? `\n\n${tagsLine}` : ''}`;
    navigator.clipboard.writeText(text).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    });
  };

  // Close on Escape
  React.useEffect(() => {
    if (!open) return;
    const handleKey = (e) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', handleKey);
    return () => document.removeEventListener('keydown', handleKey);
  }, [open, onClose]);

  if (!post || !versionData) return null;

  return (
    <>
      <div
        className={`drawer-overlay ${open ? 'open' : ''}`}
        onClick={onClose}
      />
      <aside className={`drawer ${open ? 'open' : ''}`} role="dialog" aria-label="内容详情">
        <div className="drawer-header">
          <button className="drawer-close" onClick={onClose} aria-label="关闭">
            <CloseIcon />
          </button>
          <div className="drawer-actions">
            <button className="btn-outline" onClick={handleCopy}>
              <CopyIcon />
              {copied ? '已复制' : '复制文案'}
            </button>
            <button
              className="btn-primary"
              onClick={() => onToggleFav(post.id)}
            >
              {post.favorite ? '♥ 已选材' : '♥ 标记选材'}
            </button>
          </div>
        </div>

        <div className="drawer-body">
          {detailCoverUrl ? (
            <div style={{ position: 'relative' }}>
              <img key={`${post.id}-${activeVersion}`} className="detail-cover" src={detailCoverUrl} alt={post.book} />
            </div>
          ) : (
            <div className="detail-cover" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-tertiary)', fontFamily: 'var(--font-serif)', fontSize: 20 }}>
              《{post.book}》
            </div>
          )}

          {/* 每个版本独立下载：A/B/C 各自可下载封面 */}
          {detailCoverUrl && (
            <div className="detail-cover-actions">
              {(hasAB ? versionKeys : [activeVersion]).map(ver => {
                const vData = getVersionData(post, ver);
                const hasCover = (vData && vData.coverUrl) || post.coverUrl;
                if (!hasCover) return null;
                return (
                  <button
                    key={ver}
                    className={`detail-cover-dl-btn ${activeVersion === ver ? 'current' : ''}`}
                    onClick={handleSaveCover.bind(null, ver)}
                    disabled={downloading === ver}
                    title={`保存${ver}版封面（长按保存 / 分享 / 下载多方案）`}
                  >
                    <DownloadIcon />
                    <span>{downloading === ver ? '处理中…' : hasAB ? `保存${ver}版封面` : '保存封面'}</span>
                  </button>
                );
              })}
            </div>
          )}

          {/* A/B/C Version Toggle - Detail view, driven by available versions */}
          {hasAB && (
            <div className="detail-version-section">
              <div className="detail-version-toggle">
                {versionKeys.map(ver => (
                  <button
                    key={ver}
                    className={`detail-version-btn ${activeVersion === ver ? 'active' : ''}`}
                    onClick={() => setActiveVersion(ver)}
                  >
                    <span className="detail-version-letter">{ver}</span>
                    <span className="detail-version-name">{(post.versions[ver] && post.versions[ver].versionLabel) || ver}</span>
                  </button>
                ))}
              </div>
              <div className="detail-version-desc">
                {versionData.versionDesc}
              </div>
            </div>
          )}

          <div className="detail-book-tag">📖 {post.book}{post.author ? ` · ${post.author}` : ''}</div>
          <h2 className="detail-title">{versionData.title}</h2>
          <div className="detail-title-count">
            标题共 <strong className={versionData.title.length > 19 ? 'over' : ''}>{versionData.title.length}</strong> 字
            {versionData.title.length > 19 ? (
              <span className="detail-title-warn">超出 {versionData.title.length - 19} 字（≤19字为宜）</span>
            ) : (
              <span className="detail-title-ok">符合 19 字以内要求</span>
            )}
          </div>

          <div className="detail-meta-row">
            <div className="detail-meta-item">
              <strong>发布日期：</strong>
              <span>{ContentService.formatDate(post.date)}</span>
            </div>
            {post.category && (
              <div className="detail-meta-item">
                <strong>分类：</strong>
                <span>{post.category}</span>
              </div>
            )}
            {post.batch && (
              <div className="detail-meta-item">
                <strong>批次：</strong>
                <span>{post.batch}深度版</span>
              </div>
            )}
            <div className="detail-meta-item">
              <strong>角度：</strong>
              <span>{versionData.angle}</span>
            </div>
            <div className="detail-meta-item">
              <strong>字数：</strong>
              <span>{totalWordCount}字（含标签）</span>
            </div>
            <div className="detail-meta-item">
              <strong>序号：</strong>
              <span>#{post.seq}</span>
            </div>
          </div>

          {post.hotTopic && (
            <div className="detail-hot-topic">
              <strong>🔥 热点关联</strong>
              <div className="detail-hot-topic-name">{post.hotTopic}</div>
              {(post.hotTopicFull || post.hotTopicDetail) && (
                <div className="detail-hot-topic-detail">{post.hotTopicFull || post.hotTopicDetail}</div>
              )}
            </div>
          )}

          <div className="detail-body">
            {versionData.body}
            {tagsLine && (
              <span className="detail-body-tags">{'\n\n'}{tagsLine}</span>
            )}
          </div>
        </div>
      </aside>

      {/* 下载结果提示 */}
      {toastMsg && <div className="download-toast">{toastMsg}</div>}

      {/* 多方案保存面板：长按保存为主，分享/下载/复制链接/浏览器打开兜底 */}
      {sheet && (
        <div className="download-sheet-overlay" onClick={() => setSheet(null)}>
          <div className="download-sheet" onClick={(e) => e.stopPropagation()} role="dialog" aria-label="保存封面">
            <div className="download-sheet-title">保存封面（{sheet.ver}版）</div>
            <img className="download-sheet-img" key={sheet.url} src={sheet.url} alt={`${post.book} ${sheet.ver}版封面`} />
            <div className="download-sheet-hint">
              {huaweiEnv ? (
                <>华为/鸿蒙浏览器不支持直接下载。最稳方式：<b>长按上方图片</b> → 选「保存图片」/「存储图像」，即可存入手机相册。</>
              ) : (
                <>最稳方式：<b>长按上方图片</b> → 选「保存图片」/「存储图像」；或使用下方其他方式。</>
              )}
            </div>
            <div className="download-sheet-actions">
              {canShareCover && (
                <button className="download-sheet-btn primary" onClick={handleSheetShare}>
                  系统分享保存
                </button>
              )}
              {!huaweiEnv && (
                <button className="download-sheet-btn" onClick={handleSheetDownload} disabled={downloading === sheet.ver}>
                  {downloading === sheet.ver ? '下载中…' : '直接下载'}
                </button>
              )}
              <button className="download-sheet-btn" onClick={handleSheetCopyLink}>
                复制图片链接
              </button>
              <a className="download-sheet-btn" href={sheetOpenUrl} target="_blank" rel="noopener noreferrer">
                浏览器打开原图
              </a>
              <button className="download-sheet-btn" onClick={() => setSheet(null)}>
                关闭
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

window.PostDetail = PostDetail;
