// =============================================================================
// WOOO AIOps - AwoooP M1 租戶管理頁面
// =============================================================================
// 顯示所有 tenant 清單，含 migration_mode badge 與 suspended 狀態

"use client";

import { useState, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl";
import { Link } from "@/i18n/routing";
import {
  ArrowRight,
  Building2,
  RefreshCw,
  AlertCircle,
  DollarSign,
  Ban,
  CheckCircle2,
  GitBranch,
  ListChecks,
  Lock,
  SearchCheck,
  ShieldCheck,
} from "lucide-react";
import { cn } from "@/lib/utils";

// =============================================================================
// Types
// =============================================================================

type MigrationMode =
  | "legacy_awoooi_default"
  | "shadow"
  | "canary"
  | "read_only"
  | "suggest"
  | "auto_remediate";

interface Tenant {
  project_id: string;
  display_name: string;
  migration_mode: MigrationMode;
  budget_limit_usd: number | string | null;
  is_active: boolean;
}

interface ApiResponse {
  tenants?: Tenant[];
  items?: Tenant[];
  total: number;
}

type GitHubTenantReadinessMetric = {
  key: string;
  value: string;
  icon: typeof ShieldCheck;
  tone: "neutral" | "warn";
};

type GitHubTenantReadinessScope = {
  key: string;
  name: string;
  status: string;
};

type OwnerResponseValidationTenantRef = {
  phase: string;
  key: string;
  contract: string;
};

// =============================================================================
// 常數
// =============================================================================

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? "";

const githubTenantReadinessMetrics: GitHubTenantReadinessMetric[] = [
  { key: "candidateRepos", value: "8", icon: GitBranch, tone: "neutral" },
  { key: "inScopeRepos", value: "7", icon: ListChecks, tone: "warn" },
  { key: "ownerResponses", value: "0/22", icon: ShieldCheck, tone: "warn" },
  { key: "tenantScopeChanges", value: "0", icon: Lock, tone: "warn" },
];

const githubTenantReadinessScopes: GitHubTenantReadinessScope[] = [
  {
    key: "tenantSourceScope",
    name: "AWOOOI 第一租戶原始碼管控範圍",
    status: "waiting",
  },
  {
    key: "giteaInventoryOwner",
    name: "S4.9 Gitea 清冊負責人證明",
    status: "0/5",
  },
  {
    key: "githubTargetOwner",
    name: "S4.10 GitHub 目標負責人決策",
    status: "0/7",
  },
  {
    key: "workflowSecretOwner",
    name: "S4.12 工作流程 / 機密名稱負責人回覆",
    status: "0/5",
  },
];

const githubTenantReadinessBoundaries = [
  "tenant_source_control_scope_accepted=false",
  "repo_owner_response_accepted=false",
  "repo_creation_authorized=false",
  "refs_mutation_authorized=false",
  "github_primary_switch_authorized=false",
  "gitea_disablement_authorized=false",
  "tenant_policy_mutation_authorized=false",
  "runtime_execution_authorized=false",
  "action_buttons_allowed=false",
];

const ownerResponseValidationTenantRefs: OwnerResponseValidationTenantRef[] = [
  {
    phase: "S4.13",
    key: "validationRollup",
    contract: "source_control_owner_response_validation_rollup_v1",
  },
  {
    phase: "S4.9",
    key: "giteaAttestation",
    contract: "gitea_inventory_owner_attestation_response_v1",
  },
  {
    phase: "S4.10",
    key: "githubTarget",
    contract: "github_target_owner_decision_response_v1",
  },
  {
    phase: "S4.11",
    key: "refsTruth",
    contract: "source_control_ref_truth_owner_response_v1",
  },
  {
    phase: "S4.12",
    key: "workflowSecret",
    contract: "source_control_workflow_secret_name_owner_response_v1",
  },
];

const ownerResponseValidationTenantBoundaries = [
  "owner_response_validation_received_count=0",
  "owner_response_validation_accepted_count=0",
  "owner_response_validation_rejected_count=0",
  "tenant_source_control_scope_accepted=false",
  "tenant_policy_mutation_authorized=false",
  "repo_creation_authorized=false",
  "refs_sync_authorized=false",
  "workflow_modification_authorized=false",
  "secret_value_collection_allowed=false",
  "github_primary_switch_authorized=false",
  "runtime_execution_authorized=false",
  "action_buttons_allowed=false",
];

const MIGRATION_MODE_CONFIG: Record<
  MigrationMode,
  { label: string; bg: string; text: string; border: string }
> = {
  legacy_awoooi_default: {
    label: "舊版",
    bg: "bg-white",
    text: "text-[#5f5b52]",
    border: "border-[#d8d3c7]",
  },
  shadow: {
    label: "影子",
    bg: "bg-[#f4f1e8]",
    text: "text-[#5f5b52]",
    border: "border-[#d8d3c7]",
  },
  canary: {
    label: "金絲雀",
    bg: "bg-[#fff7e8]",
    text: "text-[#8a5a08]",
    border: "border-[#d9b36f]",
  },
  read_only: {
    label: "只讀",
    bg: "bg-[#eef5ff]",
    text: "text-[#1f5b9b]",
    border: "border-[#9bb6d9]",
  },
  suggest: {
    label: "建議",
    bg: "bg-[#f6f0ff]",
    text: "text-[#6541a5]",
    border: "border-[#baa7de]",
  },
  auto_remediate: {
    label: "自動修復",
    bg: "bg-[#f0faf2]",
    text: "text-[#17602a]",
    border: "border-[#9bc7a4]",
  },
};

// =============================================================================
// Sub Components
// =============================================================================

function MigrationModeBadge({ mode }: { mode: MigrationMode }) {
  const config = MIGRATION_MODE_CONFIG[mode] ?? MIGRATION_MODE_CONFIG.shadow;
  return (
    <span
      className={cn(
        "inline-flex items-center px-2.5 py-0.5 rounded-md text-xs font-mono font-medium border",
        config.bg,
        config.text,
        config.border
      )}
    >
      {config.label}
    </span>
  );
}

function SuspendedBadge({ suspended }: { suspended: boolean }) {
  return suspended ? (
    <span className="inline-flex items-center gap-1 border border-[#e2a29b] bg-[#fff0ef] px-2.5 py-0.5 text-xs font-medium text-[#9f2f25]">
      <Ban className="w-3 h-3" aria-hidden="true" />
      停用
    </span>
  ) : (
    <span className="inline-flex items-center gap-1 border border-[#9bc7a4] bg-[#f0faf2] px-2.5 py-0.5 text-xs font-medium text-[#17602a]">
      <CheckCircle2 className="w-3 h-3" aria-hidden="true" />
      正常
    </span>
  );
}

function TenantRow({ tenant }: { tenant: Tenant }) {
  const budget =
    tenant.budget_limit_usd == null ? null : Number(tenant.budget_limit_usd);

  return (
    <tr className="border-b border-border hover:bg-accent/30 transition-colors">
      <td className="px-4 py-3">
        <span className="font-mono text-sm text-foreground">
          {tenant.project_id}
        </span>
      </td>
      <td className="px-4 py-3">
        <span className="text-sm text-foreground font-medium">{tenant.display_name || "--"}</span>
      </td>
      <td className="px-4 py-3">
        <MigrationModeBadge mode={tenant.migration_mode} />
      </td>
      <td className="px-4 py-3">
        <span className="flex items-center gap-1 text-sm text-muted-foreground font-mono">
          {tenant.budget_limit_usd != null ? (
            <>
              <DollarSign className="w-3.5 h-3.5" aria-hidden="true" />
              {budget?.toLocaleString("en-US", {
                minimumFractionDigits: 2,
              })}
            </>
          ) : (
            "--"
          )}
        </span>
      </td>
      <td className="px-4 py-3">
        <SuspendedBadge suspended={!tenant.is_active} />
      </td>
    </tr>
  );
}

function SecurityTenantScopeCandidatePanel() {
  const t = useTranslations("awooop.tenants.securityTenantScopeCandidate");
  const metrics = [
    {
      label: t("metrics.primaryTenant"),
      value: "AWOOOI",
      detail: t("metrics.primaryTenantDetail"),
    },
    {
      label: t("metrics.securityEntry"),
      value: "IwoooS",
      detail: t("metrics.securityEntryDetail"),
    },
    {
      label: t("metrics.hostCoverage"),
      value: "3",
      detail: t("metrics.hostCoverageDetail"),
    },
    {
      label: t("metrics.policyMutations"),
      value: "0",
      detail: t("metrics.policyMutationsDetail"),
    },
  ];
  const scopes = [
    {
      name: "AWOOOI 第一租戶",
      detail: t("scopeRefs.awoooiTenant"),
    },
    {
      name: "IwoooS 資安鏡像",
      detail: t("scopeRefs.iwooosMirror"),
    },
    {
      name: "Kali 112 / 開發主機 168 / 開發主機 111",
      detail: t("scopeRefs.hostCoverage"),
    },
    {
      name: "S4.9-S4.12 負責人回覆等待中",
      detail: t("scopeRefs.ownerResponse"),
    },
  ];

  return (
    <section className="overflow-hidden border border-[#e0ddd4] bg-white">
      <div className="sm:hidden">
        <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-2 py-2">
          <p className="text-[11px] font-semibold leading-4 text-[#141413]">{t("title")}</p>
          <span className="mt-1 inline-flex border border-[#9bb6d9] bg-[#eef5ff] px-1.5 py-0.5 text-[10px] font-semibold text-[#1f5b9b]">
            {t("badge")}
          </span>
        </div>
        <div className="grid gap-px bg-[#e0ddd4] text-[10px]">
          <div className="bg-white px-2 py-2">
            <p className="font-semibold text-[#77736a]">AWOOOI</p>
            <p className="mt-1 text-lg font-semibold text-[#141413]">租戶</p>
          </div>
          <div className="bg-white px-2 py-2">
            <p className="font-semibold text-[#77736a]">IwoooS</p>
            <p className="mt-1 text-lg font-semibold text-[#141413]">鏡像</p>
          </div>
          <div className="bg-white px-2 py-2">
            <p className="font-semibold text-[#77736a]">主機</p>
            <p className="mt-1 font-mono text-lg font-semibold text-[#141413]">3</p>
          </div>
          <div className="bg-white px-2 py-2">
            <p className="font-semibold text-[#77736a]">政策</p>
            <p className="mt-1 font-mono text-lg font-semibold text-[#141413]">0</p>
          </div>
        </div>
        <div className="space-y-2 bg-[#faf9f3] px-2 py-2 text-[10px] leading-4 text-[#5f5b52]">
          <p className="font-semibold text-[#141413]">{t("boundaryTitle")}</p>
          <p>4 gates = false</p>
          <Link
            href="/iwooos"
            className="inline-flex items-center gap-1 border border-[#d8d3c7] bg-white px-2 py-1 font-semibold text-[#141413] hover:border-[#d97757]"
          >
            IwoooS
            <ArrowRight className="h-3 w-3 text-[#77736a]" aria-hidden="true" />
          </Link>
        </div>
      </div>

      <div className="hidden sm:block">
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex items-start gap-2">
          <ShieldCheck className="mt-0.5 h-4 w-4 text-[#d97757]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 max-w-3xl text-xs leading-5 text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <span className="inline-flex border border-[#9bb6d9] bg-[#eef5ff] px-2 py-0.5 text-xs font-semibold text-[#1f5b9b]">
          {t("badge")}
        </span>
      </div>

      <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-2 xl:grid-cols-4">
        {metrics.map((item) => (
          <div key={item.label} className="bg-white px-4 py-3">
            <p className="text-xs font-semibold text-[#77736a]">{item.label}</p>
            <p className="mt-2 break-words font-mono text-2xl font-semibold text-[#141413]">{item.value}</p>
            <p className="mt-2 text-xs leading-5 text-[#5f5b52]">{item.detail}</p>
          </div>
        ))}
      </div>

      <div className="grid min-w-0 gap-4 p-4 xl:grid-cols-[1.1fr_0.9fr]">
        <div className="min-w-0 border border-[#e0ddd4] bg-white">
          <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3 text-xs font-semibold text-[#141413]">
            {t("scopeRefsTitle")}
          </div>
          <div className="divide-y divide-[#eee9dd]">
            {scopes.map((item) => (
              <div key={item.name} className="px-4 py-3">
                <p className="break-words font-mono text-xs font-semibold text-[#141413]">{item.name}</p>
                <p className="mt-1 text-xs leading-5 text-[#5f5b52]">{item.detail}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="min-w-0 border border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
          <p className="text-xs font-semibold text-[#77736a]">{t("boundaryLabel")}</p>
          <p className="mt-2 text-sm font-semibold text-[#141413]">{t("boundaryTitle")}</p>
          <p className="mt-2 text-xs leading-5 text-[#5f5b52]">{t("boundaryDetail")}</p>
          <div className="mt-4 grid gap-2 font-mono text-xs text-[#141413]">
            <span>tenant_migration_mode_changed=false</span>
            <span>tenant_policy_mutation_authorized=false</span>
            <span>runtime_execution_authorized=false</span>
            <span>action_buttons_allowed=false</span>
          </div>
          <Link
            href="/iwooos"
            className="mt-4 inline-flex items-center gap-2 border border-[#d8d3c7] bg-white px-3 py-1.5 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
          >
            {t("openIwooos")}
            <ArrowRight className="h-3.5 w-3.5 text-[#77736a]" aria-hidden="true" />
          </Link>
        </div>
      </div>
      </div>
    </section>
  );
}

function GitHubTenantReadinessScopePanel() {
  const t = useTranslations("awooop.tenants.githubTenantReadinessScope");

  return (
    <section className="overflow-hidden border border-[#e0ddd4] bg-white">
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex min-w-0 items-start gap-2">
          <GitBranch className="mt-0.5 h-4 w-4 shrink-0 text-[#d97757]" aria-hidden="true" />
          <div className="min-w-0">
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 max-w-3xl text-xs leading-5 text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <span className="inline-flex border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 text-xs font-semibold text-[#8a5a08]">
            {t("badge")}
          </span>
          <Link
            href="/iwooos"
            className="inline-flex items-center gap-2 border border-[#d8d3c7] bg-white px-3 py-1.5 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
          >
            {t("openIwooos")}
            <ArrowRight className="h-3.5 w-3.5 text-[#77736a]" aria-hidden="true" />
          </Link>
        </div>
      </div>

      <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-2 xl:grid-cols-4">
        {githubTenantReadinessMetrics.map((metric) => {
          const Icon = metric.icon;
          return (
            <div key={metric.key} className="min-h-[122px] bg-white px-4 py-3">
              <div className="flex items-start justify-between gap-3">
                <div className="min-w-0">
                  <p className="text-xs font-semibold text-[#77736a]">
                    {t(`metrics.${metric.key}.label` as never)}
                  </p>
                  <p className="mt-2 break-words font-mono text-2xl font-semibold text-[#141413]">
                    {metric.value}
                  </p>
                </div>
                <span
                  className={cn(
                    "flex h-8 w-8 shrink-0 items-center justify-center border",
                    metric.tone === "warn" && "border-[#d9b36f] bg-[#fff7e8] text-[#8a5a08]",
                    metric.tone === "neutral" && "border-[#d8d3c7] bg-[#faf9f3] text-[#5f5b52]"
                  )}
                >
                  <Icon className="h-4 w-4" aria-hidden="true" />
                </span>
              </div>
              <p className="mt-3 text-xs leading-5 text-[#5f5b52]">
                {t(`metrics.${metric.key}.detail` as never)}
              </p>
            </div>
          );
        })}
      </div>

      <div className="grid min-w-0 gap-4 p-4 xl:grid-cols-[1.1fr_0.9fr]">
        <div className="min-w-0 border border-[#e0ddd4] bg-white">
          <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3 text-xs font-semibold text-[#141413]">
            {t("scopeRefsTitle")}
          </div>
          <div className="divide-y divide-[#eee9dd]">
            {githubTenantReadinessScopes.map((scope) => (
              <div key={scope.key} className="grid gap-3 px-4 py-3 md:grid-cols-[minmax(0,1fr)_96px]">
                <div className="min-w-0">
                  <p className="break-words font-mono text-xs font-semibold text-[#141413]">
                    {scope.name}
                  </p>
                  <p className="mt-1 text-xs leading-5 text-[#5f5b52]">
                    {t(`scopeRefs.${scope.key}` as never)}
                  </p>
                </div>
                <div>
                  <span className="inline-flex border border-[#d9b36f] bg-[#fff7e8] px-2 py-0.5 font-mono text-xs font-semibold text-[#8a5a08]">
                    {scope.status}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="min-w-0 border border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
          <p className="text-xs font-semibold text-[#77736a]">{t("boundaryLabel")}</p>
          <p className="mt-2 text-sm font-semibold text-[#141413]">{t("boundaryTitle")}</p>
          <p className="mt-2 text-xs leading-5 text-[#5f5b52]">{t("boundaryDetail")}</p>
          <div className="mt-4 grid gap-2 break-all font-mono text-xs text-[#141413]">
            {githubTenantReadinessBoundaries.map((boundary) => (
              <span key={boundary}>{boundary}</span>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function OwnerResponseValidationTenantScopePanel() {
  const t = useTranslations("awooop.tenants.ownerResponseValidationScope");
  const metrics = [
    {
      label: t("metrics.packets"),
      value: "4",
      detail: t("metrics.packetsDetail"),
    },
    {
      label: t("metrics.templates"),
      value: "22",
      detail: t("metrics.templatesDetail"),
    },
    {
      label: t("metrics.received"),
      value: "0",
      detail: t("metrics.receivedDetail"),
    },
    {
      label: t("metrics.accepted"),
      value: "0",
      detail: t("metrics.acceptedDetail"),
    },
    {
      label: t("metrics.tenantPolicyChanges"),
      value: "0",
      detail: t("metrics.tenantPolicyChangesDetail"),
    },
    {
      label: t("metrics.displaySections"),
      value: "8",
      detail: t("metrics.displaySectionsDetail"),
    },
  ];

  return (
    <section className="overflow-hidden border border-[#d9d4e6] bg-white">
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#d9d4e6] bg-[#f8f6fc] px-4 py-3">
        <div className="flex min-w-0 items-start gap-2">
          <ListChecks className="mt-0.5 h-4 w-4 shrink-0 text-[#6f5ca8]" aria-hidden="true" />
          <div className="min-w-0">
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 max-w-3xl text-xs leading-5 text-[#5f5a70]">{t("subtitle")}</p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <span className="inline-flex border border-[#b7add8] bg-white px-2 py-0.5 text-xs font-semibold text-[#5b4b91]">
            {t("badge")}
          </span>
          <Link
            href="/iwooos"
            className="inline-flex items-center gap-2 border border-[#b7add8] bg-white px-3 py-1.5 text-xs font-semibold text-[#141413] hover:border-[#6f5ca8]"
          >
            {t("openIwooos")}
            <ArrowRight className="h-3.5 w-3.5 text-[#5f5a70]" aria-hidden="true" />
          </Link>
        </div>
      </div>

      <div className="grid gap-px bg-[#d9d4e6] md:grid-cols-2 xl:grid-cols-6">
        {metrics.map((item) => (
          <div key={item.label} className="min-h-[122px] bg-white px-4 py-3">
            <p className="text-xs font-semibold text-[#5f5a70]">{item.label}</p>
            <p className="mt-2 break-words font-mono text-2xl font-semibold text-[#141413]">{item.value}</p>
            <p className="mt-2 text-xs leading-5 text-[#4f4a60]">{item.detail}</p>
          </div>
        ))}
      </div>

      <div className="grid min-w-0 gap-4 p-4 xl:grid-cols-[1.1fr_0.9fr]">
        <div className="min-w-0 border border-[#d9d4e6] bg-white">
          <div className="border-b border-[#d9d4e6] bg-[#f8f6fc] px-4 py-3 text-xs font-semibold text-[#141413]">
            {t("scopeRefsTitle")}
          </div>
          <div className="divide-y divide-[#e8e3f2]">
            {ownerResponseValidationTenantRefs.map((item) => (
              <div key={item.key} className="grid gap-3 px-4 py-3 md:grid-cols-[72px_minmax(0,1fr)]">
                <span className="font-mono text-xs font-semibold text-[#141413]">{item.phase}</span>
                <div className="min-w-0">
                  <p className="text-sm font-semibold text-[#141413]">
                    {t(`scopeRefs.${item.key}.title` as never)}
                  </p>
                  <p className="mt-1 text-xs leading-5 text-[#4f4a60]">
                    {t(`scopeRefs.${item.key}.detail` as never)}
                  </p>
                  <p className="mt-2 break-all font-mono text-[11px] text-[#5f5a70]">
                    {item.contract}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="min-w-0 border border-[#d9d4e6] bg-[#f8f6fc] px-4 py-3">
          <p className="text-xs font-semibold text-[#5f5a70]">{t("boundaryLabel")}</p>
          <p className="mt-2 text-sm font-semibold text-[#141413]">{t("boundaryTitle")}</p>
          <p className="mt-2 text-xs leading-5 text-[#4f4a60]">{t("boundaryDetail")}</p>
          <div className="mt-4 grid gap-2 break-all font-mono text-xs text-[#141413]">
            {ownerResponseValidationTenantBoundaries.map((boundary) => (
              <span key={boundary}>{boundary}</span>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// =============================================================================
// Main Component
// =============================================================================

export default function TenantsPage() {
  const [tenants, setTenants] = useState<Tenant[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchTenants = useCallback(async () => {
    try {
      setError(null);
      const res = await fetch(`${API_BASE}/api/v1/platform/tenants`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data: ApiResponse = await res.json();
      const rows = Array.isArray(data.tenants) ? data.tenants : data.items;
      setTenants(Array.isArray(rows) ? rows : []);
    } catch (err) {
      setError(err instanceof Error ? err.message : "載入失敗");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchTenants();
  }, [fetchTenants]);

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Building2 className="w-5 h-5 text-brand-accent" aria-hidden="true" />
          <div>
            <h2 className="text-lg font-semibold text-foreground">租戶管理</h2>
            <p className="text-xs text-muted-foreground">
              {loading ? "載入中..." : `共 ${tenants.length} 個租戶`}
            </p>
          </div>
        </div>
        <button
          onClick={fetchTenants}
          disabled={loading}
          className="flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition disabled:opacity-50"
          aria-label="重新整理租戶清單"
        >
          <RefreshCw className={cn("w-4 h-4", loading && "animate-spin")} aria-hidden="true" />
          重新整理
        </button>
      </div>

      <SecurityTenantScopeCandidatePanel />

      <GitHubTenantReadinessScopePanel />

      <OwnerResponseValidationTenantScopePanel />

      {/* Error State */}
      {error && (
        <div className="flex items-start gap-3 p-4 bg-red-900/20 border border-red-800/40 rounded-lg">
          <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" aria-hidden="true" />
          <div>
            <p className="text-sm font-medium text-red-300">無法載入租戶資料</p>
            <p className="text-xs text-red-400 mt-1">{error}</p>
          </div>
        </div>
      )}

      {/* Table */}
      <div className="overflow-hidden border border-[#e0ddd4] bg-white shadow-[0_1px_4px_rgba(0,0,0,0.05)]">
        <div className="overflow-x-auto">
          <table className="w-full" role="table" aria-label="租戶清單">
            <thead>
              <tr className="border-b border-border bg-muted/50">
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  專案 ID
                </th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  名稱
                </th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  模式
                </th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  預算上限 (USD)
                </th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  狀態
                </th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                // Loading skeleton
                Array.from({ length: 5 }).map((_, i) => (
                  <tr key={i} className="border-b border-border">
                    {Array.from({ length: 5 }).map((_, j) => (
                      <td key={j} className="px-4 py-3">
                        <div className="h-5 bg-muted animate-pulse rounded w-24" />
                      </td>
                    ))}
                  </tr>
                ))
              ) : tenants.length === 0 && !error ? (
                <tr>
                  <td colSpan={5} className="px-4 py-16 text-center">
                    <Building2 className="w-10 h-10 text-muted-foreground/30 mx-auto mb-3" aria-hidden="true" />
                    <p className="text-sm text-muted-foreground">尚無租戶資料</p>
                  </td>
                </tr>
              ) : (
                tenants.map((tenant) => (
                  <TenantRow key={tenant.project_id} tenant={tenant} />
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
