// Alerts Center — timeline-milestone alerts (50/80/95%) + under-KPI per booking.
// Reads directly from PulseStore.getAlerts() which recomputes from live data.
const { useState: useStateA } = React;

const AlertsCenter = () => {
  const t = useT();
  const [filter, setFilter] = useStateA('open');
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    const h = () => force();
    window.addEventListener('pulse-data-change', h);
    return () => window.removeEventListener('pulse-data-change', h);
  }, []);

  const all = (window.PulseStore ? window.PulseStore.getAlerts() : []);
  const filtered = filter === 'all' ? all : all.filter(a => a.status === filter);
  const openCount = all.filter(a => a.status === 'open').length;
  const resolvedCount = all.filter(a => a.status === 'resolved').length;
  const underKpiCount = all.filter(a => a.type === 'under_kpi' && a.status === 'open').length;

  return (
    <div style={{ padding: '24px 20px 64px', maxWidth: 1400, margin: '0 auto' }} className="pulse-page">
      <div style={{ marginBottom: 28 }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(28px, 5vw, 44px)', fontWeight: 400, margin: 0, letterSpacing: 0, textTransform: 'uppercase' }}>{t('al.title')}</h1>
        <div style={{ fontSize: 14, color: 'var(--ink-500)', marginTop: 6 }}>{t('al.subtitle')}</div>
      </div>

      {/* Summary cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12, marginBottom: 20 }}>
        <AlertSummary label={t('al.open')} value={openCount} icon="alert" accent="brand"/>
        <AlertSummary label={t('al.under_kpi')} value={underKpiCount} icon="trending-down" accent="brand"/>
        <AlertSummary label={t('al.resolved_week')} value={resolvedCount} icon="check" accent="ink"/>
        <AlertSummary label={t('al.resp_time')} value="2.4h" icon="zap" accent="ink"/>
      </div>

      {/* Rules config */}
      <div className="panel" style={{ padding: 16, marginBottom: 20, background: 'var(--bg-panel)', borderLeft: '3px solid var(--brand-500)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
          <div style={{ width: 36, height: 36, borderRadius: 6, background: 'var(--brand-500)', color: 'white', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
            <Icon name="sparkle" size={16}/>
          </div>
          <div style={{ flex: 1, minWidth: 200 }}>
            <div style={{ fontSize: 14, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.02em' }}>{t('al.rules_active')}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-600)', marginTop: 2 }}>{t('al.rules_sub')}</div>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <MilestoneChip pct={50} sev="low"/>
            <MilestoneChip pct={80} sev="med"/>
            <MilestoneChip pct={95} sev="high"/>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, borderBottom: '1px solid var(--border)', marginBottom: 12, overflowX: 'auto' }}>
        {[
          { k: 'open', l: t('al.filter_open'), n: openCount },
          { k: 'resolved', l: t('al.filter_resolved'), n: resolvedCount },
          { k: 'all', l: t('al.filter_all'), n: all.length },
        ].map(tab => (
          <button key={tab.k} onClick={() => setFilter(tab.k)} style={{
            padding: '10px 14px', fontSize: 13,
            color: filter === tab.k ? 'var(--ink-900)' : 'var(--ink-500)',
            fontWeight: 600,
            borderBottomWidth: 2, borderBottomStyle: 'solid',
            borderBottomColor: filter === tab.k ? 'var(--brand-500)' : 'transparent',
            marginBottom: -1,
            display: 'flex', alignItems: 'center', gap: 6,
            whiteSpace: 'nowrap',
            textTransform: 'uppercase', letterSpacing: '0.04em',
          }}>
            {tab.l}
            <span style={{
              fontSize: 11,
              background: filter === tab.k ? 'var(--brand-500)' : 'var(--ink-100)',
              color: filter === tab.k ? 'white' : 'var(--ink-600)',
              padding: '1px 7px', borderRadius: 999, fontWeight: 700,
            }}>{tab.n}</span>
          </button>
        ))}
      </div>

      {/* List */}
      <div className="panel" style={{ padding: 0 }}>
        {filtered.map((a, i) => (
          <AlertRow key={a.id} alert={a} last={i === filtered.length - 1}/>
        ))}
        {filtered.length === 0 && (
          <div style={{ padding: '60px 20px', textAlign: 'center', color: 'var(--ink-500)' }}>
            <Icon name="check" size={24} style={{ color: 'var(--ink-900)', display: 'block', margin: '0 auto 8px' }}/>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-700)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{t('al.no_alerts')}</div>
          </div>
        )}
      </div>
    </div>
  );
};

const MilestoneChip = ({ pct, sev }) => {
  const sevBg = sev === 'high' ? 'var(--brand-500)' : sev === 'med' ? 'var(--bg-inverse)' : 'var(--ink-200)';
  const sevFg = sev === 'high' ? '#FFFFFF' : sev === 'med' ? 'var(--text-inverse)' : 'var(--text-primary)';
  return (
    <span style={{
      fontFamily: 'var(--font-mono)',
      fontSize: 11, fontWeight: 700,
      padding: '4px 10px',
      background: sevBg, color: sevFg,
      letterSpacing: '0.1em',
    }}>{pct}%</span>
  );
};

const AlertSummary = ({ label, value, icon, accent }) => {
  const bg = accent === 'brand' ? 'var(--brand-100)' : 'var(--ink-100)';
  const fg = accent === 'brand' ? 'var(--brand-600)' : 'var(--text-primary)';
  return (
    <div className="panel" style={{ padding: 18 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 14 }}>
        <div style={{ width: 32, height: 32, borderRadius: 6, background: bg, color: fg, display: 'grid', placeItems: 'center' }}>
          <Icon name={icon} size={16}/>
        </div>
      </div>
      <div className="num" style={{ fontSize: 28, fontWeight: 600, letterSpacing: 0, lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 11, color: 'var(--ink-500)', marginTop: 6, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700 }}>{label}</div>
    </div>
  );
};

const AlertRow = ({ alert, last }) => {
  const t = useT();
  const resolved = alert.status === 'resolved';
  const sevColor = alert.severity === 'high' ? 'var(--brand-500)'
                 : alert.severity === 'med'  ? 'var(--ink-900)'
                 :                              'var(--ink-500)';

  // Compose title + subtitle per alert type
  let title = '';
  let iconName = 'alert';
  if (alert.type === 'timeline') {
    const key = alert.milestone === 50 ? 'al.msg.timeline_50'
              : alert.milestone === 80 ? 'al.msg.timeline_80'
              :                          'al.msg.timeline_95';
    title = t(key, { pct: alert.kpiPct });
    iconName = 'trending-down';
  } else if (alert.type === 'under_kpi') {
    title = t('al.msg.timeline_80', { pct: alert.kpiPct }); // reuse message
    iconName = 'trending-down';
  } else if (alert.type === 'stale_data') {
    title = t('sync.stale_alert', { n: alert.staleCount });
    iconName = 'refresh';
  }

  const resolve = () => window.PulseStore && window.PulseStore.resolveAlert(alert.id);
  const reopen  = () => window.PulseStore && window.PulseStore.reopenAlert(alert.id);

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '16px 20px',
      borderBottomWidth: last ? 0 : 1, borderBottomStyle: 'solid', borderBottomColor: 'var(--border)',
      opacity: resolved ? 0.55 : 1,
      flexWrap: 'wrap',
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 6,
        background: resolved ? 'var(--ink-100)' : (alert.severity === 'high' ? 'var(--brand-100)' : 'var(--ink-100)'),
        color:      resolved ? 'var(--ink-700)' : sevColor,
        display: 'grid', placeItems: 'center', flexShrink: 0,
      }}>
        <Icon name={resolved ? 'check' : iconName} size={16} stroke={2}/>
      </div>

      {alert.influencer && (
        <img src={alert.influencer.avatar} alt="" style={{ width: 32, height: 32, borderRadius: 8, flexShrink: 0, objectFit: 'cover' }}/>
      )}
      {!alert.influencer && alert.brandColor && (
        <div style={{ width: 32, height: 32, borderRadius: 6, background: alert.brandColor, flexShrink: 0, display: 'grid', placeItems: 'center', color: '#FFF', fontFamily: 'var(--font-display)', fontSize: 14 }}>
          {(alert.brand || 'C').charAt(0)}
        </div>
      )}

      <div style={{ flex: 1, minWidth: 180 }}>
        {alert.influencer ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 13, fontWeight: 600 }}>{alert.influencer.name}</span>
            <span style={{ fontSize: 11, color: 'var(--ink-400)' }}>{alert.influencer.handle}</span>
          </div>
        ) : (
          <div style={{ fontSize: 13, fontWeight: 600 }}>{alert.campaignName}</div>
        )}
        <div style={{ fontSize: 13, color: 'var(--ink-700)', lineHeight: 1.4 }}>{title}</div>
        <div style={{ fontSize: 10, color: 'var(--ink-500)', marginTop: 4, display: 'flex', gap: 8, flexWrap: 'wrap', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700 }}>
          {alert.type === 'timeline' && <span>{t('al.type.timeline')} · {alert.milestone}%</span>}
          {alert.type === 'under_kpi' && <span>{t('al.type.under_kpi')}</span>}
          {alert.type === 'stale_data' && <span>{t('admin.ingestion_title')}</span>}
          <span>·</span>
          <span>{alert.campaignName}</span>
          <span>·</span>
          <span>{alert.raisedAt}</span>
        </div>
      </div>

      <span style={{
        fontFamily: 'var(--font-mono)',
        fontSize: 10, fontWeight: 700,
        padding: '4px 8px',
        background: alert.severity === 'high' ? 'var(--brand-500)' : alert.severity === 'med' ? 'var(--bg-inverse)' : 'var(--ink-200)',
        color: alert.severity === 'high' ? '#FFFFFF' : alert.severity === 'med' ? 'var(--text-inverse)' : 'var(--text-primary)',
        letterSpacing: '0.1em', textTransform: 'uppercase',
      }}>
        {alert.severity === 'high' ? t('al.severity_high') : alert.severity === 'med' ? t('al.severity_med') : t('al.severity_low')}
      </span>

      {!resolved && (
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn" style={{ fontSize: 12 }} onClick={resolve}>
            <Icon name="check" size={13}/> {t('action.resolve')}
          </button>
        </div>
      )}
      {resolved && (
        <button className="btn ghost" style={{ fontSize: 12 }} onClick={reopen}>
          <Icon name="refresh" size={12}/> {t('al.resolved')}
        </button>
      )}
    </div>
  );
};

Object.assign(window, { AlertsCenter });
