// 文章发布编辑器
const { useState, useEffect, useRef } = React;

function ArticlePublishPage({ show, onClose, onPublished }) {
  const { showToast, api } = useApp();
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [coverImage, setCoverImage] = useState('');
  const [categoryId, setCategoryId] = useState(0);
  const [categories, setCategories] = useState([]);
  const [visibility, setVisibility] = useState('public');
  const [password, setPassword] = useState('');
  const [price, setPrice] = useState('');
  const [rewardEnabled, setRewardEnabled] = useState(true);
  const [seoTitle, setSeoTitle] = useState('');
  const [seoDescription, setSeoDescription] = useState('');
  const [seoKeywords, setSeoKeywords] = useState('');
  const [showSEO, setShowSEO] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [showVisibilitySheet, setShowVisibilitySheet] = useState(false);
  const [showCategorySheet, setShowCategorySheet] = useState(false);
  const editorRef = useRef(null);

  const visibilityOptions = [
    { key: 'public', label: '完全公开', desc: '所有人可见', icon: '🌍' },
    { key: 'private', label: '完全保密', desc: '仅自己可见', icon: '🔒' },
    { key: 'friends', label: '仅朋友可看', desc: '关注你的人可见', icon: '👥' },
    { key: 'password', label: '密码访问', desc: '输入密码可看', icon: '🔑' },
    { key: 'paid', label: '付费阅读', desc: '设置价格解锁', icon: '💰' },
  ];

  useEffect(() => {
    if (show) {
      loadCategories();
      setTitle('');
      setContent('');
      setCoverImage('');
      setCategoryId(0);
      setVisibility('public');
      setPassword('');
      setPrice('');
      setRewardEnabled(true);
    }
  }, [show]);

  const loadCategories = async () => {
    try {
      const res = await api.get('/article-categories');
      if (res.success) setCategories(res.data || []);
    } catch(e) {}
  };

  const handleFormat = (cmd) => {
    // 简单富文本：插入格式化标记
    const textarea = document.getElementById('article-editor');
    if (!textarea) return;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selected = content.substring(start, end);

    let prefix = '', suffix = '', insertText = '';
    switch(cmd) {
      case 'bold':
        prefix = '<strong>'; suffix = '</strong>';
        break;
      case 'h2':
        prefix = '\n<h2>'; suffix = '</h2>\n';
        break;
      case 'h3':
        prefix = '\n<h3>'; suffix = '</h3>\n';
        break;
      case 'quote':
        prefix = '\n<blockquote>'; suffix = '</blockquote>\n';
        break;
      case 'link':
        prefix = '<a href="'; suffix = '">链接文字</a>';
        break;
      case 'image':
        insertText = '\n<img src="" alt="" />\n';
        break;
      case 'ul':
        prefix = '\n<ul>\n  <li>'; suffix = '</li>\n</ul>\n';
        break;
      default:
        break;
    }

    const newText = content.substring(0, start) + prefix + (selected || insertText) + suffix + content.substring(end);
    setContent(newText);
    setTimeout(() => {
      textarea.focus();
      const pos = start + prefix.length + (selected || insertText).length;
      textarea.setSelectionRange(pos, pos + (selected ? suffix.length : 0));
    }, 0);
  };

  const handleCoverUpload = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    // 本地上传预览
    const reader = new FileReader();
    reader.onload = (ev) => {
      setCoverImage(ev.target.result);
    };
    reader.readAsDataURL(file);
    // 模拟上传
    showToast('封面上传成功（演示模式）');
  };

  const handleSubmit = async () => {
    if (!title.trim()) {
      showToast('请输入文章标题');
      return;
    }
    if (!content.trim()) {
      showToast('请输入文章正文');
      return;
    }
    if (visibility === 'password' && !password.trim()) {
      showToast('请设置访问密码');
      return;
    }
    if (visibility === 'paid' && (!price || parseFloat(price) <= 0)) {
      showToast('请设置文章价格');
      return;
    }

    setSubmitting(true);
    try {
      const body = {
        title: title.trim(),
        content: content.trim(),
        cover_image: coverImage,
        category_id: categoryId,
        visibility: visibility === 'paid' ? 'public' : visibility,
        password: password || '',
        price: visibility === 'paid' ? parseFloat(price) : 0,
        reward_enabled: rewardEnabled ? 1 : 0,
        seo_title: seoTitle.trim(),
        seo_description: seoDescription.trim(),
        seo_keywords: seoKeywords.trim(),
      };
      const res = await api.post('/articles', body);
      if (res.success) {
        showToast('发布成功');
        if (onClose) onClose();
        if (onPublished) onPublished(res.data);
      } else {
        showToast(res.message || '发布失败');
      }
    } catch(e) {
      showToast('发布失败');
    } finally {
      setSubmitting(false);
    }
  };

  if (!show) return null;

  const currentVisibility = visibilityOptions.find(v => v.key === visibility);
  const currentCategory = categories.find(c => c.id === categoryId);

  return (
    <div className="publish-article-overlay">
      <div className="publish-article-container">
        {/* 顶部导航 */}
        <div className="publish-header">
          <div className="publish-close" onClick={onClose}>取消</div>
          <div className="publish-title">发布文章</div>
          <button
            className={`publish-submit ${submitting ? 'disabled' : ''}`}
            onClick={handleSubmit}
            disabled={submitting}
          >
            {submitting ? '发布中...' : '发布'}
          </button>
        </div>

        <div className="publish-body">
          {/* 标题输入 */}
          <input
            type="text"
            className="title-input"
            placeholder="请输入文章标题"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            maxLength={60}
          />

          {/* 封面图 */}
          <div className="cover-upload">
            {coverImage ? (
              <div className="cover-preview">
                <img src={coverImage} alt="" />
                <div className="cover-remove" onClick={() => setCoverImage('')}>✕ 更换封面</div>
              </div>
            ) : (
              <label className="cover-upload-btn">
                <input type="file" accept="image/*" onChange={handleCoverUpload} style={{ display: 'none' }} />
                <div className="cover-upload-icon">🖼️</div>
                <div>上传封面图</div>
              </label>
            )}
          </div>

          {/* 富文本工具栏 */}
          <div className="editor-toolbar">
            <button onClick={() => handleFormat('bold')} title="加粗"><b>B</b></button>
            <button onClick={() => handleFormat('h2')} title="标题2">H2</button>
            <button onClick={() => handleFormat('h3')} title="标题3">H3</button>
            <button onClick={() => handleFormat('quote')} title="引用">❝</button>
            <button onClick={() => handleFormat('ul')} title="列表">•</button>
            <button onClick={() => handleFormat('link')} title="链接">🔗</button>
            <button onClick={() => handleFormat('image')} title="图片">🖼️</button>
          </div>

          {/* 正文编辑区 */}
          <textarea
            id="article-editor"
            ref={editorRef}
            className="content-editor"
            placeholder="开始撰写你的文章..."
            value={content}
            onChange={(e) => setContent(e.target.value)}
          />

          {/* 设置项 */}
          <div className="publish-settings">
            <div className="setting-row" onClick={() => setShowCategorySheet(true)}>
              <span className="setting-label">📂 文章分类</span>
              <span className="setting-value">
                {currentCategory ? currentCategory.name : '未分类'} →
              </span>
            </div>

            <div className="setting-row" onClick={() => setShowVisibilitySheet(true)}>
              <span className="setting-label">
                {currentVisibility?.icon} {currentVisibility?.label}
              </span>
              <span className="setting-value">{currentVisibility?.desc} →</span>
            </div>

            {visibility === 'password' && (
              <div className="setting-row-input">
                <span className="setting-label">🔑 访问密码</span>
                <input
                  type="text"
                  placeholder="请设置访问密码"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  maxLength={20}
                />
              </div>
            )}

            {visibility === 'paid' && (
              <div className="setting-row-input">
                <span className="setting-label">💰 文章价格</span>
                <div className="price-input-wrap">
                  <span className="price-symbol">¥</span>
                  <input
                    type="number"
                    placeholder="0.00"
                    value={price}
                    onChange={(e) => setPrice(e.target.value)}
                    min="0"
                    step="0.01"
                  />
                </div>
              </div>
            )}

            <div className="setting-row">
              <span className="setting-label">🎁 开启打赏</span>
              <label className="switch">
                <input
                  type="checkbox"
                  checked={rewardEnabled}
                  onChange={(e) => setRewardEnabled(e.target.checked)}
                />
                <span className="slider"></span>
              </label>
            </div>

            {/* SEO 设置折叠 */}
            <div
              style={{
                padding: '12px 0',
                borderTop: '1px solid var(--border)',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
              }}
              onClick={() => setShowSEO(!showSEO)}
            >
              <span style={{ fontSize: 14, color: 'var(--text-primary)' }}>🔍 SEO 自定义</span>
              <span style={{ fontSize: 14, color: 'var(--text-tertiary)' }}>
                {showSEO ? '▲' : '▼'}
              </span>
            </div>

            {showSEO && (
              <div style={{ paddingBottom: 8 }}>
                <div style={{ marginBottom: 12 }}>
                  <div style={{
                    fontSize: 12,
                    color: 'var(--text-secondary)',
                    marginBottom: 4,
                  }}>SEO 标题（留空则使用文章标题）</div>
                  <input
                    type="text"
                    value={seoTitle}
                    onChange={(e) => setSeoTitle(e.target.value)}
                    placeholder="建议30字以内"
                    style={{
                      width: '100%',
                      padding: '8px 10px',
                      borderRadius: 6,
                      border: '1px solid var(--border)',
                      fontSize: 13,
                      outline: 'none',
                      boxSizing: 'border-box',
                    }}
                  />
                </div>
                <div style={{ marginBottom: 12 }}>
                  <div style={{
                    fontSize: 12,
                    color: 'var(--text-secondary)',
                    marginBottom: 4,
                  }}>SEO 描述（留空则自动截取正文）</div>
                  <textarea
                    value={seoDescription}
                    onChange={(e) => setSeoDescription(e.target.value)}
                    placeholder="建议80-120字"
                    rows={2}
                    style={{
                      width: '100%',
                      padding: '8px 10px',
                      borderRadius: 6,
                      border: '1px solid var(--border)',
                      fontSize: 13,
                      outline: 'none',
                      resize: 'vertical',
                      minHeight: 48,
                      boxSizing: 'border-box',
                      fontFamily: 'inherit',
                    }}
                  />
                </div>
                <div style={{ marginBottom: 4 }}>
                  <div style={{
                    fontSize: 12,
                    color: 'var(--text-secondary)',
                    marginBottom: 4,
                  }}>SEO 关键词（留空则使用标签）</div>
                  <input
                    type="text"
                    value={seoKeywords}
                    onChange={(e) => setSeoKeywords(e.target.value)}
                    placeholder="英文逗号分隔"
                    style={{
                      width: '100%',
                      padding: '8px 10px',
                      borderRadius: 6,
                      border: '1px solid var(--border)',
                      fontSize: 13,
                      outline: 'none',
                      boxSizing: 'border-box',
                    }}
                  />
                </div>
              </div>
            )}
          </div>

          <div className="publish-tip">
            💡 支持 HTML 标签排版：h2/h3 标题、strong 加粗、blockquote 引用、a 链接、img 图片、ul/li 列表等
          </div>
        </div>
      </div>

      {/* 分类选择 BottomSheet */}
      {showCategorySheet && (
        <BottomSheet show={showCategorySheet} onClose={() => setShowCategorySheet(false)} title="选择分类">
          <div className="sheet-options">
            <div
              className={`sheet-option ${categoryId === 0 ? 'active' : ''}`}
              onClick={() => { setCategoryId(0); setShowCategorySheet(false); }}
            >
              <span>未分类</span>
              {categoryId === 0 && <span className="check">✓</span>}
            </div>
            {categories.map(c => (
              <div
                key={c.id}
                className={`sheet-option ${categoryId === c.id ? 'active' : ''}`}
                onClick={() => { setCategoryId(c.id); setShowCategorySheet(false); }}
              >
                <span>{c.name}</span>
                {categoryId === c.id && <span className="check">✓</span>}
              </div>
            ))}
          </div>
        </BottomSheet>
      )}

      {/* 权限选择 BottomSheet */}
      {showVisibilitySheet && (
        <BottomSheet show={showVisibilitySheet} onClose={() => setShowVisibilitySheet(false)} title="访问权限">
          <div className="sheet-options">
            {visibilityOptions.map(opt => (
              <div
                key={opt.key}
                className={`sheet-option visibility-option ${visibility === opt.key ? 'active' : ''}`}
                onClick={() => {
                  setVisibility(opt.key);
                  if (opt.key !== 'password') setPassword('');
                  if (opt.key !== 'paid') setPrice('');
                  setShowVisibilitySheet(false);
                }}
              >
                <div className="visibility-option-left">
                  <span className="visibility-icon">{opt.icon}</span>
                  <div>
                    <div className="visibility-label">{opt.label}</div>
                    <div className="visibility-desc">{opt.desc}</div>
                  </div>
                </div>
                {visibility === opt.key && <span className="check">✓</span>}
              </div>
            ))}
          </div>
        </BottomSheet>
      )}

      <style>{`
        .publish-article-overlay {
          position: fixed;
          inset: 0;
          background: #fff;
          z-index: 1000;
          display: flex;
          flex-direction: column;
        }
        .publish-article-container {
          display: flex;
          flex-direction: column;
          height: 100%;
        }
        .publish-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 12px 16px;
          border-bottom: 1px solid #f0f0f0;
          padding-top: calc(12px + env(safe-area-inset-top, 0px));
        }
        .publish-close {
          font-size: 14px;
          color: #666;
          cursor: pointer;
          padding: 4px 8px;
        }
        .publish-title {
          font-size: 16px;
          font-weight: 600;
        }
        .publish-submit {
          padding: 6px 16px;
          border: none;
          border-radius: 20px;
          background: var(--primary-color, #2E7CF6);
          color: #fff;
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
        }
        .publish-submit.disabled {
          background: #ccc;
          cursor: not-allowed;
        }
        .publish-body {
          flex: 1;
          overflow-y: auto;
          padding: 16px;
        }
        .title-input {
          width: 100%;
          border: none;
          font-size: 22px;
          font-weight: 700;
          outline: none;
          margin-bottom: 12px;
          padding: 4px 0;
          box-sizing: border-box;
        }
        .title-input::placeholder { color: #ccc; }

        .cover-upload {
          margin-bottom: 12px;
        }
        .cover-upload-btn {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 120px;
          background: #f8f8f8;
          border: 2px dashed #ddd;
          border-radius: 8px;
          color: #999;
          font-size: 13px;
          cursor: pointer;
        }
        .cover-upload-icon {
          font-size: 32px;
          margin-bottom: 6px;
        }
        .cover-preview {
          position: relative;
          border-radius: 8px;
          overflow: hidden;
        }
        .cover-preview img {
          width: 100%;
          max-height: 200px;
          object-fit: cover;
          display: block;
        }
        .cover-remove {
          position: absolute;
          top: 8px;
          right: 8px;
          background: rgba(0,0,0,0.6);
          color: #fff;
          padding: 4px 10px;
          border-radius: 14px;
          font-size: 12px;
          cursor: pointer;
        }

        .editor-toolbar {
          display: flex;
          gap: 4px;
          padding: 8px;
          background: #f8f8f8;
          border-radius: 8px;
          margin-bottom: 8px;
          flex-wrap: wrap;
        }
        .editor-toolbar button {
          padding: 4px 10px;
          border: none;
          background: #fff;
          border-radius: 4px;
          font-size: 13px;
          color: #333;
          cursor: pointer;
          min-width: 32px;
        }
        .editor-toolbar button:active { background: #e8e8e8; }

        .content-editor {
          width: 100%;
          min-height: 250px;
          border: 1px solid #f0f0f0;
          border-radius: 8px;
          padding: 12px;
          font-size: 15px;
          line-height: 1.7;
          outline: none;
          resize: vertical;
          box-sizing: border-box;
          font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', sans-serif;
        }
        .content-editor:focus { border-color: var(--primary-color, #2E7CF6); }
        .content-editor::placeholder { color: #bbb; }

        .publish-settings {
          margin-top: 16px;
          background: #fafafa;
          border-radius: 10px;
          overflow: hidden;
        }
        .setting-row {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 14px 16px;
          border-bottom: 1px solid #f0f0f0;
          cursor: pointer;
        }
        .setting-row:last-child { border-bottom: none; }
        .setting-label {
          font-size: 14px;
          color: #333;
        }
        .setting-value {
          font-size: 13px;
          color: #999;
        }
        .setting-row-input {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 12px 16px;
          border-bottom: 1px solid #f0f0f0;
          gap: 12px;
        }
        .setting-row-input input {
          flex: 1;
          max-width: 180px;
          padding: 6px 10px;
          border: 1px solid #eee;
          border-radius: 6px;
          font-size: 14px;
          text-align: right;
          outline: none;
          background: #fff;
        }
        .price-input-wrap {
          display: flex;
          align-items: center;
        }
        .price-symbol {
          font-size: 15px;
          color: #ff6b00;
          margin-right: 4px;
          font-weight: 600;
        }
        .price-input-wrap input {
          width: 100px;
          text-align: left;
        }

        /* Switch 开关 */
        .switch {
          position: relative;
          display: inline-block;
          width: 44px;
          height: 26px;
        }
        .switch input {
          opacity: 0;
          width: 0;
          height: 0;
        }
        .slider {
          position: absolute;
          cursor: pointer;
          inset: 0;
          background-color: #ccc;
          transition: .3s;
          border-radius: 26px;
        }
        .slider:before {
          position: absolute;
          content: "";
          height: 20px;
          width: 20px;
          left: 3px;
          bottom: 3px;
          background-color: white;
          transition: .3s;
          border-radius: 50%;
        }
        input:checked + .slider {
          background-color: var(--primary-color, #2E7CF6);
        }
        input:checked + .slider:before {
          transform: translateX(18px);
        }

        .publish-tip {
          margin-top: 16px;
          padding: 12px;
          background: #fff8e6;
          border-radius: 8px;
          font-size: 12px;
          color: #996600;
          line-height: 1.5;
        }

        /* Sheet 选项 */
        .sheet-options {
          padding: 8px 0;
        }
        .sheet-option {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 14px 20px;
          font-size: 15px;
          color: #333;
          cursor: pointer;
        }
        .sheet-option:active {
          background: #f5f5f5;
        }
        .sheet-option.active {
          color: var(--primary-color, #2E7CF6);
        }
        .sheet-option .check {
          color: var(--primary-color, #2E7CF6);
          font-weight: 600;
        }
        .visibility-option {
          align-items: flex-start;
        }
        .visibility-option-left {
          display: flex;
          gap: 12px;
          align-items: center;
        }
        .visibility-icon {
          font-size: 24px;
          width: 36px;
          text-align: center;
        }
        .visibility-label {
          font-size: 15px;
          font-weight: 500;
          color: #333;
        }
        .visibility-desc {
          font-size: 12px;
          color: #999;
          margin-top: 2px;
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { ArticlePublishPage });
