// Fleet Dashboard — Views (Acme Bank branding, fully light)

/* ==============================
   Shared helpers
   ============================== */

const panelBase = {
  background: '#FFFFFF',
  border: `1px solid ${FC.chromeBorder}`,
  borderRadius: 12,
  boxShadow: '0 1px 3px rgba(0,0,0,0.06), 0 4px 12px rgba(0,0,0,0.04)',
  pointerEvents: 'auto',
};

function SpecRow({ label, value, color, mono }) {
  return (
    <div style={{ marginBottom: 12 }}>
      <div style={{
        color: FC.chromeSubtle, fontSize: 9.5, fontFamily: FC.font,
        textTransform: 'uppercase', letterSpacing: 1.2, marginBottom: 3, fontWeight: 600,
      }}>
        {label}
      </div>
      <div style={{
        color: color || FC.chromeText, fontSize: 12.5,
        fontFamily: mono ? FC.mono : FC.font,
        fontWeight: 500, lineHeight: 1.4, whiteSpace: 'pre-line',
      }}>
        {value}
      </div>
    </div>
  );
}

function Divider() {
  return <div style={{ height: 1, background: FC.chromeBorder, margin: '2px 0' }} />;
}

/* ==============================
   1. PLACEMENT VIEW
   ============================== */

function PlacementView({ clusters = CLUSTERS, placement = PLACEMENT, fleetHub = FLEET_HUB }) {
  const boundList = placement.boundClusters || [placement.boundCluster];
  const boundNames = boundList
    .map(id => clusters.find(c => c.id === id)?.name).filter(Boolean).join('\n');
  const rejectedNames = placement.rejectedClusters
    .map(id => clusters.find(c => c.id === id)?.name).filter(Boolean).join('\n');

  return (
    <div style={{ display: 'flex', height: '100%' }}>
      {/* Map takes most of the space */}
      <div style={{ flex: 1, position: 'relative' }}>
        <WorldMap mode="placement" placementData={placement} clusters={clusters} fleetHub={fleetHub}>
          {/* Regulatory banner (floating, bottom) */}
          <div style={{
            position: 'absolute', bottom: 16, left: 16, right: 16,
            ...panelBase, borderRadius: 10,
            padding: '10px 18px',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: 6,
              background: FC.primaryBg,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 14, flexShrink: 0,
            }}>🛡</div>
            <div>
              <span style={{
                color: FC.primary, fontSize: 12, fontFamily: FC.font,
                fontWeight: 600, marginRight: 8,
              }}>
                EU PSD2 Data Residency
              </span>
              <span style={{
                color: FC.chromeMuted, fontSize: 11.5,
                fontFamily: FC.font,
              }}>
                Payment workloads with PII must remain on EU-labeled clusters
              </span>
            </div>
          </div>
        </WorldMap>
      </div>

      {/* Spec sidebar */}
      <aside style={{
        width: 264, flexShrink: 0,
        borderLeft: `1px solid ${FC.chromeBorder}`,
        background: '#fff',
        padding: '20px 18px',
        overflowY: 'auto',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{
          color: FC.chromeSubtle, fontSize: 9.5, fontFamily: FC.font,
          textTransform: 'uppercase', letterSpacing: 1.5, marginBottom: 6, fontWeight: 600,
        }}>
          Cluster Resource Placement
        </div>
        <div style={{
          color: FC.primary, fontSize: 14.5,
          fontFamily: FC.mono,
          fontWeight: 600, marginBottom: 16, lineHeight: 1.3,
        }}>
          {placement.name}
        </div>

        <Divider />
        <div style={{ height: 12 }} />

        <SpecRow label="Policy Type" value={`${placement.policyType} (count: ${placement.count})`} />
        <SpecRow label="Affinity" value={`${placement.affinity.key} ${placement.affinity.operator} ${placement.affinity.value}`} mono />
        <SpecRow label="Resources" value={placement.resources[0]} mono />

        <Divider />
        <div style={{ height: 12 }} />

        <SpecRow label="Bound Clusters" value={boundNames} color="#059669" mono />
        <SpecRow label="Not Selected" value={rejectedNames || '—'} color="#DC2626" mono />

        <Divider />
        <div style={{ height: 12 }} />

        <div style={{
          color: FC.chromeSubtle, fontSize: 9.5, fontFamily: FC.font,
          textTransform: 'uppercase', letterSpacing: 1.2, marginBottom: 8, fontWeight: 600,
        }}>
          Resource Spec
        </div>
        <pre style={{
          fontFamily: FC.mono, fontSize: 10,
          color: FC.chromeMuted, lineHeight: 1.7,
          background: FC.chromeBg, borderRadius: 8, padding: '12px 14px',
          margin: 0, whiteSpace: 'pre-wrap',
          border: `1px solid ${FC.chromeBorder}`,
        }}>
{`resourceSelectors:
  - group: ""
    kind: ${(placement.resources[0] || '').split('/')[0] || 'Namespace'}
    name: ${(placement.resources[0] || '').split('/')[1] || ''}
policy:
  placementType: ${placement.policyType}
  numberOfClusters: ${placement.count}
  affinity:
    clusterSelectorTerms:
      - labelSelector:
          matchLabels:
            ${placement.affinity.key}: ${placement.affinity.value}`}
        </pre>
      </aside>
    </div>
  );
}

/* ==============================
   2. OVERVIEW VIEW
   ============================== */

function StatCard({ label, value, accent, sub }) {
  return (
    <div style={{
      padding: '0 28px',
      borderRight: `1px solid ${FC.chromeBorder}`,
      display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 2,
    }}>
      <div style={{
        color: FC.chromeSubtle, fontSize: 9.5, fontFamily: FC.font,
        textTransform: 'uppercase', letterSpacing: 1.2, fontWeight: 600,
      }}>
        {label}
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
        <span style={{
          color: accent || FC.chromeText, fontSize: 24,
          fontFamily: FC.mono, fontWeight: 700, lineHeight: 1,
        }}>
          {value}
        </span>
        {sub && (
          <span style={{ color: FC.chromeMuted, fontSize: 11, fontFamily: FC.font }}>
            {sub}
          </span>
        )}
      </div>
    </div>
  );
}

function OverviewView({ clusters = CLUSTERS, fleetStats = FLEET_STATS, activityFeed = ACTIVITY_FEED, fleetHub = FLEET_HUB }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* Stats bar */}
      <div style={{
        display: 'flex', alignItems: 'center',
        padding: '16px 0',
        background: '#fff',
        borderBottom: `1px solid ${FC.chromeBorder}`,
        flexShrink: 0,
      }}>
        <StatCard label="Total Clusters" value={fleetStats.totalClusters} sub={`${fleetStats.shownClusters} shown`} />
        <StatCard label="Fleet Health" value="✓" accent="#059669" sub={fleetStats.healthyCount === fleetStats.totalClusters ? "All healthy" : `${fleetStats.healthyCount} healthy`} />
        <StatCard label="Active Upgrades" value={fleetStats.activeUpgrades} accent="#D97706" sub="in progress" />
        <StatCard label="Policy Compliance" value={`${fleetStats.policyCompliance}%`} accent="#059669" />
      </div>

      {/* Map + floating activity panel */}
      <div style={{ flex: 1, position: 'relative', minHeight: 0 }}>
        <WorldMap mode="overview" clusters={clusters} fleetHub={fleetHub}>
          {/* Activity panel */}
          <div style={{
            position: 'absolute', bottom: 16, left: 16, right: 16,
            ...panelBase,
            padding: '14px 20px',
            maxHeight: 160, overflowY: 'auto',
          }}>
            <div style={{
              color: FC.chromeSubtle, fontSize: 9.5, fontFamily: FC.font,
              textTransform: 'uppercase', letterSpacing: 1.2, fontWeight: 600, marginBottom: 12,
            }}>
              Recent Activity
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              {activityFeed.map((item, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
                  <span style={{
                    color: item.color, fontSize: 11,
                    fontFamily: FC.mono,
                    width: 14, textAlign: 'center', flexShrink: 0, marginTop: 1,
                  }}>
                    {item.icon}
                  </span>
                  <span style={{
                    color: FC.chromeMuted, fontSize: 12,
                    fontFamily: FC.font, lineHeight: 1.4, flex: 1,
                  }}>
                    {item.text}
                  </span>
                  <span style={{
                    color: FC.chromeSubtle, fontSize: 10,
                    fontFamily: FC.mono,
                    flexShrink: 0, marginTop: 2,
                  }}>
                    {item.time}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </WorldMap>
      </div>
    </div>
  );
}

/* ==============================
   3. UPGRADE RUN VIEW
   ============================== */

function UpgradeView({ clusters = CLUSTERS, upgrade = UPGRADE, fleetHub = FLEET_HUB }) {
  const [approved, setApproved] = React.useState(false);
  const [approving, setApproving] = React.useState(false);

  function handleApprove() {
    setApproving(true);
    setTimeout(() => { setApproved(true); setApproving(false); }, 1200);
  }

  const displayUpgrade = approved
    ? { ...upgrade, stages: upgrade.stages.map(s =>
        s.id === 2 ? { ...s, status: 'in-progress' } : s) }
    : upgrade;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* Upgrade header bar */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 28,
        padding: '14px 28px',
        background: '#fff',
        borderBottom: `1px solid ${FC.chromeBorder}`,
        flexShrink: 0,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{
            color: FC.chromeSubtle, fontSize: 9.5, fontFamily: FC.font,
            textTransform: 'uppercase', letterSpacing: 1.2, fontWeight: 600,
          }}>Upgrade</span>
          <span style={{
            color: '#D97706', fontSize: 20,
            fontFamily: FC.mono, fontWeight: 700,
          }}>{upgrade.fromVersion}</span>
          <span style={{ color: FC.chromeSubtle, fontSize: 16 }}>→</span>
          <span style={{
            color: FC.primary, fontSize: 20,
            fontFamily: FC.mono, fontWeight: 700,
          }}>{upgrade.toVersion}</span>
        </div>

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

        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{
            color: FC.chromeSubtle, fontSize: 9.5, fontFamily: FC.font,
            textTransform: 'uppercase', letterSpacing: 1, fontWeight: 600,
          }}>Strategy</span>
          <span style={{
            color: FC.chromeText, fontSize: 13,
            fontFamily: FC.mono,
          }}>{upgrade.strategy}</span>
        </div>

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

        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{
            color: FC.chromeSubtle, fontSize: 9.5, fontFamily: FC.font,
            textTransform: 'uppercase', letterSpacing: 1, fontWeight: 600,
          }}>Initiated</span>
          <span style={{
            color: FC.chromeText, fontSize: 13,
            fontFamily: FC.mono,
          }}>
            {new Date(upgrade.startedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} UTC
          </span>
        </div>
      </div>

      {/* Map + approval panel */}
      <div style={{ flex: 1, position: 'relative', minHeight: 0 }}>
        <WorldMap mode="upgrade" upgradeData={displayUpgrade} clusters={clusters} fleetHub={fleetHub}>
          {/* Approval CTA */}
          <div style={{
            position: 'absolute', bottom: 20, left: '50%', transform: 'translateX(-50%)',
            ...panelBase,
            padding: '14px 20px',
            display: 'flex', alignItems: 'center', gap: 14,
          }}>
            {!approved ? (
              <>
                <button onClick={handleApprove} disabled={approving} style={{
                  background: approving
                    ? FC.chromeBg
                    : 'linear-gradient(135deg, #f59e0b, #d97706)',
                  color: approving ? FC.chromeSubtle : '#fff',
                  border: 'none', borderRadius: 10,
                  padding: '12px 28px',
                  fontSize: 14, fontFamily: FC.font, fontWeight: 700,
                  cursor: approving ? 'wait' : 'pointer',
                  transition: 'all 0.2s',
                  letterSpacing: 0.3,
                  boxShadow: approving ? 'none' : '0 4px 16px rgba(245,158,11,0.25)',
                  pointerEvents: 'auto',
                }}>
                  {approving ? '⏳  Approving…' : '⏸  Approve Stage 2 — acme-aks-eu'}
                </button>
                <button style={{
                  background: '#F9FAFB',
                  color: FC.chromeMuted,
                  border: `1px solid ${FC.chromeBorder}`,
                  borderRadius: 10, padding: '12px 20px',
                  fontSize: 13, fontFamily: FC.font, fontWeight: 500,
                  cursor: 'pointer',
                  pointerEvents: 'auto',
                }}>
                  Rollback
                </button>
              </>
            ) : (
              <div style={{
                display: 'flex', alignItems: 'center', gap: 10,
                color: '#059669', fontSize: 14,
                fontFamily: FC.font, fontWeight: 600,
              }}>
                <span style={{ fontSize: 18 }}>✓</span>
                Stage 2 approved — upgrade in progress on acme-aks-eu
              </div>
            )}
          </div>
        </WorldMap>
      </div>
    </div>
  );
}

Object.assign(window, { PlacementView, OverviewView, UpgradeView });
