/* acme-ui.jsx — Reusable UI components for Acme Bank prototype */

const ACME = {
  primary: '#0D7C4A', primaryDark: '#065F3A', primaryBg: '#ECFDF5',
  bg: '#F3F4F6', card: '#FFFFFF', border: '#E5E7EB',
  text: '#111827', muted: '#6B7280', subtle: '#9CA3AF',
  success: '#059669', warning: '#D97706', danger: '#DC2626', neutral: '#6B7280',
  font: "'Plus Jakarta Sans', sans-serif",
};

/* ─── Top Nav ─── */
const NAV_TABS = ['Dashboard', 'Applications', 'Portfolio', 'Reports', 'Settings'];

const AcmeNav = ({ activeTab, onTabClick }) => (
  <div style={{ background: '#fff', display: 'flex', alignItems: 'center', padding: '0 24px', height: 56, borderBottom: '1px solid ' + ACME.border, flexShrink: 0 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginRight: 36, cursor: 'pointer' }} onClick={() => onTabClick && onTabClick('Dashboard')}>
      <div style={{ width: 30, height: 30, borderRadius: 8, background: ACME.primary, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
          <path d="M8 2L2 14h12L8 2z" fill="none" stroke="#fff" strokeWidth="1.8" strokeLinejoin="round"/>
          <line x1="8" y1="7" x2="8" y2="10.5" stroke="#fff" strokeWidth="1.5" strokeLinecap="round"/>
        </svg>
      </div>
      <span style={{ fontSize: 17, fontWeight: 700, color: ACME.text, fontFamily: ACME.font }}>acme<span style={{ color: ACME.primary }}>bank</span></span>
    </div>
    {NAV_TABS.map((t) => {
      const active = t === activeTab;
      return (
        <div key={t} onClick={() => onTabClick && onTabClick(t)} style={{ padding: '0 14px', height: 56, display: 'flex', alignItems: 'center', fontSize: 14, fontWeight: active ? 600 : 500, color: active ? ACME.primary : ACME.muted, borderBottom: active ? '2px solid ' + ACME.primary : '2px solid transparent', cursor: 'pointer', fontFamily: ACME.font }}>{t}</div>
      );
    })}
    <div style={{ flex: 1 }}></div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{ padding: '6px 12px', background: ACME.bg, borderRadius: 8, display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: ACME.muted, cursor: 'pointer', fontFamily: ACME.font }}>
        <svg width="14" height="14" fill="none" stroke={ACME.muted} strokeWidth="2"><circle cx="6" cy="6" r="5"/><line x1="10" y1="10" x2="13" y2="13"/></svg>
        Search
      </div>
      <div style={{ position: 'relative', cursor: 'pointer' }}>
        <svg width="20" height="20" fill="none" stroke={ACME.muted} strokeWidth="1.5" viewBox="0 0 24 24"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0"/></svg>
        <div style={{ position: 'absolute', top: 0, right: 0, width: 8, height: 8, borderRadius: 4, background: '#EF4444', border: '2px solid #fff' }}></div>
      </div>
      <div style={{ height: 24, width: 1, background: ACME.border }}></div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ width: 32, height: 32, borderRadius: '50%', background: ACME.primaryBg, color: ACME.primary, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700, fontFamily: ACME.font }}>DN</div>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600, fontFamily: ACME.font }}>David Nakamura</div>
          <div style={{ fontSize: 11, color: ACME.muted, fontFamily: ACME.font }}>Sr. Credit Analyst</div>
        </div>
      </div>
    </div>
  </div>
);

/* ─── Breadcrumb ─── */
const AcmeBreadcrumb = ({ appId }) => (
  <div style={{ padding: '10px 0 10px 24px', fontSize: 13, color: ACME.muted, flexShrink: 0, display: 'flex', alignItems: 'center', gap: 6, fontFamily: ACME.font }}>
    <span style={{ cursor: 'pointer' }}>Consumer Lending</span>
    <svg width="12" height="12" viewBox="0 0 12 12" fill={ACME.subtle}><path d="M4.5 2.5l3.5 3.5-3.5 3.5"/></svg>
    <span style={{ cursor: 'pointer' }}>Applications</span>
    <svg width="12" height="12" viewBox="0 0 12 12" fill={ACME.subtle}><path d="M4.5 2.5l3.5 3.5-3.5 3.5"/></svg>
    <span style={{ fontWeight: 600, color: ACME.text }}>{appId}</span>
  </div>
);

/* ─── Sidebar Queue ─── */
const AcmeSidebar = ({ applicants, selectedIndex, onSelect }) => {
  const statusColors = {
    'approved-conditions': { bg: '#FEF3C7', text: '#B45309', dot: '#F59E0B', label: 'Conditions' },
    'review': { bg: '#DBEAFE', text: '#1D4ED8', dot: '#3B82F6', label: 'Review' },
    'approved': { bg: '#D1FAE5', text: '#065F46', dot: '#10B981', label: 'Approved' },
    'declined': { bg: '#FEE2E2', text: '#991B1B', dot: '#EF4444', label: 'Declined' },
  };
  return (
    <div style={{ width: 260, background: '#fff', borderRight: '1px solid ' + ACME.border, display: 'flex', flexDirection: 'column', flexShrink: 0, overflow: 'hidden' }}>
      <div style={{ padding: '14px 16px 10px', borderBottom: '1px solid ' + ACME.border }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: ACME.muted, textTransform: 'uppercase', letterSpacing: 1, fontFamily: ACME.font, marginBottom: 10 }}>Application Queue</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 10px', borderRadius: 8, border: '1px solid ' + ACME.border, fontSize: 13, color: ACME.subtle, cursor: 'pointer', fontFamily: ACME.font }}>
          <svg width="14" height="14" fill="none" stroke={ACME.subtle} strokeWidth="2"><circle cx="6" cy="6" r="5"/><line x1="10" y1="10" x2="13" y2="13"/></svg>
          Filter applications...
        </div>
      </div>
      <div style={{ flex: 1, overflow: 'auto' }}>
        {applicants.map((app, i) => {
          const sel = i === selectedIndex;
          const sc = statusColors[app.decisionType] || statusColors['review'];
          return (
            <div key={app.id} onClick={() => onSelect(i)} style={{
              padding: '12px 16px', cursor: 'pointer', borderLeft: sel ? '3px solid ' + ACME.primary : '3px solid transparent',
              background: sel ? ACME.primaryBg : 'transparent', transition: 'all 0.15s',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
                <span style={{ fontSize: 14, fontWeight: sel ? 700 : 600, color: ACME.text, fontFamily: ACME.font }}>{app.name}</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 11, color: ACME.muted, fontFamily: ACME.font }}>{app.id}</span>
                <div style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '2px 8px', borderRadius: 10, background: sc.bg, fontSize: 10, fontWeight: 600, color: sc.text, fontFamily: ACME.font }}>
                  <div style={{ width: 5, height: 5, borderRadius: 3, background: sc.dot }}></div>
                  {sc.label}
                </div>
              </div>
              <div style={{ fontSize: 11, color: ACME.subtle, marginTop: 3, fontFamily: ACME.font }}>{app.productShort} · {app.amount}</div>
            </div>
          );
        })}
      </div>
      <div style={{ padding: '10px 16px', borderTop: '1px solid ' + ACME.border, fontSize: 11, color: ACME.subtle, fontFamily: ACME.font, textAlign: 'center' }}>
        Showing 4 of 47 pending
      </div>
    </div>
  );
};

/* ─── Animated Gauge ─── */
const AcmeGauge = ({ targetScore, min, max, label, isAnimating }) => {
  const [displayScore, setDisplayScore] = React.useState(targetScore);
  const prevTargetRef = React.useRef(targetScore);
  const animRef = React.useRef(null);

  React.useEffect(() => {
    if (isAnimating) { setDisplayScore(min); prevTargetRef.current = min; return; }
    const from = prevTargetRef.current;
    prevTargetRef.current = targetScore;
    if (from === targetScore) { setDisplayScore(targetScore); return; }
    let start = null;
    const duration = 1200;
    const step = (ts) => {
      if (!start) start = ts;
      const pct = Math.min((ts - start) / duration, 1);
      const eased = 1 - Math.pow(1 - pct, 3);
      setDisplayScore(Math.round(from + (targetScore - from) * eased));
      if (pct < 1) animRef.current = requestAnimationFrame(step);
    };
    animRef.current = requestAnimationFrame(step);
    return () => cancelAnimationFrame(animRef.current);
  }, [targetScore, isAnimating]);

  const score = displayScore;
  const pct = Math.max(0, (score - min) / (max - min));
  const startAngle = 135, sweep = 270;
  const endAngle = startAngle + sweep * pct;
  const r = 80, cx = 100, cy = 100;
  const polarToCart = (deg) => {
    const rad = (deg - 90) * Math.PI / 180;
    return { x: cx + r * Math.cos(rad), y: cy + r * Math.sin(rad) };
  };
  const describeArc = (s, e) => {
    if (e - s < 0.5) return '';
    const sp = polarToCart(s), ep = polarToCart(e);
    return `M ${sp.x} ${sp.y} A ${r} ${r} 0 ${(e - s) > 180 ? 1 : 0} 1 ${ep.x} ${ep.y}`;
  };

  const arcColor = score >= 740 ? '#059669' : score >= 670 ? '#0D7C4A' : score >= 580 ? '#D97706' : '#DC2626';

  return (
    <svg viewBox="0 0 200 165" style={{ width: '100%', maxWidth: 210 }}>
      <path d={describeArc(startAngle, startAngle + sweep)} fill="none" stroke="#E5E7EB" strokeWidth="14" strokeLinecap="round" />
      {pct > 0.01 && <path d={describeArc(startAngle, endAngle)} fill="none" stroke={arcColor} strokeWidth="14" strokeLinecap="round" />}
      <circle cx={cx} cy={cy} r="46" fill="#F0FDF4" />
      <text x={cx} y={cy - 2} textAnchor="middle" dominantBaseline="central" fill={ACME.primaryDark} fontSize="32" fontWeight="700" fontFamily={ACME.font}>{score}</text>
      <text x={cx} y={cy + 20} textAnchor="middle" fill={arcColor} fontSize="11" fontWeight="600" fontFamily={ACME.font}>{label}</text>
      <text x="22" y="162" fill={ACME.subtle} fontSize="9" fontFamily={ACME.font}>{min}</text>
      <text x="178" y="162" textAnchor="end" fill={ACME.subtle} fontSize="9" fontFamily={ACME.font}>{max}</text>
    </svg>
  );
};

/* ─── Decision Badge ─── */
const DecisionBadge = ({ decision, type, visible }) => {
  const styles = {
    'approved': { bg: '#D1FAE5', color: '#065F46', icon: '✓' },
    'approved-conditions': { bg: '#D1FAE5', color: '#065F46', icon: '✓' },
    'review': { bg: '#DBEAFE', color: '#1E40AF', icon: '⬭' },
    'declined': { bg: '#FEE2E2', color: '#991B1B', icon: '✕' },
  };
  const s = styles[type] || styles['review'];
  return (
    <div style={{ opacity: visible ? 1 : 0, transform: visible ? 'translateY(0)' : 'translateY(8px)', transition: 'all 0.4s ease', display: 'inline-flex', alignItems: 'center', gap: 8, background: s.bg, padding: '8px 20px', borderRadius: 24 }}>
      <div style={{ width: 8, height: 8, borderRadius: 4, background: s.color }}></div>
      <span style={{ fontSize: 14, fontWeight: 700, color: s.color, fontFamily: ACME.font }}>{decision}</span>
    </div>
  );
};

/* ─── Factor Card ─── */
const FactorCard = ({ factor, visible, delay }) => {
  const colors = {
    positive: { bg: '#F0FDF4', border: '#BBF7D0', text: ACME.success, icon: '✓' },
    warning:  { bg: '#FFFBEB', border: '#FDE68A', text: '#B45309', icon: '⚠' },
    neutral:  { bg: '#F9FAFB', border: ACME.border, text: ACME.neutral, icon: 'ⓘ' },
  };
  const c = colors[factor.type];
  return (
    <div style={{
      display: 'flex', gap: 10, alignItems: 'flex-start', padding: '10px 12px', borderRadius: 8,
      background: c.bg, border: '1px solid ' + c.border,
      opacity: visible ? 1 : 0, transform: visible ? 'translateX(0)' : 'translateX(12px)',
      transition: `all 0.35s ease ${delay}ms`,
    }}>
      <span style={{ fontSize: 13, color: c.text, flexShrink: 0, marginTop: 1 }}>{c.icon}</span>
      <div>
        <div style={{ fontSize: 13, fontWeight: 600, color: c.text, fontFamily: ACME.font }}>{factor.label}</div>
        <div style={{ fontSize: 12, color: ACME.muted, marginTop: 1, fontFamily: ACME.font }}>{factor.detail}</div>
      </div>
    </div>
  );
};

/* ─── Section Card ─── */
const InfoSection = ({ title, children }) => (
  <div style={{ background: ACME.card, borderRadius: 12, padding: '18px 24px', boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>
    <div style={{ fontSize: 12, fontWeight: 600, color: ACME.muted, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 14, fontFamily: ACME.font }}>{title}</div>
    {children}
  </div>
);

/* ─── Field ─── */
const InfoField = ({ label, value }) => (
  <div>
    <div style={{ fontSize: 11, color: ACME.muted, marginBottom: 3, fontFamily: ACME.font }}>{label}</div>
    <div style={{ fontSize: 14, fontWeight: 500, color: ACME.text, fontFamily: ACME.font }}>{value}</div>
  </div>
);

/* ─── Loading Spinner ─── */
const ScoringLoader = () => (
  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '40px 0', gap: 16 }}>
    <div style={{ width: 48, height: 48, border: '4px solid ' + ACME.border, borderTopColor: ACME.primary, borderRadius: '50%', animation: 'acme-spin 0.8s linear infinite' }}></div>
    <div style={{ fontSize: 14, fontWeight: 600, color: ACME.primary, fontFamily: ACME.font }}>Analyzing application...</div>
    <div style={{ fontSize: 12, color: ACME.muted, fontFamily: ACME.font }}>Running credit model inference</div>
  </div>
);

Object.assign(window, {
  ACME, AcmeNav, AcmeBreadcrumb, AcmeSidebar, AcmeGauge,
  DecisionBadge, FactorCard, InfoSection, InfoField, ScoringLoader,
});
