/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useEffect } from "react";
import { 
  Smartphone, 
  Download, 
  Plus, 
  RefreshCw, 
  CheckCircle2, 
  AlertTriangle, 
  Play, 
  Code, 
  QrCode, 
  Copy, 
  Check, 
  Layers, 
  ShieldCheck, 
  Building2, 
  Zap, 
  Terminal, 
  Edit3, 
  Share2, 
  HardDrive, 
  Cpu, 
  Sparkles, 
  Search, 
  Filter, 
  CheckSquare, 
  Square,
  X,
  FileCheck,
  ExternalLink,
  ChevronRight
} from "lucide-react";
import { Employee, SaaSTenant, CtoApkBuild } from "../types";

interface CtoApkBuildManagerProps {
  currentUser: Employee;
  tenants?: SaaSTenant[];
  onApkBuildUpdated?: (builds: CtoApkBuild[]) => void;
}

const DEFAULT_TENANTS_LIST = [
  { id: "GLOBAL", name: "Global Default (Semua Tenant & Internal)", code: "GLOBAL" },
  { id: "tenant-median-01", name: "PT Median Usaha Mandiri", code: "MEDIAN" },
  { id: "tenant-sinarmas-02", name: "PT Sinar Mas Retail Enterprise", code: "SINARMAS" },
  { id: "tenant-kios-03", name: "CV Kios Berkah UMKM POS", code: "KIOSPOS" },
  { id: "tenant-eo-04", name: "PT Wahana Event Organizer", code: "EVENTO" }
];

const INITIAL_APK_BUILDS: CtoApkBuild[] = [
  {
    id: "apk-build-001",
    versionName: "2.5.0-release",
    versionCode: 250,
    targetTenantId: "GLOBAL",
    targetTenantName: "Global Default (Semua Tenant & Internal)",
    packageName: "id.co.ptmedian.emsclient",
    apkFileName: "EMS_Mobile_v2.5.0_Global_Release.apk",
    fileSizeBytes: 29810000, // 29.8 MB
    targetSdkVersion: 34,
    minSdkVersion: 21, // Android 5.0+ Universal Compatibility
    buildChannel: "RELEASE",
    status: "READY",
    builtAt: "2026-08-07T02:15:00.000Z",
    builtBy: "Dian Ermawan (CTO)",
    downloadCount: 342,
    releaseNotes: "Dukungan universal Android 5.0+ s/d Android 15, suara Beep Notifikasi QR Absensi, Sync Realtime Supabase-Firebase, & Optimasi SQLite Caching.",
    apiGatewayUrl: "https://api.median.co.id/v2",
    featuresIncluded: [
      "Suara Beep Notifikasi QR Absensi",
      "Realtime Sync Supabase & Firebase",
      "Offline Database Cache (SQLite)",
      "Biometric Fingerprint Auth",
      "DMS Document Scanner Mobile",
      "Push Notification FCM"
    ],
    keystoreAlias: "ems-enterprise-release-key",
    sha256Fingerprint: "SHA256:A1:B2:C3:D4:E5:F6:78:90:12:34:56:78:90:AB:CD:EF:12:34:56:78"
  },
  {
    id: "apk-build-002",
    versionName: "2.4.8-tenant-custom",
    versionCode: 248,
    targetTenantId: "tenant-median-01",
    targetTenantName: "PT Median Usaha Mandiri",
    packageName: "id.co.ptmedian.ems.tenant.median",
    apkFileName: "EMS_Mobile_v2.4.8_PT_Median_Usaha.apk",
    fileSizeBytes: 28400000, // 28.4 MB
    targetSdkVersion: 34,
    minSdkVersion: 21, // Android 5.0+
    buildChannel: "RELEASE",
    status: "READY",
    builtAt: "2026-08-05T14:30:00.000Z",
    builtBy: "Dian Ermawan (CTO)",
    downloadCount: 189,
    releaseNotes: "Custom branding warna institusi, integrasi Absensi GPS Portal Kantor, & Pengajuan Cuti Mandiri.",
    apiGatewayUrl: "https://app.median.co.id/api/v2",
    featuresIncluded: [
      "Branding Logo PT Median",
      "Geofencing Portal Kantor GPS",
      "Persetujuan Cuti Online",
      "DMS Scan Kamera Mobile"
    ],
    keystoreAlias: "tenant-median-key",
    sha256Fingerprint: "SHA256:88:77:66:55:44:33:22:11:00:FF:EE:DD:CC:BB:AA:99:88:77:66"
  },
  {
    id: "apk-build-003",
    versionName: "1.9.5-pos-kios",
    versionCode: 195,
    targetTenantId: "tenant-kios-03",
    targetTenantName: "CV Kios Berkah UMKM POS",
    packageName: "id.co.ptmedian.microsaas.kiospos",
    apkFileName: "MicroSaaS_KasirPOS_v1.9.5_KiosBerkah.apk",
    fileSizeBytes: 18200000, // 18.2 MB
    targetSdkVersion: 33,
    minSdkVersion: 21,
    buildChannel: "RELEASE",
    status: "READY",
    builtAt: "2026-08-01T09:10:00.000Z",
    builtBy: "Frontend Dev Team",
    downloadCount: 512,
    releaseNotes: "Cetak Nota Thermal Bluetooth, Struk QRIS Otomatis, Katalog Produk Kasir & Laporan Harian.",
    apiGatewayUrl: "https://pos.kiosberkah.id/api",
    featuresIncluded: [
      "Kasir POS Penjualan",
      "Struk QRIS Dinamis",
      "Cetak Printer Thermal Bluetooth",
      "Katalog Produk & Diskon"
    ],
    keystoreAlias: "microsaas-pos-key",
    sha256Fingerprint: "SHA256:11:22:33:44:55:66:77:88:99:00:AA:BB:CC:DD:EE:FF:00:11:22"
  }
];

export const CtoApkBuildManager: React.FC<CtoApkBuildManagerProps> = ({
  currentUser,
  tenants = [],
  onApkBuildUpdated
}) => {
  const [apkBuilds, setApkBuilds] = useState<CtoApkBuild[]>(() => {
    const saved = localStorage.getItem("cto_apk_builds");
    if (saved) {
      try {
        return JSON.parse(saved);
      } catch (e) {
        return INITIAL_APK_BUILDS;
      }
    }
    return INITIAL_APK_BUILDS;
  });

  const [searchQuery, setSearchQuery] = useState("");
  const [filterTenant, setFilterTenant] = useState("ALL");
  const [filterChannel, setFilterChannel] = useState("ALL");

  // Modal State for Build / Create New APK
  const [isBuildModalOpen, setIsBuildModalOpen] = useState(false);
  const [editingApkId, setEditingApkId] = useState<string | null>(null);

  // Form State
  const [buildForm, setBuildForm] = useState({
    versionName: "2.5.1-release",
    versionCode: 251,
    targetTenantId: "GLOBAL",
    targetTenantName: "Global Default (Semua Tenant & Internal)",
    packageName: "id.co.ptmedian.emsclient",
    targetSdkVersion: 34,
    minSdkVersion: 21, // Android 5.0 Lollipop+ (Universal backward compatibility)
    buildChannel: "RELEASE" as 'RELEASE' | 'STAGING' | 'BETA' | 'HOTFIX',
    apiGatewayUrl: "https://api.median.co.id/v2",
    releaseNotes: "Dukungan universal Android 5.0+ s/d Android 15 (Bebas Error Minimal Android 9), perbaikan Bug Fixes, & Suara Beep QR Absensi.",
    featuresIncluded: [
      "Suara Beep Notifikasi QR Absensi",
      "Realtime Sync Supabase & Firebase",
      "Offline Database Cache (SQLite)",
      "Biometric Fingerprint Auth"
    ]
  });

  // Build Simulation State
  const [isBuildingApk, setIsBuildingApk] = useState(false);
  const [buildLogs, setBuildLogs] = useState<string[]>([]);
  const [buildProgress, setBuildProgress] = useState<number>(0);

  // Download & QR Code Preview Modal State
  const [qrModalApk, setQrModalApk] = useState<CtoApkBuild | null>(null);
  const [copiedApkId, setCopiedApkId] = useState<string | null>(null);

  // Combine default tenant options with passed prop tenants
  const availableTenants = [
    { id: "GLOBAL", name: "Global Default (Semua Tenant & Internal)", code: "GLOBAL" },
    ...tenants.map(t => ({ id: t.id, name: t.name, code: t.code })),
    ...DEFAULT_TENANTS_LIST.filter(d => d.id !== "GLOBAL" && !tenants.some(t => t.id === d.id))
  ];

  // Save builds to localStorage
  useEffect(() => {
    localStorage.setItem("cto_apk_builds", JSON.stringify(apkBuilds));
    if (onApkBuildUpdated) {
      onApkBuildUpdated(apkBuilds);
    }
  }, [apkBuilds]);

  // Filtered builds list
  const filteredBuilds = apkBuilds.filter(build => {
    const matchesSearch = build.versionName.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          build.releaseNotes.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          build.packageName.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          build.targetTenantName.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesTenant = filterTenant === "ALL" || build.targetTenantId === filterTenant;
    const matchesChannel = filterChannel === "ALL" || build.buildChannel === filterChannel;

    return matchesSearch && matchesTenant && matchesChannel;
  });

  // Handler Execute Build APK Terbaru
  const handleStartBuildApk = () => {
    setIsBuildingApk(true);
    setBuildProgress(5);
    setBuildLogs(["[00:01] 🚀 Memulai kompilasi CTO Mobile APK Build Engine..."]);

    const tenantObj = availableTenants.find(t => t.id === buildForm.targetTenantId) || availableTenants[0];

    const logSteps = [
      { progress: 20, log: "[00:03] 🔍 Validating AndroidManifest.xml, Target SDK 34, & Permissions..." },
      { progress: 40, log: "[00:06] ⚡ Compiling React Native & Kotlin Native Mobile App Bundle..." },
      { progress: 60, log: "[00:09] 🛡️ Applying ProGuard obfuscation, Dexing, & SQLite DB Cache Injection..." },
      { progress: 80, log: `[00:12] 🔑 Signing APK with Enterprise V2/V3 Keystore for ${tenantObj.name}...` },
      { progress: 100, log: "[00:15] ✅ Build Selesai! Paket APK berhasil dibuat & diverifikasi." }
    ];

    let stepIndex = 0;
    const interval = setInterval(() => {
      if (stepIndex < logSteps.length) {
        const step = logSteps[stepIndex];
        setBuildProgress(step.progress);
        setBuildLogs(prev => [...prev, step.log]);
        stepIndex++;
      } else {
        clearInterval(interval);
        setTimeout(() => {
          setIsBuildingApk(false);

          const generatedFileName = `EMS_Mobile_v${buildForm.versionName}_${tenantObj.code}_${buildForm.buildChannel}.apk`;
          const generatedFileSize = Math.floor(25000000 + Math.random() * 8000000); // ~25-33MB

          if (editingApkId) {
            // Update existing APK build
            setApkBuilds(prev => prev.map(b => {
              if (b.id === editingApkId) {
                return {
                  ...b,
                  versionName: buildForm.versionName,
                  versionCode: buildForm.versionCode,
                  targetTenantId: buildForm.targetTenantId,
                  targetTenantName: tenantObj.name,
                  packageName: buildForm.packageName,
                  apkFileName: generatedFileName,
                  fileSizeBytes: generatedFileSize,
                  targetSdkVersion: buildForm.targetSdkVersion,
                  minSdkVersion: buildForm.minSdkVersion,
                  buildChannel: buildForm.buildChannel,
                  builtAt: new Date().toISOString(),
                  builtBy: `${currentUser.name} (CTO Dev)`,
                  releaseNotes: buildForm.releaseNotes,
                  apiGatewayUrl: buildForm.apiGatewayUrl,
                  featuresIncluded: buildForm.featuresIncluded
                };
              }
              return b;
            }));
          } else {
            // Create brand new APK build
            const newBuild: CtoApkBuild = {
              id: `apk-build-${Date.now()}`,
              versionName: buildForm.versionName,
              versionCode: buildForm.versionCode,
              targetTenantId: buildForm.targetTenantId,
              targetTenantName: tenantObj.name,
              packageName: buildForm.packageName,
              apkFileName: generatedFileName,
              fileSizeBytes: generatedFileSize,
              targetSdkVersion: buildForm.targetSdkVersion,
              minSdkVersion: buildForm.minSdkVersion,
              buildChannel: buildForm.buildChannel,
              status: "READY",
              builtAt: new Date().toISOString(),
              builtBy: `${currentUser.name} (CTO Dev)`,
              downloadCount: 0,
              releaseNotes: buildForm.releaseNotes,
              apiGatewayUrl: buildForm.apiGatewayUrl,
              featuresIncluded: buildForm.featuresIncluded,
              keystoreAlias: `keystore-${tenantObj.code.toLowerCase()}`,
              sha256Fingerprint: `SHA256:${Math.random().toString(16).substring(2, 10).toUpperCase()}:77:88:99:00:AA`
            };
            setApkBuilds(prev => [newBuild, ...prev]);
            
            // Automatically trigger download of newly built APK
            triggerApkBinaryDownload(newBuild);
          }

          setIsBuildModalOpen(false);
          setEditingApkId(null);
        }, 800);
      }
    }, 400);
  };

  // Direct APK Binary Download Generator
  const triggerApkBinaryDownload = (build: CtoApkBuild) => {
    // Increment download counter
    setApkBuilds(prev => prev.map(b => b.id === build.id ? { ...b, downloadCount: b.downloadCount + 1 } : b));

    const apkManifestPayload = {
      manifestHeader: "ANDROID_PACKAGE_ARCHIVE_BINARY_PAYLOAD",
      applicationName: `EMS Mobile Client - ${build.targetTenantName}`,
      versionName: build.versionName,
      versionCode: build.versionCode,
      packageName: build.packageName,
      targetTenantId: build.targetTenantId,
      targetSdkVersion: build.targetSdkVersion,
      builtAt: build.builtAt,
      builtBy: build.builtBy,
      apiGatewayUrl: build.apiGatewayUrl,
      features: build.featuresIncluded,
      sha256Signature: build.sha256Fingerprint,
      installationGuide: "1. Buka file .apk ini di HP Android Anda. 2. Izinkan 'Install from Unknown Sources'. 3. Selesai!"
    };

    const blob = new Blob([JSON.stringify(apkManifestPayload, null, 2)], { 
      type: "application/vnd.android.package-archive" 
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = build.apkFileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // Copy Download Link Handler
  const handleCopyDownloadLink = (build: CtoApkBuild) => {
    const downloadUrl = `${window.location.origin}/download/apk/${build.apkFileName}`;
    navigator.clipboard.writeText(downloadUrl);
    setCopiedApkId(build.id);
    setTimeout(() => setCopiedApkId(null), 2000);
  };

  // Toggle feature inclusion in form
  const toggleFeature = (feature: string) => {
    setBuildForm(prev => {
      const exists = prev.featuresIncluded.includes(feature);
      if (exists) {
        return { ...prev, featuresIncluded: prev.featuresIncluded.filter(f => f !== feature) };
      } else {
        return { ...prev, featuresIncluded: [...prev.featuresIncluded, feature] };
      }
    });
  };

  const AVAILABLE_FEATURE_OPTIONS = [
    "Suara Beep Notifikasi QR Absensi",
    "Realtime Sync Supabase & Firebase",
    "Offline Database Cache (SQLite)",
    "Biometric Fingerprint Auth",
    "DMS Document Scanner Mobile",
    "Push Notification FCM",
    "Geofencing Portal Kantor GPS",
    "Kasir POS Penjualan",
    "Cetak Printer Thermal Bluetooth",
    "Workflow Approval Notifikasi"
  ];

  return (
    <div className="space-y-6 font-sans">
      
      {/* HEADER BANNER: CTO FRONTEND MOBILE BUILD & TENANT APK DISTRIBUTION */}
      <div className="bg-slate-900/95 border border-sky-500/40 rounded-2xl p-6 text-white space-y-6 shadow-xl relative overflow-hidden">
        <div className="absolute top-0 right-0 p-8 opacity-10 pointer-events-none">
          <Smartphone className="w-64 h-64 text-sky-400" />
        </div>

        <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4 border-b border-slate-800 pb-5">
          <div>
            <div className="flex items-center gap-2">
              <span className="text-[10px] font-mono font-bold uppercase bg-sky-500/20 text-sky-300 border border-sky-500/30 px-2.5 py-0.5 rounded flex items-center gap-1">
                <Cpu className="w-3 h-3 text-sky-400" />
                CTO FRONTEND DEVELOPMENT & SAAS DISTRIBUTION
              </span>
              <span className="text-[10px] font-mono font-bold uppercase bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 px-2.5 py-0.5 rounded">
                GRADLE v8.4 • ANDROID SDK 34
              </span>
            </div>

            <h3 className="text-xl font-black text-white uppercase tracking-tight mt-1.5 flex items-center gap-2.5">
              <Smartphone className="w-6 h-6 text-sky-400" />
              Generator & Distribusi File .APK Mobile Tenant
            </h3>

            <p className="text-xs text-slate-300 mt-1 max-w-3xl leading-relaxed">
              Modul pengembangan CTO untuk membuat (build), memperbarui (update patch), dan mendistribusikan file installer Android **.APK** terbaru bagi seluruh pegawai internal dan tenant/klien penyewa aplikasi SaaS.
            </p>
          </div>

          <button
            onClick={() => {
              setEditingApkId(null);
              setBuildForm({
                versionName: `2.5.${apkBuilds.length + 1}-release`,
                versionCode: 250 + apkBuilds.length + 1,
                targetTenantId: "GLOBAL",
                targetTenantName: "Global Default (Semua Tenant & Internal)",
                packageName: "id.co.ptmedian.emsclient",
                targetSdkVersion: 34,
                minSdkVersion: 24,
                buildChannel: "RELEASE",
                apiGatewayUrl: "https://api.median.co.id/v2",
                releaseNotes: "Build rilis terbaru dengan penambahan Suara Beep QR Absensi, Sync Realtime Supabase-Firebase & optimasi stabilitas.",
                featuresIncluded: [
                  "Suara Beep Notifikasi QR Absensi",
                  "Realtime Sync Supabase & Firebase",
                  "Offline Database Cache (SQLite)",
                  "Biometric Fingerprint Auth"
                ]
              });
              setIsBuildModalOpen(true);
            }}
            className="px-5 py-3 bg-gradient-to-r from-sky-500 to-blue-600 hover:from-sky-400 hover:to-blue-500 text-slate-950 font-black text-xs uppercase tracking-wider rounded-xl transition-all shadow-lg shadow-sky-500/25 flex items-center gap-2 shrink-0 cursor-pointer"
          >
            <Plus className="w-4 h-4 stroke-[3]" />
            <span>Create / Build File .APK Terbaru</span>
          </button>
        </div>

        {/* METRIC METRICS CARDS */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 font-mono text-xs">
          <div className="p-4 bg-slate-950/80 border border-slate-800 rounded-xl space-y-1">
            <span className="text-slate-400 text-[10px] uppercase block">Total Rilis APK Tersedia:</span>
            <strong className="text-sky-300 text-lg font-black block">{apkBuilds.length} Paket APK</strong>
            <span className="text-[10px] text-slate-400 block">Termasuk Global & Tenant SaaS</span>
          </div>

          <div className="p-4 bg-slate-950/80 border border-slate-800 rounded-xl space-y-1">
            <span className="text-slate-400 text-[10px] uppercase block">Versi Rilis Produksi Utama:</span>
            <strong className="text-emerald-400 text-base font-bold block">
              {apkBuilds[0]?.versionName || "v2.5.0-release"}
            </strong>
            <span className="text-[10px] text-slate-400 block">Target Android SDK 34 (Android 14/15)</span>
          </div>

          <div className="p-4 bg-slate-950/80 border border-slate-800 rounded-xl space-y-1">
            <span className="text-slate-400 text-[10px] uppercase block">Total Di-download User / Tenant:</span>
            <strong className="text-amber-400 text-lg font-black block">
              {apkBuilds.reduce((sum, b) => sum + b.downloadCount, 0).toLocaleString("id-ID")} x Download
            </strong>
            <span className="text-[10px] text-slate-400 block">Via Direct Link & QR Code Scan</span>
          </div>

          <div className="p-4 bg-slate-950/80 border border-slate-800 rounded-xl space-y-1">
            <span className="text-slate-400 text-[10px] uppercase block">Status Keystore Keamanan:</span>
            <strong className="text-emerald-400 font-bold flex items-center gap-1.5 text-xs">
              <ShieldCheck className="w-4 h-4 text-emerald-400" />
              ENTERPRISE SIGNED
            </strong>
            <span className="text-[10px] text-slate-400 block">Keystore V2/V3 Validated</span>
          </div>
        </div>
      </div>

      {/* FILTER & SEARCH TOOLBAR */}
      <div className="bg-slate-900/90 border border-slate-800 rounded-2xl p-4 flex flex-col md:flex-row items-stretch md:items-center justify-between gap-4">
        
        {/* Search */}
        <div className="relative flex-1">
          <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-3" />
          <input
            type="text"
            placeholder="Cari berdasarkan versi, nama file, tenant, atau release notes..."
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            className="w-full bg-slate-950 border border-slate-800 rounded-xl pl-10 pr-4 py-2.5 text-xs text-white focus:outline-none focus:border-sky-400 font-mono"
          />
        </div>

        {/* Filters */}
        <div className="flex flex-wrap items-center gap-3 text-xs font-mono">
          <div className="flex items-center gap-2">
            <Filter className="w-3.5 h-3.5 text-slate-400" />
            <span className="text-slate-400 text-[10px] uppercase font-bold">Target Tenant:</span>
            <select
              value={filterTenant}
              onChange={e => setFilterTenant(e.target.value)}
              className="bg-slate-950 border border-slate-800 text-white text-xs rounded-xl px-3 py-2 focus:outline-none focus:border-sky-400"
            >
              <option value="ALL">Semua Target Tenant</option>
              {availableTenants.map(t => (
                <option key={t.id} value={t.id}>{t.name}</option>
              ))}
            </select>
          </div>

          <div className="flex items-center gap-2">
            <span className="text-slate-400 text-[10px] uppercase font-bold">Channel:</span>
            <select
              value={filterChannel}
              onChange={e => setFilterChannel(e.target.value)}
              className="bg-slate-950 border border-slate-800 text-white text-xs rounded-xl px-3 py-2 focus:outline-none focus:border-sky-400"
            >
              <option value="ALL">Semua Channel</option>
              <option value="RELEASE">RELEASE</option>
              <option value="STAGING">STAGING</option>
              <option value="BETA">BETA</option>
              <option value="HOTFIX">HOTFIX</option>
            </select>
          </div>
        </div>

      </div>

      {/* DAFTAR PAKET FILE .APK TERSEDIA FOR SAAS TENANTS & USERS */}
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="text-xs font-black uppercase text-slate-300 tracking-wider flex items-center gap-2">
            <Layers className="w-4 h-4 text-sky-400" />
            Daftar Paket Installer Mobile .APK Terkompilasi ({filteredBuilds.length})
          </h3>

          <span className="text-[11px] font-mono text-slate-400">
            Klik <strong className="text-emerald-400 font-bold">"Download File .APK"</strong> untuk mengunduh installer langsung.
          </span>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredBuilds.map(build => (
            <div
              key={build.id}
              className="bg-slate-900/90 border border-slate-800 hover:border-sky-500/40 rounded-2xl p-5 text-white space-y-4 shadow-xl flex flex-col justify-between transition-all group"
            >
              <div className="space-y-3">
                {/* Header Card */}
                <div className="flex items-start justify-between gap-2 border-b border-slate-800/80 pb-3">
                  <div>
                    <div className="flex items-center gap-1.5 flex-wrap">
                      <span className="px-2 py-0.5 bg-sky-500/20 text-sky-300 border border-sky-500/30 text-[9px] font-mono font-bold uppercase rounded">
                        {build.buildChannel}
                      </span>
                      <span className="px-2 py-0.5 bg-slate-800 text-slate-300 text-[9px] font-mono font-bold rounded">
                        SDK {build.targetSdkVersion}
                      </span>
                      <span className="px-2 py-0.5 bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 text-[9px] font-mono font-bold rounded">
                        {(build.fileSizeBytes / (1024 * 1024)).toFixed(1)} MB
                      </span>
                    </div>

                    <h4 className="text-base font-black text-white mt-1.5 flex items-center gap-2">
                      <Smartphone className="w-4 h-4 text-sky-400" />
                      v{build.versionName}
                    </h4>
                  </div>

                  <span className="text-[10px] font-mono text-amber-400 font-bold bg-amber-500/10 border border-amber-500/20 px-2 py-1 rounded">
                    {build.downloadCount}x Downloaded
                  </span>
                </div>

                {/* Target Tenant Name */}
                <div className="p-2.5 bg-slate-950 border border-slate-800 rounded-xl space-y-1 font-mono text-xs">
                  <span className="text-slate-400 text-[9px] uppercase block">Peruntukan Tenant / Klien:</span>
                  <strong className="text-sky-300 block truncate">{build.targetTenantName}</strong>
                  <span className="text-slate-400 text-[10px] block truncate font-mono">Pkg: {build.packageName}</span>
                </div>

                {/* Release Notes */}
                <div className="space-y-1">
                  <span className="text-[10px] font-mono text-slate-400 uppercase block font-bold">Release Patch Notes:</span>
                  <p className="text-xs text-slate-300 bg-slate-950/60 p-2.5 rounded-xl border border-slate-800/80 line-clamp-3 leading-relaxed">
                    {build.releaseNotes}
                  </p>
                </div>

                {/* Included Features */}
                <div className="space-y-1">
                  <span className="text-[10px] font-mono text-slate-400 uppercase block font-bold">Fitur Terkandung:</span>
                  <div className="flex flex-wrap gap-1">
                    {build.featuresIncluded.map((feat, idx) => (
                      <span key={idx} className="px-2 py-0.5 bg-slate-800/80 text-slate-300 text-[10px] font-mono rounded">
                        ✓ {feat}
                      </span>
                    ))}
                  </div>
                </div>
              </div>

              {/* Card Bottom Actions */}
              <div className="pt-4 border-t border-slate-800 space-y-2">
                <button
                  onClick={() => triggerApkBinaryDownload(build)}
                  className="w-full py-2.5 bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-400 hover:to-teal-500 text-slate-950 font-black uppercase text-xs tracking-wider rounded-xl transition-all shadow-lg shadow-emerald-500/20 flex items-center justify-center gap-2 cursor-pointer"
                >
                  <Download className="w-4 h-4 stroke-[2.5]" />
                  <span>Download File .APK Terbaru</span>
                </button>

                <div className="grid grid-cols-2 gap-2 font-mono text-[11px]">
                  <button
                    onClick={() => setQrModalApk(build)}
                    className="py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 rounded-lg transition-colors flex items-center justify-center gap-1 cursor-pointer"
                  >
                    <QrCode className="w-3.5 h-3.5 text-sky-400" />
                    <span>Scan QR HP</span>
                  </button>

                  <button
                    onClick={() => handleCopyDownloadLink(build)}
                    className="py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 rounded-lg transition-colors flex items-center justify-center gap-1 cursor-pointer"
                  >
                    {copiedApkId === build.id ? (
                      <Check className="w-3.5 h-3.5 text-emerald-400" />
                    ) : (
                      <Copy className="w-3.5 h-3.5 text-amber-400" />
                    )}
                    <span>{copiedApkId === build.id ? "Tersalin!" : "Salin Link"}</span>
                  </button>
                </div>
              </div>

            </div>
          ))}
        </div>
      </div>

      {/* MATRIX DISTRIBUTION UNTUK SAAS TENANTS / CLIENTS */}
      <div className="bg-slate-900/90 border border-slate-800 rounded-2xl p-6 text-white space-y-4 shadow-xl">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-slate-800 pb-3">
          <div>
            <h3 className="text-sm font-black uppercase text-white flex items-center gap-2">
              <Building2 className="w-4 h-4 text-sky-400" />
              Matriks Distribusi APK Sewa SaaS Tenant & Klien UMKM
            </h3>
            <p className="text-xs text-slate-400 mt-0.5">
              Portal unduh instan installer .APK berlisensi khusus untuk setiap tenant penyewa aplikasi.
            </p>
          </div>
          <span className="text-[10px] font-mono text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-2.5 py-1 rounded">
            DIRECT DOWNLOAD AUTHORIZED
          </span>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left font-mono text-xs text-slate-300">
            <thead className="bg-slate-950 text-slate-400 text-[10px] uppercase border-b border-slate-800">
              <tr>
                <th className="p-3">SaaS Tenant / Klien</th>
                <th className="p-3">Kode Tenant</th>
                <th className="p-3">Versi APK Aktif</th>
                <th className="p-3">Ukuran File</th>
                <th className="p-3">Aksi Unduh File .APK</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-800/60">
              {availableTenants.map(t => {
                const tenantApk = apkBuilds.find(b => b.targetTenantId === t.id) || apkBuilds[0];
                return (
                  <tr key={t.id} className="hover:bg-slate-800/40 transition-colors">
                    <td className="p-3 font-bold text-white flex items-center gap-2">
                      <Building2 className="w-3.5 h-3.5 text-sky-400 shrink-0" />
                      <span>{t.name}</span>
                    </td>
                    <td className="p-3">
                      <span className="px-2 py-0.5 bg-slate-800 text-amber-300 rounded text-[10px] font-bold">
                        {t.code}
                      </span>
                    </td>
                    <td className="p-3">
                      <strong className="text-emerald-400">v{tenantApk.versionName}</strong>
                    </td>
                    <td className="p-3 text-slate-400">
                      {(tenantApk.fileSizeBytes / (1024 * 1024)).toFixed(1)} MB
                    </td>
                    <td className="p-3">
                      <button
                        onClick={() => triggerApkBinaryDownload(tenantApk)}
                        className="px-3 py-1.5 bg-sky-500 hover:bg-sky-400 text-slate-950 font-black text-[11px] uppercase rounded-lg transition-colors flex items-center gap-1 cursor-pointer"
                      >
                        <Download className="w-3.5 h-3.5" />
                        <span>Unduh .APK ({t.code})</span>
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* CREATE / UPDATE NEW APK BUILD MODAL */}
      {isBuildModalOpen && (
        <div className="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-sm flex items-center justify-center p-4 font-sans">
          <div className="bg-slate-900 border border-sky-500/50 rounded-2xl max-w-2xl w-full p-6 text-white space-y-5 shadow-2xl max-h-[90vh] overflow-y-auto">
            
            <div className="flex items-center justify-between border-b border-slate-800 pb-3">
              <div>
                <span className="text-[10px] font-mono font-bold text-sky-400 uppercase bg-sky-500/20 px-2 py-0.5 rounded">
                  CTO COMPILER & BUILD ENGINE
                </span>
                <h3 className="text-base font-black text-white uppercase tracking-wide mt-1 flex items-center gap-2">
                  <Smartphone className="w-5 h-5 text-sky-400" />
                  {editingApkId ? "Update & Re-build Package .APK" : "Build & Kompilasi File .APK Terbaru"}
                </h3>
              </div>
              <button onClick={() => setIsBuildModalOpen(false)} className="text-slate-400 hover:text-white font-bold text-xs">Tutup [X]</button>
            </div>

            {isBuildingApk ? (
              <div className="space-y-4 py-8 text-center font-mono">
                <RefreshCw className="w-12 h-12 text-sky-400 animate-spin mx-auto" />
                <div className="space-y-1">
                  <h4 className="text-sm font-black text-white uppercase">Proses Kompilasi APK Sedang Berjalan...</h4>
                  <p className="text-xs text-sky-300">Men-generate paket file binary .apk untuk {buildForm.targetTenantName}</p>
                </div>

                {/* Progress Bar */}
                <div className="w-full bg-slate-950 h-3 rounded-full overflow-hidden border border-slate-800 max-w-md mx-auto">
                  <div
                    className="bg-gradient-to-r from-sky-500 to-emerald-400 h-full transition-all duration-300"
                    style={{ width: `${buildProgress}%` }}
                  ></div>
                </div>

                {/* Live Logs Terminal */}
                <div className="bg-slate-950 border border-slate-800 rounded-xl p-4 text-left font-mono text-[11px] text-emerald-300 space-y-1 max-h-48 overflow-y-auto max-w-lg mx-auto">
                  {buildLogs.map((log, idx) => (
                    <div key={idx}>{log}</div>
                  ))}
                </div>
              </div>
            ) : (
              <form onSubmit={e => { e.preventDefault(); handleStartBuildApk(); }} className="space-y-4 text-xs font-mono">
                
                {/* Target Tenant Selection */}
                <div>
                  <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">
                    Target Peruntukan Tenant / Klien Sewa SaaS:
                  </label>
                  <select
                    value={buildForm.targetTenantId}
                    onChange={e => {
                      const selected = availableTenants.find(t => t.id === e.target.value);
                      setBuildForm(prev => ({
                        ...prev,
                        targetTenantId: e.target.value,
                        targetTenantName: selected ? selected.name : "Global Default",
                        packageName: e.target.value === "GLOBAL" 
                          ? "id.co.ptmedian.emsclient" 
                          : `id.co.ptmedian.ems.tenant.${selected?.code.toLowerCase() || 'custom'}`
                      }));
                    }}
                    className="w-full bg-slate-950 border border-slate-800 rounded-xl p-3 text-white focus:outline-none focus:border-sky-400 font-bold"
                  >
                    {availableTenants.map(t => (
                      <option key={t.id} value={t.id}>{t.name} ({t.code})</option>
                    ))}
                  </select>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">
                      Versi Rilis (Version Name)
                    </label>
                    <input
                      type="text"
                      required
                      value={buildForm.versionName}
                      onChange={e => setBuildForm(prev => ({ ...prev, versionName: e.target.value }))}
                      placeholder="e.g. 2.5.0-release"
                      className="w-full bg-slate-950 border border-slate-800 rounded-xl p-2.5 text-white focus:outline-none focus:border-sky-400"
                    />
                  </div>

                  <div>
                    <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">
                      Version Code (Integer)
                    </label>
                    <input
                      type="number"
                      required
                      value={buildForm.versionCode}
                      onChange={e => setBuildForm(prev => ({ ...prev, versionCode: parseInt(e.target.value) || 250 }))}
                      className="w-full bg-slate-950 border border-slate-800 rounded-xl p-2.5 text-white focus:outline-none focus:border-sky-400"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">
                      Android Package Name
                    </label>
                    <input
                      type="text"
                      required
                      value={buildForm.packageName}
                      onChange={e => setBuildForm(prev => ({ ...prev, packageName: e.target.value }))}
                      className="w-full bg-slate-950 border border-slate-800 rounded-xl p-2.5 text-sky-300 focus:outline-none focus:border-sky-400"
                    />
                  </div>

                  <div>
                    <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">
                      Build Channel
                    </label>
                    <select
                      value={buildForm.buildChannel}
                      onChange={e => setBuildForm(prev => ({ ...prev, buildChannel: e.target.value as any }))}
                      className="w-full bg-slate-950 border border-slate-800 rounded-xl p-2.5 text-white focus:outline-none focus:border-sky-400"
                    >
                      <option value="RELEASE">RELEASE (Produksi)</option>
                      <option value="STAGING">STAGING (Testing)</option>
                      <option value="BETA">BETA (Trial)</option>
                      <option value="HOTFIX">HOTFIX (Perbaikan Urgent)</option>
                    </select>
                  </div>
                </div>

                {/* Release Notes */}
                <div>
                  <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">
                    Catatan Rilis (Release Notes & Patch Changelog):
                  </label>
                  <textarea
                    rows={3}
                    required
                    value={buildForm.releaseNotes}
                    onChange={e => setBuildForm(prev => ({ ...prev, releaseNotes: e.target.value }))}
                    className="w-full bg-slate-950 border border-slate-800 rounded-xl p-3 text-slate-200 focus:outline-none focus:border-sky-400"
                  ></textarea>
                </div>

                {/* Features Included Checklist */}
                <div>
                  <label className="block text-slate-400 uppercase font-bold text-[10px] mb-1">
                    Fitur & Modul Ditamankan Dalam APK:
                  </label>
                  <div className="grid grid-cols-2 gap-2 p-3 bg-slate-950 border border-slate-800 rounded-xl max-h-36 overflow-y-auto">
                    {AVAILABLE_FEATURE_OPTIONS.map((feat, idx) => {
                      const checked = buildForm.featuresIncluded.includes(feat);
                      return (
                        <div
                          key={idx}
                          onClick={() => toggleFeature(feat)}
                          className="flex items-center gap-2 cursor-pointer text-[11px] text-slate-300 hover:text-white"
                        >
                          {checked ? (
                            <CheckSquare className="w-4 h-4 text-emerald-400 shrink-0" />
                          ) : (
                            <Square className="w-4 h-4 text-slate-600 shrink-0" />
                          )}
                          <span>{feat}</span>
                        </div>
                      );
                    })}
                  </div>
                </div>

                {/* Submit Action */}
                <div className="flex items-center justify-end gap-2 pt-3 border-t border-slate-800">
                  <button
                    type="button"
                    onClick={() => setIsBuildModalOpen(false)}
                    className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-bold rounded-xl"
                  >
                    Batal
                  </button>

                  <button
                    type="submit"
                    className="px-5 py-2.5 bg-gradient-to-r from-sky-500 to-blue-600 hover:from-sky-400 hover:to-blue-500 text-slate-950 font-black text-xs uppercase tracking-wider rounded-xl shadow-lg shadow-sky-500/20 flex items-center gap-1.5 cursor-pointer"
                  >
                    <Play className="w-4 h-4 fill-slate-950" />
                    <span>Jalankan Build & Unduh File .APK</span>
                  </button>
                </div>

              </form>
            )}

          </div>
        </div>
      )}

      {/* QR CODE MOBILE SCAN MODAL */}
      {qrModalApk && (
        <div className="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-sm flex items-center justify-center p-4 font-sans">
          <div className="bg-slate-900 border border-sky-500/50 rounded-2xl max-w-sm w-full p-6 text-white space-y-4 text-center shadow-2xl">
            <div className="flex items-center justify-between border-b border-slate-800 pb-2">
              <h3 className="text-xs font-black text-sky-400 uppercase tracking-wide flex items-center gap-1.5">
                <QrCode className="w-4 h-4" />
                Scan QR Download APK Mobile
              </h3>
              <button onClick={() => setQrModalApk(null)} className="text-slate-400 hover:text-white font-bold text-xs">X</button>
            </div>

            <div className="p-4 bg-white rounded-2xl inline-block shadow-inner mx-auto">
              {/* Simulated High-Res QR Matrix */}
              <div className="w-44 h-44 bg-slate-950 p-2 rounded-xl flex flex-col items-center justify-center text-center space-y-2">
                <QrCode className="w-24 h-24 text-sky-400 animate-pulse" />
                <span className="text-[10px] text-slate-400 font-mono">SCAN VIA KAMERA HP</span>
              </div>
            </div>

            <div className="space-y-1 font-mono text-xs">
              <strong className="text-white block text-sm">v{qrModalApk.versionName}</strong>
              <span className="text-slate-400 text-[10px] block">{qrModalApk.targetTenantName}</span>
              <p className="text-slate-400 text-[10px] pt-1">Arahkan kamera smartphone Android Anda ke kode QR untuk mengunduh file .APK secara langsung.</p>
            </div>

            <button
              onClick={() => {
                triggerApkBinaryDownload(qrModalApk);
                setQrModalApk(null);
              }}
              className="w-full py-2.5 bg-sky-500 hover:bg-sky-400 text-slate-950 font-black text-xs uppercase rounded-xl transition-colors cursor-pointer"
            >
              Unduh File .APK Langsung
            </button>
          </div>
        </div>
      )}

    </div>
  );
};

export default CtoApkBuildManager;
