/* fraud-dashboard.jsx — Main dashboard view for fraud scoring */

const FraudDashboard = ({ transactions, alerts, metrics, mobile, demoRegion }) => {
  const regionCfg = REGION_CONFIG[demoRegion];

  return (
    <div style={{ flex: 1, overflow: 'auto', padding: mobile ? '16px 12px' : '24px 32px' }}>
      {/* Greeting */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: mobile ? 'flex-start' : 'flex-end', marginBottom: mobile ? 16 : 24, flexDirection: mobile ? 'column' : 'row', gap: mobile ? 4 : 0 }}>
        <div>
          <div style={{ fontSize: mobile ? 20 : 24, fontWeight: 700, color: ACME.text, fontFamily: ACME.font }}>Fraud Monitoring Center</div>
          <div style={{ fontSize: mobile ? 12 : 14, color: ACME.muted, marginTop: 4, fontFamily: ACME.font }}>
            Real-time transaction scoring · {regionCfg ? regionCfg.label : 'All regions'}
          </div>
        </div>
        {!mobile && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: ACME.subtle, fontFamily: ACME.font }}>
            <div style={{ width: 6, height: 6, borderRadius: 3, background: '#10B981', animation: 'pulse 2s infinite' }}></div>
            Scoring engine online · {metrics?.avgLatencyMs || 0}ms avg latency
          </div>
        )}
      </div>

      <style>{`@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }`}</style>

      {/* KPI Row */}
      <div style={{ display: 'flex', flexWrap: mobile ? 'wrap' : 'nowrap', gap: mobile ? 10 : 16, marginBottom: mobile ? 16 : 24 }}>
        <KpiCard
          label="Transactions Scanned"
          value={metrics?.totalScanned?.toLocaleString() || '0'}
          sub={`${metrics?.avgLatencyMs || 0}ms avg scoring latency`}
          subColor={ACME.success}
          accent="#3B82F6"
          mobile={mobile}
          icon={<svg width="20" height="20" fill="none" stroke={ACME.primary} strokeWidth="1.8" viewBox="0 0 24 24"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/></svg>}
        />
        <KpiCard
          label="Active Alerts"
          value={alerts?.filter(a => a.status !== 'resolved').length || 0}
          sub={`${alerts?.filter(a => a.severity === 'critical').length || 0} critical`}
          subColor={ACME.danger}
          accent="#EF4444"
          mobile={mobile}
          icon={<svg width="20" height="20" fill="none" stroke="#DC2626" strokeWidth="1.8" viewBox="0 0 24 24"><path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>}
        />
        <KpiCard
          label="Flagged Rate"
          value={`${(metrics?.flaggedRate || 0).toFixed(1)}%`}
          sub="of transactions flagged for review"
          subColor={ACME.muted}
          accent="#F59E0B"
          mobile={mobile}
          icon={<svg width="20" height="20" fill="none" stroke="#D97706" strokeWidth="1.8" viewBox="0 0 24 24"><path d="M3 21v-4m0 0V5a2 2 0 012-2h6.5l1 1H21l-3 6 3 6h-8.5l-1-1H5a2 2 0 00-2 2z"/></svg>}
        />
        <KpiCard
          label="Blocked Amount"
          value={`$${((metrics?.blockedAmount || 0) / 1000).toFixed(1)}K`}
          sub="prevented from fraudulent transactions"
          subColor={ACME.success}
          accent="#10B981"
          mobile={mobile}
          icon={<svg width="20" height="20" fill="none" stroke={ACME.primary} strokeWidth="1.8" viewBox="0 0 24 24"><path d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>}
        />
      </div>

      {/* Main Grid */}
      <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 360px', gap: 20 }}>
        {/* Left Column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          {/* Recent Alerts */}
          <div style={{ background: ACME.card, borderRadius: 12, boxShadow: '0 1px 3px rgba(0,0,0,0.06)', overflow: 'hidden' }}>
            <div style={{ padding: '16px 22px', borderBottom: '1px solid ' + ACME.border }}>
              <SectionHeader title="Active Alerts" subtitle="Transactions requiring immediate attention" action="View All" />
            </div>
            <div style={{ maxHeight: 320, overflow: 'auto' }}>
              {(alerts || []).filter(a => a.status !== 'resolved').slice(0, 5).map((alert) => (
                <div key={alert.id} style={{ padding: '14px 22px', borderBottom: '1px solid ' + ACME.border, display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer', transition: 'background 0.15s' }}
                  onMouseEnter={e => e.currentTarget.style.background = '#F9FAFB'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <div style={{ width: 36, height: 36, borderRadius: 10, background: SEVERITY_STYLES[alert.severity]?.bg || '#F3F4F6', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <svg width="18" height="18" fill="none" stroke={SEVERITY_STYLES[alert.severity]?.color || '#6B7280'} strokeWidth="2" viewBox="0 0 24 24">
                      <path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
                    </svg>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                      <span style={{ fontSize: 14, fontWeight: 600, color: ACME.text, fontFamily: ACME.font }}>{alert.type}</span>
                      <Badge label={alert.severity} styles={SEVERITY_STYLES[alert.severity] || SEVERITY_STYLES.medium} />
                    </div>
                    <div style={{ fontSize: 12, color: ACME.muted, fontFamily: ACME.font, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{alert.description}</div>
                  </div>
                  <div style={{ textAlign: 'right', flexShrink: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: ACME.text, fontFamily: ACME.font }}>{alert.amount > 0 ? `$${alert.amount.toLocaleString()}` : '—'}</div>
                    <div style={{ fontSize: 11, color: ACME.subtle, fontFamily: ACME.font }}>{formatTimeAgo(alert.timestamp)}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Transaction Feed */}
          <div style={{ background: ACME.card, borderRadius: 12, boxShadow: '0 1px 3px rgba(0,0,0,0.06)', overflow: 'hidden' }}>
            <div style={{ padding: mobile ? '12px 14px' : '16px 22px', borderBottom: '1px solid ' + ACME.border }}>
              <SectionHeader title="Transaction Feed" subtitle="Real-time scoring results" action="View All" />
            </div>
            {/* Table Header */}
            <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1.5fr 0.8fr 0.8fr 0.6fr' : '1.5fr 1.5fr 0.8fr 0.8fr 0.8fr 0.6fr', padding: mobile ? '10px 14px' : '10px 22px', borderBottom: '1px solid ' + ACME.border, fontSize: 11, fontWeight: 600, color: ACME.subtle, textTransform: 'uppercase', letterSpacing: 0.8, fontFamily: ACME.font }}>
              <span>Transaction</span>
              {!mobile && <span>Merchant</span>}
              <span>Amount</span>
              {!mobile && <span>Region</span>}
              <span>Risk</span>
              <span>Status</span>
            </div>
            <div style={{ maxHeight: 280, overflow: 'auto' }}>
              {(transactions || []).slice(0, 10).map((txn) => (
                <div key={txn.id} style={{ display: 'grid', gridTemplateColumns: mobile ? '1.5fr 0.8fr 0.8fr 0.6fr' : '1.5fr 1.5fr 0.8fr 0.8fr 0.8fr 0.6fr', padding: mobile ? '10px 14px' : '10px 22px', borderBottom: '1px solid ' + ACME.border, alignItems: 'center', fontSize: 13, fontFamily: ACME.font, transition: 'background 0.15s', cursor: 'pointer' }}
                  onMouseEnter={e => e.currentTarget.style.background = '#F9FAFB'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <div>
                    <div style={{ fontWeight: 600, color: ACME.text, fontSize: mobile ? 12 : 13 }}>{txn.id}</div>
                    <div style={{ fontSize: 11, color: ACME.subtle, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{mobile ? txn.merchant : `${txn.accountId} · ${txn.channel}`}</div>
                  </div>
                  {!mobile && <span style={{ color: ACME.text }}>{txn.merchant}</span>}
                  <span style={{ fontWeight: 600, fontFamily: 'monospace', color: txn.flagged ? ACME.danger : ACME.text, fontSize: mobile ? 12 : 13 }}>{txn.currency === 'USD' ? '$' : txn.currency === 'EUR' ? '€' : txn.currency === 'GBP' ? '£' : ''}{txn.amount.toLocaleString()}</span>
                  {!mobile && <span style={{ color: regionCfg ? regionCfg.color : ACME.muted, fontWeight: 600 }}>{txn.region}</span>}
                  <RiskScoreBar score={txn.riskScore} />
                  <Badge label={STATUS_STYLES[txn.status]?.label || txn.status} styles={STATUS_STYLES[txn.status] || STATUS_STYLES.cleared} />
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Right Column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          {/* Risk Distribution */}
          <div style={{ background: ACME.card, borderRadius: 12, padding: 22, boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>
            <SectionHeader title="Risk Distribution" subtitle="Current scoring breakdown" />
            {['low', 'medium', 'high', 'critical'].map((level) => {
              const count = metrics?.byRisk?.[level] || 0;
              const total = metrics?.totalScanned || 1;
              const pct = Math.round(count / total * 100);
              const colors = { low: '#10B981', medium: '#3B82F6', high: '#F59E0B', critical: '#EF4444' };
              return (
                <div key={level} style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
                  <div style={{ width: 8, height: 8, borderRadius: 4, background: colors[level], flexShrink: 0 }}></div>
                  <span style={{ fontSize: 13, fontWeight: 500, color: ACME.text, fontFamily: ACME.font, width: 60, textTransform: 'capitalize' }}>{level}</span>
                  <div style={{ flex: 1, height: 6, background: '#F3F4F6', borderRadius: 3, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: pct + '%', background: colors[level], borderRadius: 3, transition: 'width 0.6s ease' }}></div>
                  </div>
                  <span style={{ fontSize: 12, fontWeight: 600, color: ACME.muted, fontFamily: 'monospace', minWidth: 32, textAlign: 'right' }}>{pct}%</span>
                </div>
              );
            })}
          </div>

          {/* Model Info */}
          <div style={{ background: ACME.card, borderRadius: 12, padding: 22, boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>
            <SectionHeader title="Scoring Engine" subtitle="Model performance" />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                { label: 'Model', value: 'phi-4-ft-acme-fraud-v2' },
                { label: 'Precision', value: '96.8%' },
                { label: 'Recall', value: '94.2%' },
                { label: 'F1 Score', value: '95.5%' },
                { label: 'Avg Latency', value: `${metrics?.avgLatencyMs || 0}ms` },
              ].map(({ label, value }) => (
                <div key={label} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '6px 0', borderBottom: '1px solid ' + ACME.border }}>
                  <span style={{ fontSize: 13, color: ACME.muted, fontFamily: ACME.font }}>{label}</span>
                  <span style={{ fontSize: 13, fontWeight: 600, color: ACME.text, fontFamily: 'monospace' }}>{value}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.FraudDashboard = FraudDashboard;
