<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pembantu Protokol PHOENIX V3.9 (Titan Prime)</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; background-color: #111827; color: #E5E7EB; }
        .phoenix-card { background-color: #1F2937; border: 1px solid #374151; }
        .phoenix-tab { transition: all 0.3s ease; border-bottom: 2px solid transparent; }
        .phoenix-tab.active { color: #F59E0B; border-bottom-color: #F59E0B; }
        .phoenix-textarea, .phoenix-input { background-color: #111827; border: 1px solid #4B5563; color: #D1D5DB; }
        .phoenix-textarea:focus, .phoenix-input:focus { outline: none; border-color: #F59E0B; box-shadow: 0 0 0 2px #b45309; }
        .phoenix-btn { background-color: #D97706; color: #111827; transition: background-color 0.3s ease; }
        .phoenix-btn:hover { background-color: #F59E0B; }
        .accordion-content { max-height: 0; overflow: hidden; transition: max-height 0.5s ease-in-out; }
        .prose-custom h1, .prose-custom h2, .prose-custom h3, .prose-custom h4 { color: #F3F4F6; border-bottom: 1px solid #374151; padding-bottom: 0.5rem; margin-top: 1.5rem; }
        .prose-custom h1 { font-size: 1.875rem; } .prose-custom h2 { font-size: 1.5rem; }
        .prose-custom h3 { color: #E5E7EB; font-size: 1.25rem; } .prose-custom h4 { color: #F59E0B; font-size: 1.1rem; border-bottom: none; }
        .prose-custom p, .prose-custom li { color: #9CA3AF; line-height: 1.7; }
        .prose-custom strong { color: #F59E0B; }
        .prose-custom code { color: #FBBF24; background-color: #374151; padding: 0.2em 0.4em; margin: 0; font-size: 85%; border-radius: 3px; }
        .prose-custom hr { border-color: #374151; margin-top: 2rem; margin-bottom: 2rem; }
    </style>
</head>
<body class="flex items-center justify-center min-h-screen p-4 sm:p-6">
    <div class="w-full max-w-5xl mx-auto my-8">
        <div class="text-center mb-8">
            <h1 class="text-4xl md:text-5xl font-bold text-white">
                <span class="text-amber-500">P</span>rotokol <span class="text-amber-500">P</span>hoenix V3.9 <span class="text-gray-500 text-3xl md:text-4xl">(Titan Prime)</span>
            </h1>
            <p class="text-lg text-gray-400 mt-2">Sistem Pengurusan Kerjasama & Pembangunan Definitif.</p>
        </div>

        <div class="phoenix-card rounded-xl shadow-2xl overflow-hidden">
            <div class="p-6 md:p-8">
                <div class="border-b border-gray-700 mb-6">
                    <nav class="flex -mb-px space-x-2 sm:space-x-6 overflow-x-auto" aria-label="Tabs">
                        <button id="tab-diagnostik" class="phoenix-tab whitespace-nowrap py-4 px-2 text-sm sm:text-base font-medium">Alat Diagnostik</button>
                        <button id="tab-onboarding" class="phoenix-tab whitespace-nowrap py-4 px-2 text-sm sm:text-base font-medium">Onboarding Projek</button>
                        <button id="tab-baru" class="phoenix-tab whitespace-nowrap py-4 px-2 text-sm sm:text-base font-medium">Sesi Baru</button>
                        <button id="tab-sambungan" class="phoenix-tab whitespace-nowrap py-4 px-2 text-sm sm:text-base font-medium">Sesi Sambungan</button>
                        <button id="tab-pemulihan" class="phoenix-tab whitespace-nowrap py-4 px-2 text-sm sm:text-base font-medium">Pemulihan Sesi</button>
                    </nav>
                </div>
                <!-- Container untuk konten input setiap tab -->
                <div id="content-container"></div>
            </div>
            <!-- Bahagian Output Prompt yang dikongsi oleh semua tab -->
            <div id="output-container" class="bg-gray-800/50 px-6 md:px-8 py-5">
                <label for="outputPrompt" class="block text-sm font-medium text-gray-300 mb-2">Prompt Janaan (Sedia untuk Disalin):</label>
                <div class="relative">
                    <textarea id="outputPrompt" readonly rows="15" class="phoenix-textarea w-full rounded-lg p-3 text-sm font-mono"></textarea>
                    <button id="copyButton" class="phoenix-btn absolute top-3 right-3 rounded-md px-3 py-1.5 text-xs sm:text-sm font-semibold shadow-sm">Salin</button>
                </div>
            </div>
        </div>

        <div class="mt-6">
            <div class="phoenix-card rounded-lg">
                <button id="accordion-header" class="w-full flex justify-between items-center p-4 text-left">
                    <span class="font-semibold text-lg text-white">Buka Manual Penuh Protokol Phoenix V3.9 (Titan Prime)</span>
                    <svg id="accordion-arrow" xmlns="http://www.w.org/2000/svg" class="h-6 w-6 transform transition-transform duration-300 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" /></svg>
                </button>
                <div id="accordion-content" class="accordion-content">
                    <div class="px-4 pb-4 border-t border-gray-700">
                        <div id="prose-container" class="prose-custom max-w-none pt-2"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

<script>
    // --- KOD SUMBER UNTUK ALAT DIAGNOSTIK ---
    const DIAGNOSTIC_SCRIPT_CODE = `<?php
/**
 * Phoenix Diagnostician v1.7
 * ARAHAN:
 * 1. Cipta fail 'diagnose.php' di server.
 * 2. Salin & tampal keseluruhan kod ini ke dalam fail itu.
 * 3. Muat naik ke direktori PUBLIC projek (cth: public_html, public).
 * 4. Akses fail ini melalui pelayar web.
 * 5. SELEPAS SELESAI, PADAM FAIL INI DARI SERVER DENGAN SEGERA.
 */
error_reporting(0); ini_set('display_errors', 0);
class PhoenixDiagnostician {
    private $rootPath; private $report; private $exclusions = ['.', '..', 'vendor', 'node_modules', '.git', '.idea', 'cgi-bin'];
    public function __construct($startPath) {
        $this->rootPath = $this->findProjectRoot($startPath);
        $this->report = [ 'server_info' => [], 'ecosystem' => 'Tidak Dikenal Pasti', 'framework' => 'Tidak Dikenal Pasti', 'tech_stack' => [], 'onboarding_files' => [], 'dependencies' => [], 'env_example' => null, 'directory_structure' => '', 'key_files' => [] ];
        $this->exclusions[] = basename(__FILE__);
    }
    private function findProjectRoot($startDir) {
        $currentDir = $startDir;
        for ($i = 0; $i < 5; $i++) {
            if (file_exists($currentDir . '/composer.json') || file_exists($currentDir . '/package.json') || file_exists($currentDir . '/wp-config.php')) { return $currentDir; }
            $parentDir = dirname($currentDir);
            if ($parentDir === $currentDir || empty($parentDir)) break;
            $currentDir = $parentDir;
        }
        return $startDir;
    }
    public function run() {
        $this->detectServerInfo(); $this->detectEcosystemAndFramework(); $this->getDependencies();
        $this->detectTechStack(); $this->identifyKeyOnboardingFiles(); $this->getEnvExample();
        $this->buildDirectoryStructure($this->rootPath, 0); return $this->report;
    }
    private function detectServerInfo() {
        $this->report['server_info']['php_version'] = phpversion();
        $db_client_version = 'Tidak dapat dikesan';
        if (function_exists('mysqli_get_client_info')) { $db_client_version = mysqli_get_client_info(); } 
        elseif (defined('PDO::ATTR_CLIENT_VERSION')) { $db_client_version = 'PDO Dikesan'; }
        $this->report['server_info']['db_client_version'] = $db_client_version;
    }
    private function detectEcosystemAndFramework() {
        if (file_exists($this->rootPath . '/composer.json')) {
            $this->report['ecosystem'] = 'PHP / Composer';
            if (file_exists($this->rootPath . '/artisan')) $this->report['framework'] = 'Laravel';
            elseif (file_exists($this->rootPath . '/bin/console')) $this->report['framework'] = 'Symfony';
            elseif (file_exists($this->rootPath . '/wp-config.php')) $this->report['framework'] = 'WordPress';
            else $this->report['framework'] = 'PHP (Lain-lain/Vanilla)';
        } elseif (file_exists($this->rootPath . '/package.json')) {
            $this->report['ecosystem'] = 'JavaScript / Node.js';
            if (file_exists($this->rootPath . '/next.config.js')) $this->report['framework'] = 'Next.js (React)';
            elseif (file_exists($this->rootPath . '/nuxt.config.js')) $this->report['framework'] = 'Nuxt.js (Vue)';
            else $this->report['framework'] = 'Node.js/Vanilla JS';
        }
    }
    private function getDependencies() {
        if (file_exists($this->rootPath . '/composer.json')) {
            $composerJson = @file_get_contents($this->rootPath . '/composer.json');
            if($composerJson) { $this->report['key_files']['composer.json'] = $composerJson; $this->report['dependencies']['composer'] = json_decode($composerJson, true); }
        }
        if (file_exists($this->rootPath . '/package.json')) {
            $packageJson = @file_get_contents($this->rootPath . '/package.json');
            if($packageJson) { $this->report['key_files']['package.json'] = $packageJson; $this->report['dependencies']['npm'] = json_decode($packageJson, true); }
        }
    }
    private function detectTechStack() {
        $techMap = [ 'tailwindcss' => 'Tailwind CSS', 'flowbite' => 'Flowbite', 'bootstrap' => 'Bootstrap', 'vite' => 'Vite', 'webpack' => 'Webpack', 'laravel-mix' => 'Laravel Mix', 'react' => 'React', 'vue' => 'Vue', 'alpinejs' => 'Alpine.js', 'jquery' => 'jQuery', 'livewire/livewire' => 'Laravel Livewire', 'inertiajs/inertia' => 'Inertia.js' ];
        if (file_exists($this->rootPath . '/tailwind.config.js')) $this->report['tech_stack'][] = 'Tailwind CSS';
        if (file_exists($this->rootPath . '/vite.config.js')) $this->report['tech_stack'][] = 'Vite';
        if (file_exists($this->rootPath . '/webpack.mix.js')) $this->report['tech_stack'][] = 'Laravel Mix';
        $allDeps = array_merge( $this->report['dependencies']['composer']['require'] ?? [], $this->report['dependencies']['composer']['require-dev'] ?? [], $this->report['dependencies']['npm']['dependencies'] ?? [], $this->report['dependencies']['npm']['devDependencies'] ?? [] );
        foreach ($techMap as $key => $name) { if (isset($allDeps[$key])) { $this->report['tech_stack'][] = $name; } }
        $this->report['tech_stack'] = array_unique($this->report['tech_stack']);
    }
    private function identifyKeyOnboardingFiles() {
        $filesToCheck = [ 'Routes (Web)' => 'routes/web.php', 'Routes (API)' => 'routes/api.php', 'Kernel Konsol' => 'app/Console/Kernel.php', 'Konfigurasi Aplikasi' => 'config/app.php', 'Konfigurasi DB' => 'config/database.php', 'Layout Utama' => 'resources/views/layouts/app.blade.php' ];
        foreach ($filesToCheck as $label => $path) { if (file_exists($this->rootPath . '/' . $path)) { $this->report['onboarding_files'][$label] = $path; } }
    }
    private function getEnvExample() { if (file_exists($this->rootPath . '/.env.example')) { $this->report['env_example'] = @file_get_contents($this->rootPath . '/.env.example'); } }
    private function buildDirectoryStructure($dir, $depth) {
        if ($depth > 4) return; $items = @scandir($dir); if (!$items) return;
        foreach ($items as $item) {
            if (in_array($item, $this->exclusions)) continue;
            $path = $dir . '/' . $item; $prefix = str_repeat('    ', $depth);
            if (is_dir($path)) { $this->report['directory_structure'] .= $prefix . '📁 ' . $item . "\\n"; $this->buildDirectoryStructure($path, $depth + 1); } 
            else { $this->report['directory_structure'] .= $prefix . '📄 ' . $item . "\\n"; }
        }
    }
    public function render() {
        $this->run();
        ?>
        <!DOCTYPE html><html lang="ms"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Laporan Diagnostik Phoenix</title><script src="https://cdn.tailwindcss.com"><\/script></head><body class="bg-gray-900 text-white p-4 sm:p-8">
            <div class="max-w-5xl mx-auto"><h1 class="text-3xl sm:text-4xl font-bold text-amber-400 text-center">Phoenix Diagnostician</h1><p class="text-md sm:text-lg text-gray-400 mt-2 text-center">Laporan Analisis Projek Automatik v1.7</p><div class="mt-6 text-xs text-red-400 bg-red-900/50 border border-red-700 p-3 rounded-lg text-center"><strong>AMARAN:</strong> Sila padam fail ini (<code><?php echo htmlspecialchars(basename(__FILE__)); ?></code>) dari server anda selepas menyalin laporan ini.</div>
                <div id="report-content" class="mt-8 bg-gray-800 rounded-xl shadow-2xl p-6 space-y-8">
                    <div class="flex justify-between items-center"><h2 class="text-2xl font-bold text-amber-400">Informasi Server</h2><button class="copy-btn" data-target="server-info">Salin</button></div>
                    <div id="server-info" class="text-sm"><p>Versi PHP: <strong><?php echo htmlspecialchars($this->report['server_info']['php_version']); ?></strong></p><p>Versi Klien DB (MySQL): <strong><?php echo htmlspecialchars($this->report['server_info']['db_client_version']); ?></strong></p></div>
                    <div class="flex justify-between items-center"><h2 class="text-2xl font-bold text-amber-400">Ringkasan Projek</h2><button class="copy-btn" data-target="project-summary">Salin</button></div>
                    <div id="project-summary" class="text-sm"><p>Ekosistem: <strong><?php echo htmlspecialchars($this->report['ecosystem']); ?></strong></p><p>Rangka Kerja: <strong><?php echo htmlspecialchars($this->report['framework']); ?></strong></p><p class="text-xs text-gray-500">* Dijana dari: <code><?php echo htmlspecialchars($this->rootPath); ?></code></p></div>
                    <div class="flex justify-between items-center"><h2 class="text-2xl font-bold text-amber-400">Timbunan Teknologi</h2><button class="copy-btn" data-target="tech-stack">Salin</button></div>
                    <div id="tech-stack" class="flex flex-wrap gap-3"><?php if(!empty($this->report['tech_stack'])): foreach ($this->report['tech_stack'] as $tech): ?><span class="bg-gray-700 text-amber-300 text-sm font-medium px-3 py-1 rounded-full"><?php echo htmlspecialchars($tech); ?></span><?php endforeach; else: ?><p class="text-gray-500">Tiada.</p><?php endif; ?></div>
                    <div class="flex justify-between items-center"><h2 class="text-2xl font-bold text-amber-400">Fail Onboarding Penting</h2><button class="copy-btn" data-target="onboarding-files">Salin</button></div>
                    <ul id="onboarding-files" class="text-sm list-disc list-inside"><?php foreach ($this->report['onboarding_files'] as $label => $path): ?><li><?php echo htmlspecialchars($label); ?>: <code><?php echo htmlspecialchars($path); ?></code></li><?php endforeach; ?></ul>
                    <div class="flex justify-between items-center"><h2 class="text-2xl font-bold text-amber-400">Struktur Direktori</h2><button class="copy-btn" data-target="dir-structure">Salin</button></div>
                    <pre id="dir-structure" class="p-4 bg-gray-900 rounded-lg text-sm max-h-96 overflow-y-auto"><?php echo htmlspecialchars($this->report['directory_structure']); ?></pre>
                    <?php foreach($this->report['key_files'] as $filename => $content): ?>
                    <div class="flex justify-between items-center"><h2 class="text-2xl font-bold text-amber-400">Kandungan <code><?php echo htmlspecialchars($filename); ?></code></h2><button class="copy-btn" data-target="file-<?php echo str_replace('.', '-', $filename); ?>">Salin</button></div>
                    <pre id="file-<?php echo str_replace('.', '-', $filename); ?>" class="p-4 bg-gray-900 rounded-lg text-xs max-h-96 overflow-y-auto"><?php echo htmlspecialchars($content); ?></pre>
                    <?php endforeach; ?>
                </div>
            </div>
            <script>
                document.querySelectorAll('.copy-btn').forEach(button => {
                    button.addEventListener('click', (e) => {
                        const btn = e.currentTarget;
                        const targetId = btn.dataset.target;
                        const targetElement = document.getElementById(targetId);
                        if (!targetElement) return;
                        const textToCopy = targetElement.innerText || targetElement.textContent;
                        const textArea = document.createElement("textarea");
                        textArea.value = textToCopy.trim();
                        document.body.appendChild(textArea);
                        textArea.style.position = 'fixed'; textArea.style.left = '-9999px';
                        textArea.focus(); textArea.select();
                        try {
                            document.execCommand('copy');
                            const originalText = btn.textContent;
                            btn.textContent = 'Disalin!';
                            setTimeout(() => { btn.textContent = 'Salin'; }, 2000);
                        } catch (err) { console.error('Gagal menyalin: ', err); }
                        document.body.removeChild(textArea);
                    });
                });
            <\/script>
        </body></html>
        <?php
    }
}
$diagnostician = new PhoenixDiagnostician(__DIR__);
$diagnostician->render();
?>`;

    // --- MANUAL PENUH V3.8 ---
    const FULL_MANUAL_MARKDOWN = `# 📜 Protokol Phoenix V3.8 (Titan Prime)

## Fasal 1: Falsafah & Ikrar Teras
**Tujuan:** Untuk mewujudkan satu kerangka kerjasama (human-AI partnership) yang kukuh, telus, dan tidak boleh musnah. Ini adalah **satu-satunya sumber rujukan (single source of truth)** untuk semua cara kerja kita.
- **Ikrar Kerjasama:** Kita beroperasi dalam model **Mentor (AI) & Mentee (Pengguna)**. Saya (AI) sebagai pakar teknikal dan arkitek, anda sebagai pemilik visi dan pelaksana akhir.

---

## Fasal 2: Komponen Teras (Aset Projek)
- **\`CHANGELOG.md\`**: Jantung & ingatan projek. Wajib dikemas kini pada setiap akhir sesi.
- **\`TASK_LIST.md\`**: Peta jalan strategik. Mengandungi senarai tugasan.
- **\`PROJECT_MANIFEST.md\`**: Peta senibina projek (dijana melalui POP atau POM).

---

## Fasal 3: Protokol Operasi Utama
### 🛡️ Protokol Kitaran Tugasan (Task Cycle)
1.  **Anda -> Permintaan Tugasan:** Mulakan dengan tag **\`TASK-XX\`** atau **\`BUGFIX-XX\`**.
2.  **Saya -> Penerimaan & Analisis:** Saya akan sahkan, analisis, dan kenal pasti fail terlibat.
3.  **Pelaksanaan (SSG / PGS):** Kita guna mod selamat (SSG) atau mod pintas (PGS) jika perlu.
4.  **Anda -> Pengesahan:** Anda laksana kod dan sahkan hasilnya.
5.  **Saya -> Penutupan:** Saya tandakan tugas selesai.

### ✅ Protokol Salinan-Sahkan-Ganti (SSG)
**Tujuan:** Mod operasi **paling selamat** dan menjadi laluan utama.

### ⚡ Protokol Gantian Sasaran (PGS)
**Tujuan:** Mod **berisiko tinggi** untuk fail sangat besar. Gunakan hanya bila diminta secara eksplisit.

---

## Fasal 4: Protokol Jaminan Kualiti & Strategi
- **Protokol Semak & Kiraan Baris (SEMAK):** Saya akan paparkan perbandingan jumlah baris kod.
- **Protokol Laporan Bug (BUG):** Format laporan: 1. Jangkaan, 2. Hasil Sebenar, 3. Mesej Ralat, 4. Kod Terlibat.
- **Protokol Cetak Biru (Blueprint):** Untuk ciri kompleks, saya akan cadangkan pelan untuk anda luluskan dahulu.
- **Protokol Kualiti Prisma:** Saya berjanji untuk hasilkan kod yang bersih, jelas, dan mempunyai komen.

---

## Fasal 5: Protokol Sesi Utama
### 🚀 Protokol Permulaan Sesi (Sesi Baru)
Untuk memulakan projek dari kosong, gunakan prompt yang dijana oleh tab **Sesi Baru**.

### 💾 Protokol Akhir Sesi (PAS)
Apabila anda arahkan "**Aktifkan Protokol Akhir Sesi**," saya akan sediakan ringkasan untuk \`CHANGELOG.md\`.

---

## Fasal 6: Protokol Lanjutan & Pemulihan
### 🤝 Protokol Jabat Tangan Digital (Handshake)
**Tujuan:** Untuk memastikan penyelarasan sempurna pada permulaan sesi sambungan atau pemulihan.

### 🔄 Protokol Pemulihan Sesi (PPS)
**Tujuan:** Untuk memulihkan "ingatan" sesi dengan pantas selepas terputus hubungan.

---

## Fasal 7: Protokol Onboarding Projek
### 🏗️ Protokol Onboarding Projek (POP & POM)
**Tujuan:** Untuk membolehkan saya (Mentor AI) menyerap dan memahami struktur teras sesebuah projek dan persekitaran servernya dengan pantas.

#### Mod 1: Protokol Onboarding Manual (POM)
- **Situasi:** Apabila projek terlalu besar untuk dimuat naik atau akses terhad.
- **Pelaksanaan:**
    1.  Gunakan **Alat Diagnostik** untuk menjana laporan.
    2.  Gunakan butang **"Salin"** individu di sebelah setiap bahagian laporan.
    3.  Buka tab **Onboarding Projek**.
    4.  Pilih **Kaedah 2: Onboarding Manual**.
    5.  Tampal setiap bahagian ke dalam ruangan yang sepadan.

#### Mod 2: Protokol Onboarding Projek (POP)
- **Situasi:** Apabila anda boleh memuat naik keseluruhan projek sebagai fail ZIP.
- **Pelaksanaan:**
    1.  Buka tab **Onboarding Projek**.
    2.  Pilih **Kaedah 1: Guna Borang**.
    3.  Isi borang manifest untuk menjana kandungan \`PROJECT_MANIFEST.md\`.
`;

    document.addEventListener('DOMContentLoaded', () => {
        const dom = {
            tabs: { diagnostik: document.getElementById('tab-diagnostik'), onboarding: document.getElementById('tab-onboarding'), baru: document.getElementById('tab-baru'), sambungan: document.getElementById('tab-sambungan'), pemulihan: document.getElementById('tab-pemulihan') },
            contentContainer: document.getElementById('content-container'),
            outputContainer: document.getElementById('output-container'),
            outputPrompt: document.getElementById('outputPrompt'),
            copyButton: document.getElementById('copyButton'),
            accordion: { header: document.getElementById('accordion-header'), content: document.getElementById('accordion-content'), arrow: document.getElementById('accordion-arrow') },
            manualContainer: document.getElementById('prose-container')
        };

        let activeTab = 'diagnostik';

        const TAB_TEMPLATES = {
            diagnostik: `<div class="space-y-4"><h3 class="text-xl font-bold text-amber-400">Phoenix Diagnostician v1.7</h3><p class="text-gray-400">Alat ini akan menganalisis projek dan persekitaran server anda secara automatik. Ikuti langkah-langkah ini:</p><ol class="list-decimal list-inside text-gray-400 space-y-2"><li>Tekan butang di bawah untuk menyalin keseluruhan kod skrip.</li><li>Cipta satu fail baharu bernama <code class="text-amber-300 bg-gray-800 px-1 rounded">diagnose.php</code> di komputer anda.</li><li>Tampal kod yang disalin ke dalam fail tersebut.</li><li>Muat naik fail <code class="text-amber-300 bg-gray-800 px-1 rounded">diagnose.php</code> ke direktori <strong>public</strong> projek di server.</li><li>Buka pelayar web dan layari URL fail tersebut.</li><li>Gunakan butang "Salin" di sebelah setiap tajuk untuk menyalin maklumat yang diperlukan.</li><li class="text-red-400 font-semibold">Selepas mendapat laporan, padam fail diagnostik dari server anda serta-merta.</li></ol><div class="relative mt-4"><textarea id="diagnose-script-content" readonly rows="15" class="phoenix-textarea w-full rounded-lg p-3 text-xs font-mono"></textarea><button id="copy-diagnose-script" class="phoenix-btn absolute top-3 right-3 rounded-md px-3 py-1.5 text-sm font-semibold shadow-sm">Salin Skrip</button></div></div>`,
            onboarding: `<p class="text-gray-400 mb-4">Pilih salah satu kaedah di bawah untuk memulakan kerja pada projek sedia ada.</p><div class="border border-gray-600 rounded-lg p-4 mb-6"><h3 class="font-semibold text-amber-400 mb-2">Kaedah 1: Onboarding Standard (Guna Borang)</h3><p class="text-sm text-gray-400 mb-4">Sesuai jika anda boleh muat naik projek sebagai fail ZIP.</p><div id="onboarding-form-1" class="space-y-3"><div><label class="block text-sm font-medium text-gray-300 mb-1">Nama Projek</label><input type="text" class="phoenix-input w-full rounded-lg p-2 text-sm" placeholder="cth: Sistem E-Dagang Klien X"></div><div><label class="block text-sm font-medium text-gray-300 mb-1">Rangka Kerja & Versi</label><input type="text" class="phoenix-input w-full rounded-lg p-2 text-sm" placeholder="cth: Laravel 10.2, PHP 8.2"></div></div></div><div class="border border-gray-600 rounded-lg p-4"><h3 class="font-semibold text-amber-400 mb-2">Kaedah 2: Onboarding Manual (Guna Laporan Diagnostik)</h3><p class="text-sm text-gray-400 mb-4">Jalankan Alat Diagnostik dan tampal setiap bahagian laporan ke dalam ruangan yang sepadan di bawah.</p><div id="onboarding-form-2" class="space-y-4"><div><label class="block text-sm font-medium text-gray-300 mb-1">1. Informasi Server</label><textarea rows="2" class="phoenix-textarea w-full rounded-lg p-2 text-sm font-mono" placeholder="Tampal bahagian 'Informasi Server' di sini..."></textarea></div><div><label class="block text-sm font-medium text-gray-300 mb-1">2. Ringkasan Projek</label><textarea rows="3" class="phoenix-textarea w-full rounded-lg p-2 text-sm font-mono" placeholder="Tampal bahagian 'Ringkasan Projek' di sini..."></textarea></div><div><label class="block text-sm font-medium text-gray-300 mb-1">3. Timbunan Teknologi</label><textarea rows="3" class="phoenix-textarea w-full rounded-lg p-2 text-sm font-mono" placeholder="Tampal bahagian 'Timbunan Teknologi' di sini..."></textarea></div><div><label class="block text-sm font-medium text-gray-300 mb-1">4. Fail Onboarding Penting</label><textarea rows="4" class="phoenix-textarea w-full rounded-lg p-2 text-sm font-mono" placeholder="Tampal bahagian 'Fail Onboarding Penting' di sini..."></textarea></div><div><label class="block text-sm font-medium text-gray-300 mb-1">5. Struktur Direktori</label><textarea rows="5" class="phoenix-textarea w-full rounded-lg p-2 text-sm font-mono" placeholder="Tampal bahagian 'Struktur Direktori' di sini..."></textarea></div><div><label class="block text-sm font-medium text-gray-300 mb-1">6. Kandungan composer.json</label><textarea rows="5" class="phoenix-textarea w-full rounded-lg p-2 text-sm font-mono" placeholder="Tampal kandungan 'composer.json' di sini..."></textarea></div><div><label class="block text-sm font-medium text-gray-300 mb-1">7. Kandungan package.json (jika ada)</label><textarea rows="5" class="phoenix-textarea w-full rounded-lg p-2 text-sm font-mono" placeholder="Tampal kandungan 'package.json' di sini..."></textarea></div></div></div>`,
            baru: `<div class="space-y-4"><p class="text-gray-400 mb-4">Gunakan mod ini untuk memulakan projek baru dari kosong. Sediakan fail ZIP anda dengan betul.</p><div class="border border-green-700 bg-green-900/50 rounded-lg p-4"><h3 class="font-semibold text-green-300">WAJIB SERTAKAN</h3><ul class="list-disc list-inside text-gray-400 mt-2 text-sm space-y-1"><li>Semua kod sumber projek (\`app\`, \`routes\`, dsb.)</li><li>Aset Projek (\`CHANGELOG.md\`, \`TASK_LIST.md\`)</li></ul></div><div class="border border-red-700 bg-red-900/50 rounded-lg p-4"><h3 class="font-semibold text-red-300">WAJIB KECUALIKAN</h3><ul class="list-disc list-inside text-gray-400 mt-2 text-sm space-y-1"><li>Folder \`node_modules\` & \`vendor\`</li><li>Fail \`.env\` sebenar</li></ul></div></div>`,
            sambungan: `<div class="p-4"><p class="text-gray-400">Gunakan mod ini apabila anda menyambung semula sesi kerja yang terhenti seketika. Pastikan anda memuat naik kod terkini jika ada perubahan.</p></div>`,
            pemulihan: `<div class="p-4"><p class="text-gray-400 mb-4">Untuk memulihkan ingatan sesi selepas terputus lama, sila tampal keseluruhan kandungan dari fail \`CHANGELOG.md\` terkini anda di bawah.</p><textarea id="changelogInput" rows="8" class="phoenix-textarea w-full rounded-lg p-3 text-sm" placeholder="Tampal kandungan penuh CHANGELOG.md di sini..."></textarea></div>`
        };

        const generatePrompt = () => {
            let promptText = '';
            switch(activeTab) {
                case 'onboarding':
                    const form2Textareas = document.querySelectorAll('#onboarding-form-2 textarea');
                    let manualReportContent = '';
                    let isManualMode = false;
                    form2Textareas.forEach(textarea => {
                        if (textarea.value.trim() !== '') {
                            isManualMode = true;
                            const label = textarea.previousElementSibling.textContent;
                            manualReportContent += `--- ${label.toUpperCase()} ---\n${textarea.value.trim()}\n\n`;
                        }
                    });

                    if (isManualMode) {
                        promptText = `[AKTIFKAN PROTOKOL ONBOARDING MANUAL (POM)]\nBro, kita akan mulakan kerja pada projek sedia ada menggunakan laporan diagnostik.\n\n[LAPORAN DIAGNOSTIK]\n${manualReportContent.trim()}\n\n[ARAHAN PERMULAAN]\nLaksanakan **Protokol Onboarding Manual (POM)**. Analisis laporan di atas. Sahkan pemahaman anda dan tunggu arahan untuk TASK-01.`;
                    } else {
                        const form1Inputs = document.querySelectorAll('#onboarding-form-1 input');
                        const projectName = form1Inputs[0].value || '[Nama Projek]';
                        const framework = form1Inputs[1].value || '[Rangka Kerja & Versi]';
                        const manifestContent = `# PROJECT MANIFEST: ${projectName}\n- Framework: ${framework}`;
                        promptText = `[AKTIFKAN PROTOKOL ONBOARDING PROJEK (POP)]\nBro, kita akan mulakan kerja pada satu projek sedia ada.\n\n[KONTEKS PROJEK]\n1. Kod Sumber: Saya telah memuat naik kod projek penuh dalam fail ZIP.\n2. Manifest Projek:\n\`\`\`markdown\n${manifestContent}\n\`\`\`\n\n[ARAHAN PERMULAAN]\nLaksanakan **Protokol Onboarding Projek (POP)**. Sahkan pemahaman anda dan tunggu arahan untuk TASK-01.`;
                    }
                    break;
                case 'baru':
                    promptText = `[PENGAKTIFAN PENUH PROTOKOL PHOENIX V3.8]\nBro, kita mulakan projek baru dari kosong.\n\nSila fahami dan serapkan keseluruhan manual **Protokol Phoenix V3.8 (Titan Prime)** sebagai sumber rujukan utama kita.\n\n--- MANUAL PENUH ---\n${FULL_MANUAL_MARKDOWN}\n--- TAMAT MANUAL ---\n\n[KONTEKS PROJEK]\nSaya telah memuat naik kod projek dalam fail ZIP.\n\`source_references=['uploaded:_ALL_']\`\n\n[ARAHAN PERMULAAN]\nSahkan penerimaan dengan membalas: **"Protokol Phoenix V3.8 (Titan Prime) diterima dan diaktifkan. Sedia untuk TASK-01."**`;
                    break;
                case 'sambungan':
                    promptText = `[AKTIFKAN SEMULA PROTOKOL PHOENIX V3.8]\nBro, kita sambung sesi kerja.\n\n[SITUASI & IKRAR]\nIni adalah sesi sambungan. Kita komited sepenuhnya terhadap Protokol PHOENIX V3.8.\n\n[KONTEKS PROJEK]\nSaya telah memuat naik kod projek terkini dalam fail ZIP (jika ada perubahan).\n\`source_references=['uploaded:_ALL_']\`\n\n[ARAHAN PERMULAAN]\nLaksanakan **Protokol Jabat Tangan Digital**. Sahkan keadaan semasa dan tunggu arahan saya.`;
                    break;
                case 'pemulihan':
                    const changelogContent = document.getElementById('changelogInput')?.value.trim() || "[Sila tampal kandungan CHANGELOG.md di sini]";
                    promptText = `[AKTIFKAN PROTOKOL PEMULIHAN SESI (PPS)]\nBro, sesi kita terputus. Mohon pulihkan konteks.\n\n[SITUASI & IKRAR]\nIni adalah pemulihan sesi. Kita komited sepenuhnya terhadap Protokol PHOENIX V3.8.\n\n[PEMULIHAN INGATAN & KONTEKS]\n1. Konteks Kod: Saya memuat naik kod projek terkini (jika perlu).\n2. Ingatan Sesi: Berikut kandungan \`CHANGELOG.md\`:\n\`\`\`markdown\n${changelogContent}\n\`\`\`\n\n[ARAHAN PERMULAAN]\nAktifkan **PPS** dan laksanakan **Protokol Jabat Tangan Digital**. Sahkan pemulihan ingatan anda dan tunggu arahan.`;
                    break;
                default:
                    promptText = 'Sila pilih tab untuk menjana prompt.';
            }
            dom.outputPrompt.value = promptText;
        };

        const copyToClipboard = (text, button) => {
            const textArea = document.createElement("textarea");
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            try {
                document.execCommand('copy');
                const originalText = button.textContent;
                button.textContent = 'Disalin!';
                setTimeout(() => { button.textContent = originalText; }, 2000);
            } catch (err) { button.textContent = 'Gagal'; }
            document.body.removeChild(textArea);
        };
        
        const markdownToHtml = (md) => {
            let html = md.replace(/`([^`]+)`/g, '<code>$1</code>').replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            return html.split('\\n').map(line => {
                if (line.startsWith('#### ')) return `<h4>${line.substring(5)}</h4>`;
                if (line.startsWith('### ')) return `<h3>${line.substring(4)}</h3>`;
                if (line.startsWith('## ')) return `<h2>${line.substring(3)}</h2>`;
                if (line.startsWith('# ')) return `<h1>${line.substring(2)}</h1>`;
                if (line.startsWith('- ')) return `<li class="ml-4 list-disc">${line.substring(2)}</li>`;
                if (line.trim() === '---') return '<hr>';
                if (line.trim() === '') return '';
                return `<p>${line}</p>`;
            }).join('');
        };

        const showTab = (tabName) => {
            activeTab = tabName;
            for (const key in dom.tabs) {
                dom.tabs[key].classList.toggle('active', key === tabName);
            }
            dom.contentContainer.innerHTML = TAB_TEMPLATES[tabName] || '';
            dom.outputContainer.style.display = (tabName === 'diagnostik') ? 'none' : 'block';
            addDynamicEventListeners();
            generatePrompt();
        };

        const addDynamicEventListeners = () => {
            if (activeTab === 'diagnostik') {
                const scriptTextarea = document.getElementById('diagnose-script-content');
                const copyBtn = document.getElementById('copy-diagnose-script');
                if (scriptTextarea) scriptTextarea.value = DIAGNOSTIC_SCRIPT_CODE;
                if (copyBtn) copyBtn.addEventListener('click', () => copyToClipboard(DIAGNOSTIC_SCRIPT_CODE, copyBtn));
            } else {
                const inputs = dom.contentContainer.querySelectorAll('input, textarea');
                inputs.forEach(input => input.addEventListener('input', generatePrompt));
            }
        };

        // --- EVENT LISTENERS ---
        for (const key in dom.tabs) {
            dom.tabs[key].addEventListener('click', () => showTab(key));
        }
        dom.copyButton.addEventListener('click', () => copyToClipboard(dom.outputPrompt.value, dom.copyButton));
        dom.accordion.header.addEventListener('click', () => {
            const content = dom.accordion.content;
            const isOpening = !content.style.maxHeight || content.style.maxHeight === '0px';
            content.style.maxHeight = isOpening ? content.scrollHeight + "px" : null;
            dom.accordion.arrow.classList.toggle('rotate-180', isOpening);
        });

        // --- INITIALIZATION ---
        dom.manualContainer.innerHTML = markdownToHtml(FULL_MANUAL_MARKDOWN.replace(/\n/g, '\\n'));
        showTab('diagnostik');
    });
</script>
</body>
</html>
