// Fleet Dashboard — App Shell (Acme Bank branding)

function FleetApp() {
  const [activeView, setActiveView] = React.useState('placement');
  const [syncTick, setSyncTick] = React.useState(0);
  const [fleetState, setFleetState] = React.useState(null);
  const [fetchError, setFetchError] = React.useState(false);
  const [isLive, setIsLive] = React.useState(false);

  // Poll /api/fleet-state every 5 seconds
  React.useEffect(() => {
    let cancelled = false;
    async function fetchState() {
      try {
        const res = await fetch('/api/fleet-state');
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const data = await res.json();
        if (cancelled) return;
        if (data.live) {
          setIsLive(true);
          setFleetState(data);
          setFetchError(false);
        } else {
          setIsLive(false);
          setFleetState(null);
        }
      } catch (e) {
        if (!cancelled) setFetchError(true);
      }
    }
    fetchState();
    const iv = setInterval(fetchState, 5000);
    return () => { cancelled = true; clearInterval(iv); };
  }, []);

  React.useEffect(() => {
    const iv = setInterval(() => setSyncTick(t => t + 1), 2000);
    return () => clearInterval(iv);
  }, []);
  const syncSecs = (syncTick % 5) * 2 || 2;

  // Resolve data: live data wins, otherwise fall back to hardcoded globals
  const clusters = (fleetState && fleetState.clusters) || CLUSTERS;
  const placement = (fleetState && fleetState.placement) || PLACEMENT;
  const upgrade = (fleetState && fleetState.upgrade) || UPGRADE;
  const fleetStats = (fleetState && fleetState.fleetStats) || FLEET_STATS;
  const activityFeed = (fleetState && fleetState.activityFeed) || ACTIVITY_FEED;
  const fleetHub = (fleetState && fleetState.fleetHub) || FLEET_HUB;

  const NAV_ITEMS = [
    { key: 'overview', label: 'Overview' },
    { key: 'placement', label: 'Placement' },
    { key: 'upgrade', label: 'Upgrade Run' },
  ];

  const liveLabel = isLive ? 'Fleet API · Live' : `Fleet API · ${syncSecs}s ago`;

  return (
    <div style={{
      display: 'flex', flexDirection: 'column',
      height: '100vh', width: '100vw',
      background: FC.chromeBg,
      color: FC.chromeText,
      overflow: 'hidden',
    }}>
      {/* Header */}
      <header style={{
        background: '#fff',
        display: 'flex',
        alignItems: 'center',
        padding: '0 24px',
        height: 56,
        borderBottom: `1px solid ${FC.chromeBorder}`,
        flexShrink: 0,
      }}>
        {/* Brand mark */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginRight: 24, cursor: 'pointer' }}>
          <div style={{
            width: 30, height: 30, borderRadius: 8,
            background: FC.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: FC.chromeText, fontFamily: FC.font }}>
            acme<span style={{ color: FC.primary }}>bank</span>
          </span>
        </div>

        {/* Divider */}
        <div style={{ height: 24, width: 1, background: FC.chromeBorder, marginRight: 16 }} />

        {/* Section label */}
        <span style={{
          color: FC.chromeMuted, fontSize: 14,
          fontFamily: FC.font, fontWeight: 500, marginRight: 20,
        }}>
          Fleet Dashboard
        </span>

        {/* Nav tabs */}
        {NAV_ITEMS.map(({ key, label }) => {
          const on = activeView === key;
          return (
            <div key={key} onClick={() => setActiveView(key)} style={{
              padding: '0 14px', height: 56,
              display: 'flex', alignItems: 'center',
              fontSize: 14,
              fontWeight: on ? 600 : 500,
              color: on ? FC.primary : FC.chromeMuted,
              borderBottom: on ? `2px solid ${FC.primary}` : '2px solid transparent',
              cursor: 'pointer',
              fontFamily: FC.font,
            }}>
              {label}
            </div>
          );
        })}

        <div style={{ flex: 1 }} />

        {/* Live indicator */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
          <span className="fleet-live-dot" style={fetchError ? { background: '#ef4444' } : {}} />
          <span style={{ color: FC.chromeSubtle, fontSize: 11, fontFamily: FC.mono }}>
            {fetchError ? 'Fleet API · Offline' : liveLabel}
          </span>
        </div>

        <div style={{ height: 24, width: 1, background: FC.chromeBorder, margin: '0 12px' }} />

        {/* User avatar */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{
            width: 32, height: 32, borderRadius: '50%',
            background: FC.primaryBg, color: FC.primary,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 13, fontWeight: 700, fontFamily: FC.font,
          }}>RK</div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, fontFamily: FC.font }}>Ravi Kumar</div>
            <div style={{ fontSize: 11, color: FC.chromeMuted, fontFamily: FC.font }}>Platform Engineer</div>
          </div>
        </div>
      </header>

      {/* Active View */}
      <main style={{ flex: 1, overflow: 'hidden', minHeight: 0 }}>
        {activeView === 'overview'  && <OverviewView clusters={clusters} fleetStats={fleetStats} activityFeed={activityFeed} fleetHub={fleetHub} />}
        {activeView === 'placement' && <PlacementView clusters={clusters} placement={placement} fleetHub={fleetHub} />}
        {activeView === 'upgrade'   && <UpgradeView clusters={clusters} upgrade={upgrade} fleetHub={fleetHub} />}
      </main>

      {/* Status Bar */}
      <footer style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '0 24px',
        height: 32, flexShrink: 0,
        background: '#fff',
        borderTop: `1px solid ${FC.chromeBorder}`,
        fontSize: 11, fontFamily: FC.mono,
        color: FC.chromeSubtle,
      }}>
        <span>fleet.internal.acmebank.com</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <div style={{ width: 6, height: 6, borderRadius: 3, background: fetchError ? '#ef4444' : '#10B981' }} />
          {fleetStats.totalClusters} clusters · {isLive ? 'Live' : 'Demo'} · Azure Kubernetes Fleet Manager
        </span>
      </footer>
    </div>
  );
}

Object.assign(window, { FleetApp });
