// =========================================================
// FBIF 资讯订阅 · 设置 (Settings backend)
// Hosts the 失效提醒 · 飞书机器人 config (moved out of 订阅管理,
// so it's no longer always-on there), plus push/quota info and
// placeholder rows for account / supplier API / quality thresholds.
// =========================================================

const SettingsSection = ({ icon, title, desc, children, right }) => (
  <section style={{ border: '1px solid #DEE0E3', borderRadius: 8, background: '#fff', marginBottom: 16 }}>
    <header style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderBottom: children ? '1px solid #EDEFF2' : 'none' }}>
      <span style={{ width: 28, height: 28, borderRadius: 7, background: '#EBF1FE', color: '#1456F0', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name={icon} size={16} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: '#1F2329' }}>{title}</div>
        {desc && <div style={{ fontSize: 12, color: '#8F959E', marginTop: 1 }}>{desc}</div>}
      </div>
      {right}
    </header>
    {children && <div style={{ padding: 16 }}>{children}</div>}
  </section>
);

const InfoRow = ({ label, value, mono }) => (
  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '10px 0', borderBottom: '1px solid #F2F3F5' }}>
    <span style={{ fontSize: 13, color: '#646A73' }}>{label}</span>
    <span style={{ fontSize: 13, color: '#1F2329', fontFamily: mono ? 'var(--font-mono)' : 'inherit' }}>{value}</span>
  </div>
);

const PlaceholderRow = ({ icon, label, hint }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: '1px solid #F2F3F5' }}>
    <Icon name={icon} size={16} color="#8F959E" />
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13, color: '#1F2329' }}>{label}</div>
      <div style={{ fontSize: 12, color: '#8F959E' }}>{hint}</div>
    </div>
    <Tag tone="neutral" style={{ height: 20, fontSize: 11, lineHeight: '20px' }}>即将上线</Tag>
  </div>
);

const SettingsPage = ({ data, alertCfg, onAlertCfg, onTestPush, onRecheck, onManage, onClose }) => {
  useLucide();
  const [strat, setStrat] = React.useState({ retry3: true, recover: true, daily: false, tierOnly: false });
  const failed = data.SOURCES.filter(s => s.subscribed && s.health === 'failed');
  const degraded = data.SOURCES.filter(s => s.subscribed && s.health === 'degraded');
  const bad = [...failed, ...degraded];

  return (
    <div style={{ flex: 1, minWidth: 0, height: '100%', overflowY: 'auto', background: '#F5F6F7' }}>
      <div style={{ background: '#fff', borderBottom: '1px solid #DEE0E3' }}>
        <div style={{ maxWidth: 880, margin: '0 auto', width: '100%', padding: '20px 32px' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
            <div>
              <h1 style={{ fontSize: 24, lineHeight: '32px', fontWeight: 600, color: '#1F2329', margin: 0 }}>设置</h1>
              <p style={{ fontSize: 13, color: '#646A73', margin: '6px 0 0' }}>来源健康提醒、推送与配额，以及组织与接口配置。</p>
            </div>
            <Button variant="text" icon="arrow-left" onClick={onClose}>返回时间线</Button>
          </div>
        </div>
      </div>

      <div style={{ maxWidth: 880, margin: '0 auto', width: '100%', padding: '20px 32px 40px' }}>
        {/* 失效提醒 · 飞书机器人 */}
        <SettingsSection icon="bell-ring" title="失效提醒 · 飞书机器人" desc="来源连续拉取失败时，自动推送到飞书群并 @ 值班同学"
          right={<Switch on={alertCfg.enabled} onChange={(v) => onAlertCfg({ ...alertCfg, enabled: v })} />}>
          <div style={{ opacity: alertCfg.enabled ? 1 : .5, pointerEvents: alertCfg.enabled ? 'auto' : 'none' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
              <div style={{ flex: 1, minWidth: 260, display: 'flex' }}>
                <Input icon="webhook" placeholder="飞书群机器人 Webhook https://open.feishu.cn/open-apis/bot/v2/hook/…" value={alertCfg.webhook} onChange={e => onAlertCfg({ ...alertCfg, webhook: e.target.value })} width="100%" height={36} />
              </div>
              <Button variant="secondary" size="large" icon="send" onClick={onTestPush}>测试推送</Button>
            </div>
            {/* trigger conditions */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 12, flexWrap: 'wrap' }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: '#646A73' }}>
                <Icon name="circle-x" size={14} color="#F54A45" /> 来源失效时提醒
              </label>
              <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: '#646A73' }}>
                <Icon name="triangle-alert" size={14} color="#FF8800" /> 来源异常时提醒
              </label>
              <span style={{ fontSize: 12, color: '#8F959E' }}>凭证仅服务端保存，不在前端展示。</span>
            </div>

            {/* 提醒策略 */}
            <div style={{ marginTop: 14 }}>
              <div style={{ fontSize: 12, color: '#8F959E', marginBottom: 8 }}>提醒策略</div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {[['retry3', '连续失败 3 次才提醒'], ['recover', '恢复后提醒'], ['daily', '每日汇总一次'], ['tierOnly', '仅 T1 / T1.5 来源']].map(([k, l]) => {
                  const on = strat[k];
                  return (
                    <button key={k} onClick={() => setStrat(s => ({ ...s, [k]: !s[k] }))}
                      style={{ display: 'inline-flex', alignItems: 'center', gap: 6, height: 28, padding: '0 10px', borderRadius: 9999, cursor: 'pointer', fontSize: 12, fontFamily: 'inherit',
                               border: `1px solid ${on ? '#1456F0' : '#DEE0E3'}`, background: on ? '#EBF1FE' : '#fff', color: on ? '#0F4DD1' : '#646A73' }}>
                      <Icon name={on ? 'check' : 'plus'} size={12} />{l}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* 最近一次推送 */}
            <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', background: '#F7F8FA', borderRadius: 6, fontSize: 12, color: '#646A73' }}>
              <Icon name="history" size={14} color="#8F959E" />
              最近一次推送：今天 09:12 · FoodBev Media 失效 · 已送达飞书群「资讯运营」
            </div>

            {/* current health */}
            <div style={{ marginTop: 14, border: '1px solid #EDEFF2', borderRadius: 8, overflow: 'hidden' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', background: '#F7F8FA', borderBottom: bad.length ? '1px solid #EDEFF2' : 'none' }}>
                <span style={{ fontSize: 12, color: '#646A73', flex: 1 }}>当前来源健康</span>
                <Button variant="text" size="dense" icon="refresh-cw" onClick={() => onRecheck(null)}>重新检查全部</Button>
              </div>
              {bad.length === 0 && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '12px', fontSize: 13, color: '#007A52' }}>
                  <Icon name="circle-check-big" size={15} color="#00A870" /> 全部订阅来源运行正常
                </div>
              )}
              {bad.map(s => (
                <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderBottom: '1px solid #F2F3F5' }}>
                  <SourceMark short={s.short} color={s.color} size={24} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, color: '#1F2329' }}>{s.name}</div>
                    <div style={{ fontSize: 12, color: '#8F959E' }}>{s.healthNote || `最近更新 ${timeAgo(s.lastUpdate)}`}</div>
                  </div>
                  <HealthBadge health={s.health} />
                  <Button variant="secondary" size="dense" onClick={() => onRecheck(s)}>检查</Button>
                </div>
              ))}
            </div>
          </div>
        </SettingsSection>

        {/* 推送与配额 */}
        <SettingsSection icon="gauge" title="推送与配额" desc="来自供应商 API（企业级服务）">
          <InfoRow label="推送模式" value="推模式 · 95% 分钟级推送" />
          <InfoRow label="RSS 每日调用额度" value="300 次 / 天" mono />
          <InfoRow label="拉取兜底" value="推 + 拉双模式" />
          <InfoRow label="服务隔离" value="企业级独立部署" />
        </SettingsSection>

        {/* placeholders */}
        <SettingsSection icon="settings" title="组织与接口" desc="接入飞书后按角色开放">
          <PlaceholderRow icon="users" label="组织成员与角色" hint="管理员可配置来源、调整精选阈值" />
          <PlaceholderRow icon="plug" label="供应商 API 接入" hint="今天看啥企业级 API 凭证（服务端）" />
          <PlaceholderRow icon="sliders-horizontal" label="质量过滤阈值" hint="按信源等级设置精选分数线" />
          <PlaceholderRow icon="log-in" label="飞书身份接入" hint="M5 阶段启用角色权限" />
        </SettingsSection>

        <p style={{ fontSize: 12, color: '#BBBFC4', margin: '4px 2px 0', lineHeight: '18px' }}>
          来源的健康检查与失效提醒在「订阅管理」中也可单独操作；此处为统一的后台配置入口。
        </p>
      </div>
    </div>
  );
};

Object.assign(window, { SettingsPage });
