// =========================================================
// FBIF 资讯订阅 · Left rails
// IconRail  — far-left app nav with labels, logo + views
// FeedRail  — subscription / topic navigation (the filter column)
// =========================================================

const RailIcon = ({ icon, label, shortLabel, active, badge, onClick }) => {
  const [hover, setHover] = React.useState(false);
  const text = shortLabel || label;
  return (
    <button onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      title={label} aria-label={label} aria-current={active ? 'page' : undefined}
      style={{
        position: 'relative', width: 64, height: 52, margin: '2px 0', borderRadius: 8, border: 'none',
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        gap: 2, cursor: 'pointer', padding: '4px 2px',
        background: active ? '#EBF1FE' : hover ? '#F2F3F5' : 'transparent',
        color: active ? '#1456F0' : '#646A73', transition: 'background-color .15s ease',
        outline: 'none', boxShadow: 'none', fontFamily: 'inherit', boxSizing: 'border-box',
      }}
      onFocus={e => { e.currentTarget.style.boxShadow = '0 0 0 3px rgba(20,86,240,.18)'; }}
      onBlur={e => { e.currentTarget.style.boxShadow = 'none'; }}>
      <Icon name={icon} size={18} />
      <span style={{
        minWidth: 0, maxWidth: '100%', fontSize: 11, lineHeight: '14px',
        fontWeight: active ? 600 : 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
      }}>{text}</span>
      {badge != null && badge > 0 && (
        <span style={{
          position: 'absolute', top: 5, right: 9, minWidth: 7, height: 7, borderRadius: 9999,
          background: '#F54A45', border: '1.5px solid #fff',
        }} />
      )}
    </button>
  );
};

const IconRail = ({ view, onNavigate }) => {
  useLucide();
  return (
    <div style={{
      width: 76, flexShrink: 0, background: '#fff', borderRight: '1px solid #DEE0E3',
      display: 'flex', flexDirection: 'column', alignItems: 'center', height: '100%',
    }}>
      <div style={{ height: 56, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <img src="assets/logo-fbif.png" alt="FBIF" style={{ width: 28, height: 28, objectFit: 'contain' }} />
      </div>
      <Divider style={{ width: 48 }} />
      <nav style={{ flex: 1, paddingTop: 8, display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
        <RailIcon icon="newspaper"   label="时间线"   shortLabel="时间线" active={view === 'timeline'}  onClick={() => onNavigate('timeline')} badge={1} />
        <RailIcon icon="rss"         label="订阅管理" shortLabel="订阅"   active={view === 'manage'}    onClick={() => onNavigate('manage')} />
        <RailIcon icon="tags"        label="标签管理" shortLabel="标签"   active={view === 'tags'}      onClick={() => onNavigate('tags')} />
        <RailIcon icon="bar-chart-3" label="数据看板" shortLabel="看板"   active={view === 'analytics'} onClick={() => onNavigate('analytics')} />
      </nav>
      <div style={{ paddingBottom: 8, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
        <RailIcon icon="settings" label="设置" shortLabel="设置" active={view === 'settings'} onClick={() => onNavigate('settings')} />
      </div>
    </div>
  );
};

// ---- FeedRail ----------------------------------------------------------

const RailRow = ({ icon, mark, label, count, active, muted, onClick, indent, accent }) => {
  const [hover, setHover] = React.useState(false);
  const bg = active ? '#EBF1FE' : hover ? '#F2F3F5' : 'transparent';
  return (
    <div onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', alignItems: 'center', gap: 8, height: 30, borderRadius: 6, cursor: 'pointer',
        padding: `0 8px 0 ${indent ? 20 : 8}px`, margin: '1px 8px', background: bg,
        color: active ? '#0F4DD1' : '#1F2329', fontWeight: active ? 500 : 400, fontSize: 13,
      }}>
      {icon && <Icon name={icon} size={16} color={active ? '#1456F0' : accent || '#646A73'} />}
      {mark}
      <span style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                     color: muted ? '#8F959E' : undefined }}>{label}</span>
      {count != null && count > 0 && (
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: 11, color: active ? '#0F4DD1' : '#8F959E',
          minWidth: 18, textAlign: 'right',
        }}>{count}</span>
      )}
    </div>
  );
};

const RailGroup = ({ label, action, children, defaultOpen = true }) => {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div style={{ marginTop: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', padding: '2px 16px 2px 12px' }}>
        <div onClick={() => setOpen(o => !o)} style={{ display: 'flex', alignItems: 'center', gap: 2, cursor: 'pointer', flex: 1, color: '#8F959E' }}>
          <Icon name={open ? 'chevron-down' : 'chevron-right'} size={12} />
          <span style={{ fontSize: 11, fontWeight: 500, letterSpacing: '.02em' }}>{label}</span>
        </div>
        {action}
      </div>
      {open && children}
    </div>
  );
};

const FeedRail = ({ data, scope, onScope, onManage, onTags, counts, onCollapse }) => {
  useLucide();
  const subTags    = data.TAGS.filter(t => t.subscribed);
  const subSources = data.SOURCES.filter(s => s.subscribed);
  const byTier = { 'T1': [], 'T1.5': [], 'T2': [] };
  subSources.forEach(s => byTier[s.tier].push(s));
  // Count per tag is currently source-level article count; personal state belongs to account features later.
  const tagCount = (tagId) => subSources.filter(s => s.tags.includes(tagId)).reduce((a, s) => a + (s.article_count || 0), 0);

  return (
    <div style={{
      width: 244, flexShrink: 0, background: '#fff', borderRight: '1px solid #DEE0E3',
      display: 'flex', flexDirection: 'column', height: '100%',
    }}>
      {/* header */}
      <div style={{ height: 56, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 12px 0 16px', borderBottom: '1px solid #DEE0E3', flexShrink: 0 }}>
        <span style={{ fontSize: 15, fontWeight: 600, color: '#1F2329' }}>资讯订阅</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <Button variant="ghost" size="dense" icon="plus" title="添加订阅" onClick={onManage} />
          {onCollapse && <Button variant="ghost" size="dense" icon="panel-left-close" title="收起" onClick={onCollapse} />}
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 16 }}>
        {/* home */}
        <div style={{ paddingTop: 10 }}>
          <RailRow icon="newspaper" label="时间线" active={scope.type === 'timeline'} onClick={() => onScope({ type: 'timeline' })} count={counts.total} accent="#1456F0" />
        </div>

        <Divider style={{ width: 'calc(100% - 24px)', margin: '8px 12px' }} />

        {/* tags (用户标签) */}
        <RailGroup label="我的标签" action={<Button variant="ghost" size="dense" icon="settings-2" title="标签管理" onClick={onTags} />}>
          {subTags.map(t => (
            <RailRow key={t.id}
              mark={<span style={{ width: 16, display: 'inline-flex', justifyContent: 'center', flexShrink: 0 }}><span style={{ width: 8, height: 8, borderRadius: 9999, background: t.color }} /></span>}
              label={t.name} count={tagCount(t.id)}
              active={scope.type === 'tag' && scope.id === t.id}
              onClick={() => onScope({ type: 'tag', id: t.id, name: t.name })} />
          ))}
          {subTags.length === 0 && <div style={{ padding: '4px 18px', fontSize: 12, color: '#BBBFC4' }}>暂无标签</div>}
        </RailGroup>

        {/* sources grouped by tier */}
        <RailGroup label="我的来源" action={<Button variant="ghost" size="dense" icon="plus" title="添加来源" onClick={onManage} />}>
          {['T1', 'T1.5', 'T2'].map(tier => byTier[tier].length > 0 && (
            <div key={tier}>
              <div style={{ padding: '4px 16px 2px 20px', display: 'flex', alignItems: 'center', gap: 6 }}>
                <TierTag tier={tier} compact />
                <span style={{ fontSize: 11, color: '#BBBFC4' }}>{data.TIER_META[tier].label.split('·')[1]}</span>
              </div>
              {byTier[tier].map(s => (
                <RailRow key={s.id}
                  mark={<span style={{ position: 'relative', display: 'inline-flex', flexShrink: 0 }}>
                    <SourceMark short={s.short} color={s.color} size={18} />
                    {s.health !== 'healthy' && <span title={(s.health === 'failed' ? '失效' : '异常')} style={{ position: 'absolute', top: -2, right: -2, width: 7, height: 7, borderRadius: 9999, background: s.health === 'failed' ? '#F54A45' : '#FF8800', border: '1.5px solid #fff' }} />}
                  </span>}
                  label={s.name.replace(/\s*·.*/, '').replace(/\s*Newsroom/, '')} count={s.article_count} indent
                  active={scope.type === 'source' && scope.id === s.id}
                  onClick={() => onScope({ type: 'source', id: s.id, name: s.name })} />
              ))}
            </div>
          ))}
        </RailGroup>
      </div>

      {/* footer */}
      <div style={{ borderTop: '1px solid #DEE0E3', padding: '8px 16px', flexShrink: 0 }}>
        {(() => {
          const failed = subSources.filter(s => s.health === 'failed').length;
          const degraded = subSources.filter(s => s.health === 'degraded').length;
          const bad = failed + degraded;
          return (
            <div onClick={bad ? onManage : undefined} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: '#8F959E', cursor: bad ? 'pointer' : 'default' }}>
              <span style={{ width: 6, height: 6, borderRadius: 9999, flexShrink: 0, background: failed ? '#F54A45' : degraded ? '#FF8800' : '#00A870' }} />
              {bad
                ? <span style={{ color: failed ? '#B83430' : '#B45F00' }}>{failed ? `${failed} 个来源失效` : `${degraded} 个来源异常`} · 去处理</span>
                : <span>{subSources.length} 个来源 · {subTags.length} 个标签 · 全部正常</span>}
            </div>
          );
        })()}
      </div>
    </div>
  );
};

Object.assign(window, { IconRail, FeedRail, RailRow, RailGroup });
