// Home / Overview screen — admin & analyst views.

const ConnectorTile = ({ c, size = 28, radius = 6 }) => (
  <div style={{
    width: size, height: size, borderRadius: radius,
    background: c.tone, color: 'white',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontWeight: 600, fontSize: size * 0.4,
    fontFamily: c.mono === '{ }' ? 'var(--font-mono)' : 'var(--font-sans)',
    flexShrink: 0,
    boxShadow: 'inset 0 0 0 0.5px rgba(255,255,255,.18)',
  }}>{c.mono}</div>
);

const StatCard = ({ label, value, delta, kind }) => (
  <div className="nx-card" style={{ padding: 14 }}>
    <div style={{ fontSize: 11.5, color: 'var(--ink-4)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
      {label}
    </div>
    <div style={{ fontSize: 26, fontWeight: 500, marginTop: 6, letterSpacing: '-0.02em' }}>
      {value}
    </div>
    <div style={{ fontSize: 11.5, color: kind === 'down' ? 'var(--ok)' : 'var(--ink-3)', marginTop: 2, fontFamily: 'var(--font-mono)' }}>
      {delta}
    </div>
  </div>
);

// Tiny sparkline
const Spark = ({ data, color = 'var(--accent)' }) => {
  const w = 120, h = 32;
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / (max - min || 1)) * (h - 4) - 2;
    return `${x},${y}`;
  }).join(' ');
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{ display: 'block' }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
};

const ConnectionRow = ({ c }) => {
  const statusColor = c.status === 'connected' ? 'var(--ok)' : c.status === 'syncing' ? 'var(--accent)' : 'var(--ink-4)';
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: '28px 1fr auto auto',
      alignItems: 'center', gap: 10,
      padding: '8px 4px',
      borderBottom: '0.5px solid var(--line)',
    }}>
      <ConnectorTile c={c} />
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500 }}>{c.name}</div>
        <div className="nx-mono" style={{ color: 'var(--ink-4)', fontSize: 11 }}>
          {c.records || '—'}
        </div>
      </div>
      <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{c.synced}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11.5, color: statusColor, minWidth: 76, justifyContent: 'flex-end' }}>
        {c.status === 'syncing' ? (
          <Icon name="refresh" size={12} className="nx-spin" />
        ) : (
          <span style={{ width: 6, height: 6, borderRadius: 50, background: statusColor }} />
        )}
        <span style={{ textTransform: 'capitalize' }}>{c.status}</span>
      </div>
    </div>
  );
};

const ScreenHome = ({ vertical, persona, setRoute, openWizard }) => {
  const V = window.NX_DATA.VERTICALS[vertical];
  const conns = window.NX_DATA.CONNECTORS.filter(c => c.status === 'connected' || c.status === 'syncing');
  const recents = window.NX_DATA.RECENT_QUERIES;
  const events = window.NX_DATA.SYNC_EVENTS;

  // Sample sparkline
  const sparkData = [3,4,3,5,6,5,7,6,8,9,8,10,9,11,12];

  return (
    <div className="nx-page" style={{
      padding: '24px 32px 40px',
      maxWidth: 1280, margin: '0 auto',
      display: 'flex', flexDirection: 'column', gap: 20,
    }}>
      {/* Hero */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24 }}>
        <div>
          <div className="nx-chip accent" style={{ marginBottom: 10 }}>
            <Icon name="sparkle" size={11} />
            {V.label}
          </div>
          <h1 style={{
            margin: 0, fontSize: 28, fontWeight: 500,
            letterSpacing: '-0.02em', lineHeight: 1.15,
            maxWidth: 620,
          }}>
            <span className="nx-serif" style={{ fontSize: 30, fontStyle: 'italic', color: 'var(--ink-2)' }}>Good afternoon, </span>
            Rian.
          </h1>
          <div style={{ marginTop: 6, color: 'var(--ink-3)', fontSize: 14, maxWidth: 540 }}>
            {V.tagline}
          </div>
        </div>
        <button className="nx-btn accent" onClick={() => setRoute('chat')}>
          <Icon name="sparkle" size={13} />
          Ask a question
          <span className="nx-kbd" style={{ background: 'rgba(255,255,255,.2)', color: 'white', borderColor: 'transparent', marginLeft: 4 }}>⌘K</span>
        </button>
      </div>

      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
        <StatCard label={V.metricA.label} value={V.metricA.value} delta={V.metricA.delta} kind="down" />
        <StatCard label={V.metricB.label} value={V.metricB.value} delta={V.metricB.delta} />
        <StatCard label={V.metricC.label} value={V.metricC.value} delta={V.metricC.delta} />
      </div>

      {/* Two-column body */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 16 }}>
        {/* Suggested questions */}
        <div className="nx-card" style={{ padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>
              Suggested for {V.short.toLowerCase()}
            </div>
            <button className="nx-btn ghost sm" style={{ color: 'var(--ink-3)' }}>
              <Icon name="refresh" size={12} />
              Regenerate
            </button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {V.suggestions.map((q, i) => (
              <button key={i}
                onClick={() => setRoute('chat')}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '10px 12px', textAlign: 'left',
                  background: 'var(--bg-sunken)',
                  border: '0.5px solid transparent',
                  borderRadius: 8, cursor: 'pointer',
                  fontSize: 13.5, color: 'var(--ink)',
                  transition: 'background .12s, border-color .12s',
                }}
                onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--bg-elev)'; e.currentTarget.style.borderColor = 'var(--line-strong)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--bg-sunken)'; e.currentTarget.style.borderColor = 'transparent'; }}
              >
                <Icon name="sparkle" size={13} style={{ color: 'var(--accent)', flexShrink: 0 }} />
                <span style={{ flex: 1 }}>{q}</span>
                <Icon name="arrow-up-right" size={13} style={{ color: 'var(--ink-4)' }} />
              </button>
            ))}
          </div>

          {/* Activity */}
          <div style={{ marginTop: 22 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
              <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>
                Recent across your team
              </div>
              <Spark data={sparkData} />
            </div>
            <div>
              {recents.map((r, i) => (
                <div key={i} style={{
                  display: 'grid', gridTemplateColumns: '24px 1fr auto',
                  alignItems: 'center', gap: 10,
                  padding: '8px 0',
                  borderTop: i === 0 ? 'none' : '0.5px solid var(--line)',
                }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: '50%',
                    background: 'var(--bg-sunken)',
                    fontSize: 10.5, fontWeight: 600,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: 'var(--ink-3)',
                  }}>{r.who[0]}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {r.q}
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>
                      {r.who} • {r.when}
                    </div>
                  </div>
                  <Icon name="chevron-right" size={13} style={{ color: 'var(--ink-5)' }} />
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Right column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {/* Connections */}
          <div className="nx-card" style={{ padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
              <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>
                Active connections
              </div>
              <button onClick={() => setRoute('integrations')} className="nx-btn ghost sm" style={{ color: 'var(--ink-3)' }}>
                All <Icon name="arrow-right" size={12} />
              </button>
            </div>
            <div>
              {conns.slice(0, 6).map(c => <ConnectionRow key={c.id} c={c} />)}
            </div>
            <button onClick={openWizard} className="nx-btn sm" style={{ marginTop: 10, width: '100%', justifyContent: 'center' }}>
              <Icon name="plus" size={13} /> Connect a source
            </button>
          </div>

          {/* Sync feed */}
          <div className="nx-card" style={{ padding: 16 }}>
            <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 12 }}>
              Sync activity
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {events.map((e, i) => {
                const dot = e.kind === 'ok' ? 'var(--ok)' : e.kind === 'warn' ? 'var(--warn)' : 'var(--accent)';
                return (
                  <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                    <div style={{ marginTop: 5 }}>
                      {e.kind === 'syncing' ? (
                        <Icon name="refresh" size={11} className="nx-spin" style={{ color: 'var(--accent)' }} />
                      ) : (
                        <span style={{ width: 6, height: 6, borderRadius: 50, background: dot, display: 'block' }} />
                      )}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, color: 'var(--ink)' }}>{e.msg}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)' }}>
                        {e.src} · {e.t}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {persona === 'admin' && (
            <div className="nx-card" style={{ padding: 16, background: 'linear-gradient(180deg, var(--accent-soft) 0%, var(--bg-elev) 60%)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <Icon name="shield-check" size={14} style={{ color: 'var(--accent-ink)' }} />
                <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--accent-ink)' }}>Admin</div>
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink)', marginBottom: 10 }}>
                3 pending access requests · 1 connector needs re-auth
              </div>
              <div style={{ display: 'flex', gap: 6 }}>
                <button onClick={() => setRoute('sso')} className="nx-btn sm">Review access</button>
                <button onClick={() => setRoute('integrations')} className="nx-btn sm ghost">Connectors</button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

window.ConnectorTile = ConnectorTile;
window.ScreenHome = ScreenHome;
