// Admin SEO Settings Page
// 管理后台：全站 SEO 设置

const { useState, useEffect, useCallback, Component } = React;

class AdminSEOErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorInfo: '' };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, errorInfo: error?.message || '' };
  }
  componentDidCatch(error, errorInfo) {
    console.error('[AdminSEO] 渲染错误:', error, errorInfo);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div style={{ padding: 40, textAlign: 'center', color: '#999' }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>⚠️</div>
          <div>页面加载异常：{this.state.errorInfo}</div>
        </div>
      );
    }
    return this.props.children;
  }
}

function AdminSEOSettings() {
  let navigate = () => {};
  let showToast = (msg) => console.log('[toast]', msg);
  let requireLogin = (cb) => { showToast('请先登录'); return false; };

  try {
    const app = useApp ? useApp() : {};
    navigate = app.navigate || (() => {});
    showToast = app.showToast || ((msg) => console.log('[toast]', msg));
    requireLogin = app.requireLogin || ((cb) => { showToast('请先登录'); return false; });
  } catch (e) {
    console.error('[AdminSEO] useApp error:', e);
  }

  const [settings, setSettings] = useState({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [activeSection, setActiveSection] = useState('global'); // global | pages

  const loadSettings = useCallback(async () => {
    try {
      setLoading(true);
      const res = await API.get('/settings');
      if (res && res.success && res.data) {
        setSettings(res.data);
      }
    } catch (e) {
      console.error('loadSettings error:', e);
      showToast('加载设置失败');
    } finally {
      setLoading(false);
    }
  }, [showToast]);

  useEffect(() => {
    loadSettings();
  }, [loadSettings]);

  const handleChange = (key, value) => {
    setSettings(prev => ({ ...prev, [key]: value }));
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      const res = await API.post('/settings', settings);
      if (res && res.success) {
        showToast('设置已保存');
        // 立即刷新 SEO Manager 的缓存
        if (window.SEO) {
          window.SEO.loadSettings();
        }
      } else {
        showToast(res?.message || '保存失败');
      }
    } catch (e) {
      console.error('saveSettings error:', e);
      showToast('保存失败');
    } finally {
      setSaving(false);
    }
  };

  const globalFields = [
    { key: 'site_name', label: '站点名称', placeholder: '久存网', hint: '显示在浏览器标签和分享标题中' },
    { key: 'site_title_suffix', label: '标题后缀', placeholder: ' - 久存网', hint: '自动附加在所有页面标题末尾' },
    { key: 'site_description', label: '默认站点描述', placeholder: '', hint: '页面未单独设置描述时使用', rows: 3 },
    { key: 'site_keywords', label: '默认关键词', placeholder: '', hint: '英文逗号分隔', rows: 2 },
    { key: 'og_image', label: '默认分享图片', placeholder: 'https://...', hint: '社交分享时显示的默认缩略图 URL' },
  ];

  const pageSEOFields = [
    { prefix: 'seo_home', label: '站点首页' },
    { prefix: 'seo_feed', label: '说说广场' },
    { prefix: 'seo_article', label: '文章广场' },
    { prefix: 'seo_video', label: '视频广场' },
    { prefix: 'seo_archive', label: '存档广场' },
    { prefix: 'seo_memorial', label: '云纪念堂' },
    { prefix: 'seo_enterprise', label: '企业黄页' },
    { prefix: 'seo_love', label: '爱情空间' },
  ];

  const SettingField = ({ label, hint, value, onChange, placeholder, rows, type = 'text' }) => (
    <div style={{ marginBottom: 16 }}>
      <div style={{
        fontSize: 13,
        fontWeight: 500,
        color: 'var(--text-primary)',
        marginBottom: 6,
      }}>{label}</div>
      {rows > 1 ? (
        <textarea
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          rows={rows}
          style={{
            width: '100%',
            padding: '10px 12px',
            borderRadius: 8,
            border: '1px solid var(--border)',
            fontSize: 14,
            outline: 'none',
            resize: 'vertical',
            minHeight: rows * 24,
            boxSizing: 'border-box',
            fontFamily: 'inherit',
          }}
        />
      ) : (
        <input
          type={type}
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          style={{
            width: '100%',
            padding: '10px 12px',
            borderRadius: 8,
            border: '1px solid var(--border)',
            fontSize: 14,
            outline: 'none',
            boxSizing: 'border-box',
          }}
        />
      )}
      {hint && (
        <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 4 }}>{hint}</div>
      )}
    </div>
  );

  return (
    <AdminSEOErrorBoundary>
      <div style={{ minHeight: '100vh', background: 'var(--bg-page)' }}>
        {/* 顶部导航 */}
        <div style={{
          position: 'sticky', top: 0, zIndex: 20,
          background: 'var(--bg-card)',
          borderBottom: '1px solid var(--border)',
          padding: '14px 16px',
          display: 'flex',
          alignItems: 'center',
          gap: 12,
        }}>
          <div
            onClick={() => navigate('sitemap')}
            style={{ fontSize: 18, cursor: 'pointer', color: 'var(--text-primary)', width: 24 }}
          >←</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 17, fontWeight: 600, color: 'var(--text-primary)' }}>
              SEO 设置
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>
              优化搜索引擎收录与社交分享效果
            </div>
          </div>
        </div>

        {/* 分段 Tab */}
        <div style={{
          background: 'var(--bg-card)',
          borderBottom: '1px solid var(--border)',
          display: 'flex',
          padding: '0 16px',
        }}>
          {[
            { key: 'global', label: '全局设置' },
            { key: 'pages', label: '页面SEO' },
            { key: 'preview', label: '预览效果' },
          ].map(tab => (
            <div
              key={tab.key}
              onClick={() => setActiveSection(tab.key)}
              style={{
                padding: '12px 14px',
                fontSize: 13,
                fontWeight: activeSection === tab.key ? 600 : 400,
                color: activeSection === tab.key ? 'var(--primary)' : 'var(--text-secondary)',
                borderBottom: activeSection === tab.key
                  ? '2px solid var(--primary)'
                  : '2px solid transparent',
                cursor: 'pointer',
              }}
            >
              {tab.label}
            </div>
          ))}
        </div>

        {/* 内容区 */}
        <div style={{ padding: '16px' }}>
          {loading ? (
            <div style={{ textAlign: 'center', padding: '40px 0', color: 'var(--text-tertiary)' }}>
              加载中...
            </div>
          ) : (
            <>
              {/* 全局设置 */}
              {activeSection === 'global' && (
                <div style={{
                  background: 'var(--bg-card)',
                  borderRadius: 12,
                  padding: '16px',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
                }}>
                  <div style={{
                    fontSize: 14,
                    fontWeight: 600,
                    color: 'var(--text-primary)',
                    marginBottom: 16,
                  }}>
                    🌐 站点全局 SEO
                  </div>
                  {globalFields.map(f => (
                    <SettingField
                      key={f.key}
                      label={f.label}
                      hint={f.hint}
                      placeholder={f.placeholder}
                      value={settings[f.key]}
                      rows={f.rows}
                      onChange={(v) => handleChange(f.key, v)}
                    />
                  ))}
                </div>
              )}

              {/* 页面 SEO */}
              {activeSection === 'pages' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {pageSEOFields.map(page => (
                    <div
                      key={page.prefix}
                      style={{
                        background: 'var(--bg-card)',
                        borderRadius: 12,
                        padding: '16px',
                        boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
                      }}
                    >
                      <div style={{
                        fontSize: 14,
                        fontWeight: 600,
                        color: 'var(--text-primary)',
                        marginBottom: 14,
                      }}>
                        📄 {page.label}
                      </div>
                      <SettingField
                        label="页面标题（Title）"
                        placeholder={`${page.label} - 久存网`}
                        value={settings[`${page.prefix}_title`]}
                        onChange={(v) => handleChange(`${page.prefix}_title`, v)}
                        hint="浏览器标签标题，建议 30 字以内"
                      />
                      <SettingField
                        label="页面描述（Description）"
                        placeholder=""
                        rows={2}
                        value={settings[`${page.prefix}_description`]}
                        onChange={(v) => handleChange(`${page.prefix}_description`, v)}
                        hint="搜索结果摘要，建议 80-120 字"
                      />
                      <SettingField
                        label="关键词（Keywords）"
                        placeholder="关键词1,关键词2,关键词3"
                        value={settings[`${page.prefix}_keywords`]}
                        onChange={(v) => handleChange(`${page.prefix}_keywords`, v)}
                        hint="英文逗号分隔，建议 5-10 个"
                      />
                    </div>
                  ))}
                </div>
              )}

              {/* 预览效果 */}
              {activeSection === 'preview' && (
                <div style={{
                  background: 'var(--bg-card)',
                  borderRadius: 12,
                  padding: '16px',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
                }}>
                  <div style={{
                    fontSize: 14,
                    fontWeight: 600,
                    color: 'var(--text-primary)',
                    marginBottom: 16,
                  }}>
                    🔍 搜索结果预览
                  </div>

                  {/* 模拟搜索结果 */}
                  <div style={{
                    border: '1px solid var(--border)',
                    borderRadius: 8,
                    padding: '14px',
                    marginBottom: 12,
                    background: '#fff',
                  }}>
                    <div style={{
                      fontSize: 16,
                      color: '#1a0dab',
                      fontWeight: 500,
                      marginBottom: 4,
                      lineHeight: 1.3,
                    }}>
                      {settings.seo_home_title || settings.site_name || '久存网'}
                    </div>
                    <div style={{
                      fontSize: 12,
                      color: '#006621',
                      marginBottom: 6,
                    }}>
                      {window.location.hostname || 'www.jiucunwang.com'}
                    </div>
                    <div style={{
                      fontSize: 13,
                      color: '#545454',
                      lineHeight: 1.5,
                    }}>
                      {settings.seo_home_description || settings.site_description || ''}
                    </div>
                  </div>

                  <div style={{
                    fontSize: 12,
                    color: 'var(--text-tertiary)',
                    lineHeight: 1.6,
                    padding: '10px 12px',
                    background: 'var(--bg-page)',
                    borderRadius: 8,
                  }}>
                    <div style={{ fontWeight: 500, color: 'var(--text-secondary)', marginBottom: 4 }}>
                      💡 SEO 小提示
                    </div>
                    • 标题控制在 30 字以内，描述控制在 120 字以内<br/>
                    • 关键词以英文逗号分隔，与页面内容强相关<br/>
                    • 内容详情页会根据内容自动生成 SEO 标签<br/>
                    • 发布文章/纪念堂/企业时可自定义 SEO 覆盖默认值
                  </div>
                </div>
              )}
            </>
          )}
        </div>

        {/* 底部保存按钮 */}
        <div style={{
          position: 'sticky',
          bottom: 0,
          background: 'var(--bg-card)',
          padding: '12px 16px',
          borderTop: '1px solid var(--border)',
          boxShadow: '0 -2px 8px rgba(0,0,0,0.04)',
        }}>
          <button
            onClick={handleSave}
            disabled={saving}
            style={{
              width: '100%',
              padding: '12px 0',
              borderRadius: 10,
              border: 'none',
              background: saving ? '#aaa' : 'linear-gradient(135deg, var(--primary), #4080FF)',
              color: '#fff',
              fontSize: 15,
              fontWeight: 500,
              cursor: saving ? 'not-allowed' : 'pointer',
            }}
          >
            {saving ? '保存中...' : '保存设置'}
          </button>
        </div>
      </div>
    </AdminSEOErrorBoundary>
  );
}

Object.assign(window, { AdminSEOSettings });
