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

import React, { useState } from 'react';
import { 
  Folder, 
  FolderOpen, 
  FileCode, 
  ChevronRight, 
  ChevronDown, 
  Copy, 
  Check, 
  Download, 
  Eye, 
  Code, 
  Layout, 
  Database, 
  Server, 
  Building2, 
  Users, 
  DollarSign, 
  CalendarDays, 
  Menu, 
  Search, 
  Bell, 
  MessageSquare, 
  Maximize, 
  Info,
  Terminal,
  Activity,
  User,
  Settings,
  HelpCircle,
  FileSpreadsheet
} from 'lucide-react';

// Code Templates for CI3 Files
const fileTemplates: Record<string, string> = {
  '.htaccess': `# URL Rewriting Rule untuk menghapus index.php di URL CodeIgniter 3
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]`,

  'index.php': `<?php
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * @package	CodeIgniter
 * @author	EllisLab Dev Team
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
 * @copyright	Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
 * @license	https://opensource.org/licenses/MIT	MIT License
 * @link	https://codeigniter.com
 * @since	Version 1.0.0
 * @filesource
 */

// Menentukan Environment (development, testing, production)
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');

switch (ENVIRONMENT)
{
	case 'development':
		error_reporting(-1);
		ini_set('display_errors', 1);
	break;

	case 'testing':
	case 'production':
		ini_set('display_errors', 0);
		if (version_compare(PHP_VERSION, '5.3', '>='))
		{
			error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
		}
		else
		{
			error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
		}
	break;

	default:
		header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
		echo 'The application environment is not set correctly.';
		exit(1); // EXIT_ERROR
}

// Nama direktori aplikasi (default: application)
$system_path = 'system';
$application_folder = 'application';
$view_folder = '';

// Path ke direktori system & application
if (defined('STDIN'))
{
	chdir(dirname(__FILE__));
}

if (($_temp = realpath($system_path)) !== FALSE)
{
	$system_path = $_temp.DIRECTORY_SEPARATOR;
}
else
{
	$system_path = strtr(
		rtrim($system_path, '/\\\\'),
		'/\\\\',
		DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
	).DIRECTORY_SEPARATOR;
}

if ( ! is_dir($system_path))
{
	header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
	echo 'Your system folder path does not appear to be set correctly.';
	exit(3); // EXIT_CONFIG
}

define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
define('BASEPATH', $system_path);
define('FCPATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
define('SYSDIR', basename(BASEPATH));

if (is_dir($application_folder))
{
	if (($_temp = realpath($application_folder)) !== FALSE)
	{
		$application_folder = $_temp.DIRECTORY_SEPARATOR;
	}
	else
	{
		$application_folder = rtrim($application_folder, '/\\\\').DIRECTORY_SEPARATOR;
	}
	define('APPPATH', $application_folder);
}
else
{
	header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
	echo 'Your application folder path does not appear to be set correctly.';
	exit(3); // EXIT_CONFIG
}

// Load core bootstrapper CodeIgniter
require_once BASEPATH.'core/CodeIgniter.php';`,

  'application/config/config.php': `<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
*/
$config['base_url'] = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

/*
|--------------------------------------------------------------------------
| Index File (Hapus 'index.php' jika menggunakan .htaccess mod_rewrite)
|--------------------------------------------------------------------------
*/
$config['index_page'] = '';

/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
*/
$config['uri_protocol']	= 'REQUEST_URI';

/*
|--------------------------------------------------------------------------
| Default Language, Character Set & Session Configuration
|--------------------------------------------------------------------------
*/
$config['language']	= 'indonesian';
$config['charset'] = 'UTF-8';
$config['enable_hooks'] = FALSE;
$config['subclass_prefix'] = 'MY_';
$config['composer_autoload'] = FALSE;
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\\-';

// Session variables untuk auth pengguna
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

// Cookie & Security
$config['cookie_prefix']	= '';
$config['cookie_domain']	= '';
$config['cookie_path']		= '/';
$config['cookie_secure']	= FALSE;
$config['cookie_httponly'] 	= FALSE;
$config['global_xss_filtering'] = TRUE;
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_propertyhub';
$config['csrf_cookie_name'] = 'csrf_cookie_ph';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();`,

  'application/config/database.php': `<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
|--------------------------------------------------------------------------
| Database Connection Settings (CodeIgniter 3 + MySQLi)
|--------------------------------------------------------------------------
*/
$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'db_properti_hub',
	'dbdriver' => 'mysqli', // Driver MySQLi PHP 7.4+
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8mb4',
	'dbcollat' => 'utf8mb4_general_ci',
	'swap_pre' => '',
	'encrypt'  => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE // Mengaktifkan query profiling untuk optimasi
);`,

  'application/config/autoload.php': `<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
|--------------------------------------------------------------------------
| Auto-load Packages, Libraries, Helpers, Drivers & Models
|--------------------------------------------------------------------------
*/

// Autoload core libraries (database, session, form_validation)
$autoload['libraries'] = array('database', 'session', 'form_validation');

// Autoload Drivers
$autoload['drivers'] = array();

// Autoload helper functions (url, file, form, security)
$autoload['helper'] = array('url', 'form', 'security', 'html');

// Autoload Configuration files
$autoload['config'] = array();

// Autoload Languages
$autoload['language'] = array();

// Autoload models agar dapat dipanggil langsung dari controller mana saja
$autoload['model'] = array('Property_model', 'User_model');`,

  'application/config/routes.php': `<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
|--------------------------------------------------------------------------
| Application Routing Rules
|--------------------------------------------------------------------------
*/

// Route default mengarah ke halaman dashboard utama
$config['default_controller'] = 'dashboard';
$config['translate_uri_dashes'] = FALSE;

// Custom routing rules untuk sistem PropertyHub
$route['login'] = 'auth/login';
$route['logout'] = 'auth/logout';
$route['register'] = 'auth/register';

// Routing property CRUD
$route['properties'] = 'property';
$route['properties/create'] = 'property/create';
$route['properties/store'] = 'property/store';
$route['properties/view/(:any)'] = 'property/view/$1';
$route['properties/delete/(:any)'] = 'property/delete/$1';

// Custom error handling page (404)
$route['404_override'] = '';`,

  'application/controllers/Dashboard.php': `<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Dashboard Controller
 * Menghubungkan template AdminLTE 3 dengan data statistik dari model
 */
class Dashboard extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // Validasi apakah user sudah login, jika belum arahkan ke login box AdminLTE
        if (!$this->session->userdata('user_id')) {
            redirect('login');
        }
    }

    public function index() {
        $data['title'] = 'Dashboard Utama - PropertyHub';
        $data['active_menu'] = 'dashboard';
        
        // Mengambil data statistik dari model untuk Info Boxes AdminLTE
        $data['stats'] = $this->Property_model->get_dashboard_stats();
        $data['recent_transactions'] = $this->Property_model->get_recent_transactions(5);
        $data['user_profile'] = $this->User_model->get_user_by_id($this->session->userdata('user_id'));

        // Render view dibungkus dengan layout templates AdminLTE 3
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('dashboard', $data);
        $this->load->view('templates/footer', $data);
    }
}`,

  'application/controllers/Property.php': `<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Property Controller
 * Mengelola Listing Properti (Hotel, Kost, Rumah, Apartemen)
 */
class Property extends CI_Controller {

    public function __construct() {
        parent::__construct();
        if (!$this->session->userdata('user_id')) {
            redirect('login');
        }
    }

    public function index() {
        $data['title'] = 'Manajemen Properti - PropertyHub';
        $data['active_menu'] = 'property_list';
        
        // Membaca query pencarian/filter
        $search = $this->input->get('search');
        $type = $this->input->get('type');

        if ($search || $type) {
            $data['properties'] = $this->Property_model->search_properties($search, $type);
        } else {
            $data['properties'] = $this->Property_model->get_all_properties();
        }

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('properties/list', $data);
        $this->load->view('templates/footer', $data);
    }

    public function create() {
        // Cek hak akses melalui RBAC (Hanya Owner yang dapat menambahkan properti)
        $role = $this->session->userdata('role');
        if ($role !== 'owner') {
            $this->session->set_flashdata('error', 'Hanya Host/Pemilik properti yang diizinkan!');
            redirect('properties');
        }

        $data['title'] = 'Daftarkan Properti Baru - PropertyHub';
        $data['active_menu'] = 'add_property';

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('properties/add', $data);
        $this->load->view('templates/footer', $data);
    }

    public function store() {
        $role = $this->session->userdata('role');
        if ($role !== 'owner') {
            redirect('properties');
        }

        // Aturan validasi Form CodeIgniter 3
        $this->form_validation->set_rules('name', 'Nama Properti', 'required|trim');
        $this->form_validation->set_rules('address', 'Alamat Lengkap', 'required|trim');
        $this->form_validation->set_rules('type', 'Tipe Properti', 'required');
        $this->form_validation->set_rules('description', 'Deskripsi Properti', 'required|trim');

        if ($this->form_validation->run() == FALSE) {
            $this->create();
        } else {
            // Mengambil input data form dengan pengamanan XSS otomatis
            $insert_data = array(
                'owner_id' => $this->session->userdata('user_id'),
                'name' => $this->input->post('name', TRUE),
                'type' => $this->input->post('type', TRUE),
                'address' => $this->input->post('address', TRUE),
                'description' => $this->input->post('description', TRUE),
                'price_day' => $this->input->post('price_day') ? intval($this->input->post('price_day')) : NULL,
                'price_month' => $this->input->post('price_month') ? intval($this->input->post('price_month')) : NULL,
                'price_buy' => $this->input->post('price_buy') ? intval($this->input->post('price_buy')) : NULL,
                'status' => 'available',
                'image_url' => $this->input->post('image_url') ?: 'https://images.unsplash.com/photo-1564013799919-ab600027ffc6',
                'created_at' => date('Y-m-d H:i:s')
            );

            if ($this->Property_model->insert_property($insert_data)) {
                $this->session->set_flashdata('success', 'Listing properti berhasil diterbitkan!');
            } else {
                $this->session->set_flashdata('error', 'Gagal menyimpan data properti.');
            }
            redirect('properties');
        }
    }

    public function delete($id) {
        $role = $this->session->userdata('role');
        $user_id = $this->session->userdata('user_id');

        // Pastikan properti milik user bersangkutan sebelum menghapus
        $property = $this->Property_model->get_property_by_id($id);
        if (!$property || ($role !== 'owner' || $property['owner_id'] !== $user_id)) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki hak akses menghapus properti ini!');
            redirect('properties');
        }

        if ($this->Property_model->delete_property($id)) {
            $this->session->set_flashdata('success', 'Listing properti berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus properti dari database.');
        }
        redirect('properties');
    }
}`,

  'application/controllers/Auth.php': `<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Auth Controller
 * Menangani Session Login / Registrasi Pengguna
 */
class Auth extends CI_Controller {

    public function login() {
        if ($this->session->userdata('user_id')) {
            redirect('dashboard');
        }

        $this->form_validation->set_rules('username', 'Username', 'required|trim');
        $this->form_validation->set_rules('password', 'Password', 'required');

        if ($this->form_validation->run() == FALSE) {
            $data['title'] = 'Masuk - Portal PropertyHub';
            $this->load->view('auth/login', $data);
        } else {
            $username = $this->input->post('username', TRUE);
            $password = $this->input->post('password');

            $user = $this->User_model->check_login($username, $password);
            
            if ($user) {
                // Set CodeIgniter Session userdata
                $session_data = array(
                    'user_id' => $user['id'],
                    'username' => $user['username'],
                    'full_name' => $user['full_name'],
                    'role' => $user['role'], // 'owner' atau 'guest'
                    'email' => $user['email']
                );
                $this->session->set_userdata($session_data);
                redirect('dashboard');
            } else {
                $this->session->set_flashdata('error', 'Kombinasi Username & Password tidak cocok!');
                redirect('login');
            }
        }
    }

    public function logout() {
        $this->session->sess_destroy();
        redirect('login');
    }
}`,

  'application/models/Property_model.php': `<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Property Model
 * Query Builder / Active Record untuk tabel properties & transactions
 */
class Property_model extends CI_Model {

    public function get_all_properties() {
        // Query: SELECT * FROM properties ORDER BY created_at DESC
        $this->db->order_by('created_at', 'DESC');
        return $this->db->get('properties')->result_array();
    }

    public function get_property_by_id($id) {
        return $this->db->get_where('properties', array('id' => $id))->row_array();
    }

    public function search_properties($search = '', $type = '') {
        $this->db->select('*');
        $this->db->from('properties');
        
        if (!empty($search)) {
            $this->db->group_start();
            $this->db->like('name', $search);
            $this->db->or_like('address', $search);
            $this->db->or_like('description', $search);
            $this->db->group_end();
        }

        if (!empty($type)) {
            $this->db->where('type', $type);
        }

        return $this->db->get()->result_array();
    }

    public function insert_property($data) {
        return $this->db->insert('properties', $data);
    }

    public function delete_property($id) {
        return $this->db->delete('properties', array('id' => $id));
    }

    public function get_dashboard_stats() {
        // Menggunakan Active Record Builder untuk menghitung cepat
        $stats = array();
        $stats['total_properties'] = $this->db->count_all('properties');
        
        // Total Pendapatan Kotor dari transaksi sukses
        $this->db->select_sum('total_price');
        $this->db->where('status', 'paid');
        $query = $this->db->get('transactions')->row_array();
        $stats['revenue'] = $query['total_price'] ?: 0;

        // Total Transaksi Booking Aktif
        $this->db->where_in('status', array('pending', 'paid'));
        $stats['active_bookings'] = $this->db->count_all_results('transactions');

        // Total properti dengan status Tersewa/Terbeli
        $this->db->where_in('status', array('rented', 'sold'));
        $stats['closed_deals'] = $this->db->count_all_results('properties');

        return $stats;
    }

    public function get_recent_transactions($limit = 5) {
        $this->db->select('transactions.*, properties.name as property_name, properties.type as property_type');
        $this->db->from('transactions');
        $this->db->join('properties', 'properties.id = transactions.property_id');
        $this->db->order_by('transactions.created_at', 'DESC');
        $this->db->limit($limit);
        return $this->db->get()->result_array();
    }
}`,

  'application/models/User_model.php': `<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * User Model
 * Mengelola Kredensial & Autentikasi RBAC di database
 */
class User_model extends CI_Model {

    public function check_login($username, $password) {
        $this->db->where('username', $username);
        $user = $this->db->get('users')->row_array();

        if ($user) {
            // Verifikasi Password Hash PHP (MD5/SHA256 sesuai skema sistem lama, atau password_verify untuk PHP 7+)
            if (password_verify($password, $user['password']) || md5($password) === $user['password']) {
                return $user;
            }
        }
        return FALSE;
    }

    public function get_user_by_id($id) {
        $this->db->select('users.*, roles.role_name, roles.description as role_desc');
        $this->db->from('users');
        $this->db->join('roles', 'roles.id = users.role_id', 'left');
        $this->db->where('users.id', $id);
        return $this->db->get()->row_array();
    }

    public function get_user_permissions($role_id) {
        $this->db->select('permissions.permission_key');
        $this->db->from('role_permissions');
        $this->db->join('permissions', 'permissions.id = role_permissions.permission_id');
        $this->db->where('role_permissions.role_id', $role_id);
        $query = $this->db->get()->result_array();

        $permissions = array();
        foreach ($query as $row) {
            $permissions[] = $row['permission_key'];
        }
        return $permissions;
    }
}`,

  'application/views/templates/header.php': `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?php echo isset($title) ? $title : 'Portal PropertyHub'; ?></title>

  <!-- Google Font: Source Sans Pro -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
  <!-- Font Awesome Icons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
  <!-- Theme style AdminLTE 3 -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2.0/dist/css/adminlte.min.css">
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

  <!-- Navbar -->
  <nav class="main-header navbar navbar-expand navbar-white navbar-light">
    <!-- Left navbar links -->
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
      </li>
      <li class="nav-item d-none d-sm-inline-block">
        <a href="<?php echo base_url('dashboard'); ?>" class="nav-link">Home</a>
      </li>
    </ul>

    <!-- Right navbar links -->
    <ul class="navbar-nav ml-auto">
      <!-- Alerts Dropdown Menu -->
      <li class="nav-item dropdown">
        <a class="nav-link" data-toggle="dropdown" href="#">
          <i class="far fa-bell"></i>
          <span class="badge badge-warning navbar-badge">3</span>
        </a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="<?php echo base_url('logout'); ?>" role="button" title="Log Out">
          <i class="fas fa-sign-out-alt text-danger"></i>
        </a>
      </li>
    </ul>
  </nav>
  <!-- /.navbar -->`,

  'application/views/templates/sidebar.php': `  <!-- Main Sidebar Container - AdminLTE Sidebar theme-dark-primary -->
  <aside class="main-sidebar sidebar-dark-primary elevation-4">
    <!-- Brand Logo -->
    <a href="<?php echo base_url('dashboard'); ?>" class="brand-link">
      <span class="brand-text font-weight-light">Property<b>Hub</b></span>
    </a>

    <!-- Sidebar -->
    <div class="sidebar">
      <!-- Sidebar user panel (optional) -->
      <div class="user-panel mt-3 pb-3 mb-3 d-flex">
        <div class="image">
          <div class="img-circle elevation-2 bg-info d-flex align-items-center justify-content-center text-white" style="width: 34px; height: 34px; font-weight: bold;">
            <?php echo strtoupper(substr($this->session->userdata('full_name'), 0, 1)); ?>
          </div>
        </div>
        <div class="info">
          <a href="#" class="d-block"><?php echo $this->session->userdata('full_name'); ?></a>
          <span class="text-xs text-muted font-bold"><i class="fa fa-circle text-success text-xs"></i> <?php echo ucfirst($this->session->userdata('role')); ?></span>
        </div>
      </div>

      <!-- Sidebar Menu -->
      <nav class="mt-2">
        <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
          
          <li class="nav-item">
            <a href="<?php echo base_url('dashboard'); ?>" class="nav-link <?php echo ($active_menu === 'dashboard') ? 'active' : ''; ?>">
              <i class="nav-icon fas fa-tachometer-alt"></i>
              <p>Dashboard</p>
            </a>
          </li>

          <li class="nav-item">
            <a href="<?php echo base_url('properties'); ?>" class="nav-link <?php echo ($active_menu === 'property_list') ? 'active' : ''; ?>">
              <i class="nav-icon fas fa-building"></i>
              <p>Jelajah Properti</p>
            </a>
          </li>

          <?php if($this->session->userdata('role') === 'owner'): ?>
          <li class="nav-item">
            <a href="<?php echo base_url('properties/create'); ?>" class="nav-link <?php echo ($active_menu === 'add_property') ? 'active' : ''; ?>">
              <i class="nav-icon fas fa-plus-circle"></i>
              <p>Daftar Properti Baru</p>
            </a>
          </li>
          <?php endif; ?>

          <li class="nav-header">AKSES USER</li>
          <li class="nav-item">
            <a href="<?php echo base_url('logout'); ?>" class="nav-link">
              <i class="nav-icon fas fa-sign-out-alt text-danger"></i>
              <p class="text">Sign Out</p>
            </a>
          </li>
        </ul>
      </nav>
      <!-- /.sidebar-menu -->
    </div>
    <!-- /.sidebar -->
  </aside>`,

  'application/views/templates/footer.php': `  <!-- Main Footer -->
  <footer class="main-footer text-xs">
    <!-- To the right -->
    <div class="float-right d-none d-sm-inline">
      CodeIgniter 3 + AdminLTE 3
    </div>
    <!-- Default to the left -->
    <strong>Copyright &copy; 2026 <a href="#">PropertyHub</a>.</strong> All rights reserved.
  </footer>
</div>
<!-- ./wrapper -->

<!-- REQUIRED SCRIPTS -->
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Bootstrap 4 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2.0/dist/js/adminlte.min.js"></script>
</body>
</html>`,

  'application/views/dashboard.php': `  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <div class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1 class="m-0">Ringkasan Sistem - PropertyHub</h1>
          </div><!-- /.col -->
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">Home</a></li>
              <li class="breadcrumb-item active">Dashboard</li>
            </ol>
          </div><!-- /.col -->
        </div><!-- /.row -->
      </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->

    <!-- Main content -->
    <div class="content">
      <div class="container-fluid">
        
        <!-- Info Boxes Row (Gaya Khas AdminLTE 3) -->
        <div class="row">
          <div class="col-12 col-sm-6 col-md-3">
            <div class="info-box shadow-sm">
              <span class="info-box-icon bg-info elevation-1"><i class="fas fa-building"></i></span>
              <div class="info-box-content">
                <span class="info-box-text">Total Properti</span>
                <span class="info-box-number"><?php echo $stats['total_properties']; ?> Unit</span>
              </div>
            </div>
          </div>
          
          <div class="col-12 col-sm-6 col-md-3">
            <div class="info-box shadow-sm">
              <span class="info-box-icon bg-success elevation-1"><i class="fas fa-money-bill-wave"></i></span>
              <div class="info-box-content">
                <span class="info-box-text">Pendapatan Kotor</span>
                <span class="info-box-number">Rp <?php echo number_format($stats['revenue'], 0, ',', '.'); ?></span>
              </div>
            </div>
          </div>

          <div class="col-12 col-sm-6 col-md-3">
            <div class="info-box shadow-sm">
              <span class="info-box-icon bg-warning elevation-1 text-white"><i class="fas fa-calendar-alt"></i></span>
              <div class="info-box-content">
                <span class="info-box-text">Booking Aktif</span>
                <span class="info-box-number"><?php echo $stats['active_bookings']; ?> Transaksi</span>
              </div>
            </div>
          </div>

          <div class="col-12 col-sm-6 col-md-3">
            <div class="info-box shadow-sm">
              <span class="info-box-icon bg-danger elevation-1"><i class="fas fa-handshake"></i></span>
              <div class="info-box-content">
                <span class="info-box-text">Transaksi Selesai</span>
                <span class="info-box-number"><?php echo $stats['closed_deals']; ?> Deal</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Main Cards Grid Row -->
        <div class="row">
          <div class="col-lg-8">
            
            <!-- Card Transaksi Terkini -->
            <div class="card card-outline card-primary shadow-sm">
              <div class="card-header border-0">
                <h3 class="card-title font-weight-bold">Aktivitas Transaksi Terbaru</h3>
                <div class="card-tools">
                  <button type="button" class="btn btn-tool" data-card-widget="collapse">
                    <i class="fas fa-minus"></i>
                  </button>
                </div>
              </div>
              <div class="card-body table-responsive p-0">
                <table class="table table-striped table-valign-middle text-sm">
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>Pemesan</th>
                      <th>Unit Properti</th>
                      <th>Tipe Layanan</th>
                      <th>Total Biaya</th>
                      <th>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php if(!empty($recent_transactions)): ?>
                      <?php foreach($recent_transactions as $tx): ?>
                        <tr>
                          <td>#<?php echo substr($tx['id'], 0, 6); ?></td>
                          <td><?php echo htmlspecialchars($tx['buyer_name']); ?></td>
                          <td>
                            <span class="font-weight-bold"><?php echo htmlspecialchars($tx['property_name']); ?></span>
                            <span class="badge badge-secondary ml-1"><?php echo $tx['property_type']; ?></span>
                          </td>
                          <td>
                            <span class="badge badge-outline border border-blue text-blue px-2">
                              <?php echo strtoupper($tx['type']); ?>
                            </span>
                          </td>
                          <td>Rp <?php echo number_format($tx['total_price'], 0, ',', '.'); ?></td>
                          <td>
                            <?php if($tx['status'] === 'paid'): ?>
                              <span class="badge badge-success">Terbayar</span>
                            <?php elseif($tx['status'] === 'cancelled'): ?>
                              <span class="badge badge-danger">Dibatalkan</span>
                            <?php else: ?>
                              <span class="badge badge-warning">Menunggu</span>
                            <?php endif; ?>
                          </td>
                        </tr>
                      <?php endforeach; ?>
                    <?php else: ?>
                      <tr>
                        <td colspan="6" class="text-center text-muted">Belum ada aktivitas transaksi terekam.</td>
                      </tr>
                    <?php endif; ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          <div class="col-lg-4">
            
            <!-- Card Info Sistem -->
            <div class="card card-info shadow-sm">
              <div class="card-header">
                <h3 class="card-title font-weight-bold">Status Server PHP & CI3</h3>
              </div>
              <div class="card-body text-xs">
                <ul class="list-group list-group-unbordered">
                  <li class="list-group-item">
                    <b>Framework</b> <span class="float-right text-success">CodeIgniter v3.1.13</span>
                  </li>
                  <li class="list-group-item">
                    <b>Database</b> <span class="float-right text-primary">MySQL v8.0 + MySQLi</span>
                  </li>
                  <li class="list-group-item">
                    <b>Runtime Environment</b> <span class="float-right">PHP 7.4.33</span>
                  </li>
                  <li class="list-group-item">
                    <b>Style Template</b> <span class="float-right">AdminLTE v3.2.0</span>
                  </li>
                  <li class="list-group-item text-center pt-3 border-0">
                    <p class="text-muted">Database SQL tersinkronisasi sempurna dengan skema relasional utama di phpMyAdmin.</p>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>

      </div><!-- /.container-fluid -->
    </div>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->`,

  'application/views/properties/list.php': `  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <div class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1 class="m-0">Daftar Properti Terdaftar</h1>
          </div>
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">Home</a></li>
              <li class="breadcrumb-item active">Properti</li>
            </ol>
          </div>
        </div>
      </div>
    </div>

    <!-- Main content -->
    <div class="content">
      <div class="container-fluid">
        
        <?php if($this->session->flashdata('success')): ?>
          <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <h5><i class="icon fas fa-check"></i> Berhasil!</h5>
            <?php echo $this->session->flashdata('success'); ?>
          </div>
        <?php endif; ?>

        <?php if($this->session->flashdata('error')): ?>
          <div class="alert alert-danger alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <h5><i class="icon fas fa-ban"></i> Error!</h5>
            <?php echo $this->session->flashdata('error'); ?>
          </div>
        <?php endif; ?>

        <!-- Filter Card -->
        <div class="card card-outline card-secondary shadow-sm mb-4">
          <div class="card-body">
            <form action="<?php echo base_url('properties'); ?>" method="GET" class="row">
              <div class="col-md-5">
                <div class="input-group">
                  <input type="text" name="search" class="form-control" placeholder="Cari nama properti atau alamat..." value="<?php echo htmlspecialchars($this->input->get('search')); ?>">
                </div>
              </div>
              <div class="col-md-3">
                <select name="type" class="form-control">
                  <option value="">-- Semua Tipe --</option>
                  <option value="hotel" <?php echo ($this->input->get('type') === 'hotel') ? 'selected' : ''; ?>>Hotel / Villa</option>
                  <option value="apartemen" <?php echo ($this->input->get('type') === 'apartemen') ? 'selected' : ''; ?>>Apartemen</option>
                  <option value="kos" <?php echo ($this->input->get('type') === 'kos') ? 'selected' : ''; ?>>Rumah Kos</option>
                </select>
              </div>
              <div class="col-md-4">
                <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> Cari</button>
                <a href="<?php echo base_url('properties'); ?>" class="btn btn-default ml-2">Reset</a>
              </div>
            </form>
          </div>
        </div>

        <!-- Property Grid -->
        <div class="row">
          <?php if(!empty($properties)): ?>
            <?php foreach($properties as $property): ?>
              <div class="col-md-4">
                <div class="card card-primary card-outline shadow-sm">
                  <img src="<?php echo $property['image_url']; ?>" class="card-img-top" alt="Properti" style="height: 200px; object-fit: cover;">
                  <div class="card-body">
                    <h5 class="card-title font-weight-bold"><?php echo htmlspecialchars($property['name']); ?></h5>
                    <p class="card-text text-muted text-xs mb-2"><i class="fa fa-map-marker-alt"></i> <?php echo htmlspecialchars($property['address']); ?></p>
                    <p class="card-text text-sm text-truncate"><?php echo htmlspecialchars($property['description']); ?></p>
                    
                    <div class="border-top pt-2 mt-2">
                      <span class="badge badge-info uppercase"><?php echo $property['type']; ?></span>
                      <span class="badge badge-success float-right"><?php echo ucfirst($property['status']); ?></span>
                    </div>
                  </div>
                  <div class="card-footer bg-white flex justify-content-between">
                    <a href="<?php echo base_url('properties/view/'.$property['id']); ?>" class="btn btn-xs btn-primary"><i class="fa fa-eye"></i> Detail</a>
                    
                    <?php if($this->session->userdata('role') === 'owner' && $property['owner_id'] === $this->session->userdata('user_id')): ?>
                      <a href="<?php echo base_url('properties/delete/'.$property['id']); ?>" class="btn btn-xs btn-danger ml-2" onclick="return confirm('Hapus listing properti ini?')">
                        <i class="fa fa-trash"></i> Hapus
                      </a>
                    <?php endif; ?>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          <?php else: ?>
            <div class="col-12">
              <div class="card p-5 text-center shadow-xs">
                <p class="text-muted mb-0">Tidak ada properti terdaftar yang memenuhi kriteria pencarian.</p>
              </div>
            </div>
          <?php endif; ?>
        </div>

      </div>
    </div>
  </div>`,

  'application/views/properties/add.php': `  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <div class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1 class="m-0">Tambah Listing Properti Baru</h1>
          </div>
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">Home</a></li>
              <li class="breadcrumb-item"><a href="#">Properti</a></li>
              <li class="breadcrumb-item active">Tambah</li>
            </ol>
          </div>
        </div>
      </div>
    </div>

    <!-- Main content -->
    <div class="content">
      <div class="container-fluid">
        
        <div class="row">
          <div class="col-md-8">
            <div class="card card-primary shadow-sm">
              <div class="card-header">
                <h3 class="card-title">Formulir Pendaftaran Unit</h3>
              </div>
              
              <!-- Menampilkan Error Validasi Form CodeIgniter -->
              <?php if(validation_errors()): ?>
                <div class="alert alert-danger alert-dismissible m-3">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <h5><i class="icon fas fa-ban"></i> Gagal Melakukan Validasi!</h5>
                  <?php echo validation_errors(); ?>
                </div>
              <?php endif; ?>

              <form action="<?php echo base_url('properties/store'); ?>" method="POST">
                <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">

                <div class="card-body">
                  <div class="form-group">
                    <label for="name">Nama Properti *</label>
                    <input type="text" name="name" class="form-control" id="name" placeholder="Contoh: Kost Premium Gading, Hotel Melati..." required value="<?php echo set_value('name'); ?>">
                  </div>

                  <div class="form-group">
                    <label for="type">Tipe Properti *</label>
                    <select name="type" class="form-control" id="type" required>
                      <option value="hotel">Hotel / Villa (Sewa Harian)</option>
                      <option value="apartemen">Apartemen (Sewa Bulanan / Jual)</option>
                      <option value="kos">Rumah Kos (Sewa Bulanan)</option>
                      <option value="house">Rumah Tapak (Jual)</option>
                    </select>
                  </div>

                  <div class="form-group">
                    <label for="address">Alamat Lengkap *</label>
                    <textarea name="address" class="form-control" id="address" rows="2" placeholder="Tulis alamat jalan, nomor, kecamatan, kota..." required><?php echo set_value('address'); ?></textarea>
                  </div>

                  <div class="form-group">
                    <label for="description">Deskripsi Lengkap *</label>
                    <textarea name="description" class="form-control" id="description" rows="4" placeholder="Fasilitas, luas, kelayakan, aturan menginap..." required><?php echo set_value('description'); ?></textarea>
                  </div>

                  <div class="row">
                    <div class="col-md-4">
                      <div class="form-group">
                        <label for="price_day">Harga per Hari (Rp)</label>
                        <input type="number" name="price_day" class="form-control" id="price_day" placeholder="Hanya untuk Hotel/Villa" value="<?php echo set_value('price_day'); ?>">
                      </div>
                    </div>
                    <div class="col-md-4">
                      <div class="form-group">
                        <label for="price_month">Harga per Bulan (Rp)</label>
                        <input type="number" name="price_month" class="form-control" id="price_month" placeholder="Hanya untuk Kost/Apartemen" value="<?php echo set_value('price_month'); ?>">
                      </div>
                    </div>
                    <div class="col-md-4">
                      <div class="form-group">
                        <label for="price_buy">Harga Jual (Rp)</label>
                        <input type="number" name="price_buy" class="form-control" id="price_buy" placeholder="Hanya untuk Rumah/Apartemen" value="<?php echo set_value('price_buy'); ?>">
                      </div>
                    </div>
                  </div>

                  <div class="form-group">
                    <label for="image_url">URL Foto Properti (Opsional)</label>
                    <input type="url" name="image_url" class="form-control" id="image_url" placeholder="https://domain.com/photo.jpg" value="<?php echo set_value('image_url'); ?>">
                  </div>
                </div>

                <div class="card-footer bg-white flex justify-content-between">
                  <button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Publikasikan Listing</button>
                  <a href="<?php echo base_url('properties'); ?>" class="btn btn-default">Kembali</a>
                </div>
              </form>
            </div>
          </div>
          
          <div class="col-md-4">
            <div class="card card-secondary shadow-sm">
              <div class="card-header">
                <h3 class="card-title">Aturan Skema</h3>
              </div>
              <div class="card-body text-xs leading-relaxed text-muted">
                <p><b>1. CSRF Security:</b> Form ini dilengkapi token CSRF otomatis menggunakan <code>$this->security->get_csrf_hash()</code> untuk memproteksi dari serangan lintas-situs.</p>
                <p><b>2. Form Validation:</b> CodeIgniter mendeteksi tipe data masukan secara ketat sebelum meneruskan proses tulis ke database relasional.</p>
                <p><b>3. Tipe Penawaran:</b> Anda dapat memasukkan salah satu atau semua harga penawaran di atas. Layanan akan otomatis terbagi sesuai skema (Stay/Rent/Buy).</p>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>`,

  'application/views/auth/login.php': `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?php echo $title; ?></title>

  <!-- Google Font: Source Sans Pro -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
  <!-- icheck bootstrap -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/icheck-bootstrap@3.0.1/icheck-bootstrap.min.css">
  <!-- Theme style AdminLTE 3 -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2.0/dist/css/adminlte.min.css">
</head>
<body class="hold-transition login-page bg-light">
<div class="login-box">
  <div class="login-logo mb-3">
    <a href="#">Property<b>Hub</b></a>
  </div>
  
  <!-- /.login-logo -->
  <div class="card card-outline card-primary shadow-lg border-0 rounded-lg">
    <div class="card-body login-card-body">
      <p class="login-box-msg font-weight-bold text-gray-800">Silakan Masuk ke Akun Anda</p>

      <?php if($this->session->flashdata('error')): ?>
        <div class="alert alert-danger text-xs mb-3">
          <?php echo $this->session->flashdata('error'); ?>
        </div>
      <?php endif; ?>

      <form action="<?php echo base_url('login'); ?>" method="POST">
        <div class="input-group mb-3">
          <input type="text" name="username" class="form-control" placeholder="Username" required>
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-user text-primary"></span>
            </div>
          </div>
        </div>
        <div class="input-group mb-3">
          <input type="password" name="password" class="form-control" placeholder="Password" required>
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-lock text-primary"></span>
            </div>
          </div>
        </div>
        
        <div class="row">
          <div class="col-8">
            <div class="icheck-primary">
              <input type="checkbox" id="remember">
              <label for="remember">Ingat Saya</label>
            </div>
          </div>
          <!-- /.col -->
          <div class="col-4">
            <button type="submit" class="btn btn-primary btn-block font-weight-bold">MASUK</button>
          </div>
          <!-- /.col -->
        </div>
      </form>
    </div>
    <!-- /.login-card-body -->
  </div>
</div>
<!-- /.login-box -->

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Bootstrap 4 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2.0/dist/js/adminlte.min.js"></script>
</body>
</html>`
};

interface TreeNode {
  name: string;
  type: 'folder' | 'file';
  path: string;
  children?: TreeNode[];
}

// Tree view structure of CodeIgniter 3
const ci3DirectoryTree: TreeNode = {
  name: 'propertyhub',
  type: 'folder',
  path: '',
  children: [
    {
      name: 'application',
      type: 'folder',
      path: 'application',
      children: [
        {
          name: 'config',
          type: 'folder',
          path: 'application/config',
          children: [
            { name: 'autoload.php', type: 'file', path: 'application/config/autoload.php' },
            { name: 'config.php', type: 'file', path: 'application/config/config.php' },
            { name: 'database.php', type: 'file', path: 'application/config/database.php' },
            { name: 'routes.php', type: 'file', path: 'application/config/routes.php' }
          ]
        },
        {
          name: 'controllers',
          type: 'folder',
          path: 'application/controllers',
          children: [
            { name: 'Auth.php', type: 'file', path: 'application/controllers/Auth.php' },
            { name: 'Dashboard.php', type: 'file', path: 'application/controllers/Dashboard.php' },
            { name: 'Property.php', type: 'file', path: 'application/controllers/Property.php' }
          ]
        },
        {
          name: 'models',
          type: 'folder',
          path: 'application/models',
          children: [
            { name: 'Property_model.php', type: 'file', path: 'application/models/Property_model.php' },
            { name: 'User_model.php', type: 'file', path: 'application/models/User_model.php' }
          ]
        },
        {
          name: 'views',
          type: 'folder',
          path: 'application/views',
          children: [
            {
              name: 'auth',
              type: 'folder',
              path: 'application/views/auth',
              children: [
                { name: 'login.php', type: 'file', path: 'application/views/auth/login.php' }
              ]
            },
            {
              name: 'properties',
              type: 'folder',
              path: 'application/views/properties',
              children: [
                { name: 'add.php', type: 'file', path: 'application/views/properties/add.php' },
                { name: 'list.php', type: 'file', path: 'application/views/properties/list.php' }
              ]
            },
            {
              name: 'templates',
              type: 'folder',
              path: 'application/views/templates',
              children: [
                { name: 'footer.php', type: 'file', path: 'application/views/templates/footer.php' },
                { name: 'header.php', type: 'file', path: 'application/views/templates/header.php' },
                { name: 'sidebar.php', type: 'file', path: 'application/views/templates/sidebar.php' }
              ]
            },
            { name: 'dashboard.php', type: 'file', path: 'application/views/dashboard.php' }
          ]
        }
      ]
    },
    {
      name: 'assets',
      type: 'folder',
      path: 'assets',
      children: [
        {
          name: 'adminlte',
          type: 'folder',
          path: 'assets/adminlte',
          children: [
            {
              name: 'css',
              type: 'folder',
              path: 'assets/adminlte/css',
              children: [
                { name: 'adminlte.min.css', type: 'file', path: 'assets/adminlte/css/adminlte.min.css' }
              ]
            },
            {
              name: 'js',
              type: 'folder',
              path: 'assets/adminlte/js',
              children: [
                { name: 'adminlte.min.js', type: 'file', path: 'assets/adminlte/js/adminlte.min.js' }
              ]
            }
          ]
        }
      ]
    },
    { name: '.htaccess', type: 'file', path: '.htaccess' },
    { name: 'index.php', type: 'file', path: 'index.php' }
  ]
};

export default function Ci3TemplateExplorer() {
  const [activeSubTab, setActiveSubTab] = useState<'explorer' | 'preview'>('explorer');
  const [selectedFilePath, setSelectedFilePath] = useState<string>('application/config/database.php');
  const [copied, setCopied] = useState(false);
  const [expandedFolders, setExpandedFolders] = useState<Record<string, boolean>>({
    '': true,
    'application': true,
    'application/config': true,
    'application/controllers': true,
    'application/models': true,
    'application/views': true,
    'application/views/templates': true,
    'assets': false,
    'assets/adminlte': false
  });

  // AdminLTE Preview Interactions State
  const [previewActiveTab, setPreviewActiveTab] = useState<'dashboard' | 'properties' | 'add'>('dashboard');
  const [previewUserRole, setPreviewUserRole] = useState<'owner' | 'guest'>('owner');
  const [searchQuery, setSearchQuery] = useState('');
  const [typeFilter, setTypeFilter] = useState('');

  // Sample data inside AdminLTE Simulator
  const initialProperties = [
    { id: 'p1', name: 'Villa Bunga Indah', type: 'villa', address: 'Jl. Raya Puncak KM 77, Bogor', price: 1500000, status: 'available', image: 'https://images.unsplash.com/photo-1580587771525-78b9dba3b914?auto=format&fit=crop&w=600&q=80' },
    { id: 'p2', name: 'Kost Premium Gading', type: 'kos', address: 'Kelapa Gading Barat, Jakarta Utara', price: 2500000, status: 'available', image: 'https://images.unsplash.com/photo-1522708323590-d24dbb6b0267?auto=format&fit=crop&w=600&q=80' },
    { id: 'p3', name: 'Hotel Grand Mercure', type: 'hotel', address: 'Slamet Riyadi, Solo', price: 850000, status: 'available', image: 'https://images.unsplash.com/photo-1566073771259-6a8506099945?auto=format&fit=crop&w=600&q=80' }
  ];

  const [properties, setProperties] = useState(initialProperties);

  // Form states for AdminLTE simulated insertion
  const [newPropName, setNewPropName] = useState('');
  const [newPropType, setNewPropType] = useState('hotel');
  const [newPropAddress, setNewPropAddress] = useState('');
  const [newPropPrice, setNewPropPrice] = useState('');

  const toggleFolder = (path: string) => {
    setExpandedFolders(prev => ({
      ...prev,
      [path]: !prev[path]
    }));
  };

  const handleCopyCode = () => {
    const code = fileTemplates[selectedFilePath] || '// Placeholder / Library asset file';
    navigator.clipboard.writeText(code);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const downloadFile = (filePath: string) => {
    const content = fileTemplates[filePath] || '// File Library Binary Asset';
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    const filename = filePath.split('/').pop() || 'file.txt';
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // Tree rendering function
  const renderTree = (node: TreeNode) => {
    const isFolder = node.type === 'folder';
    const isExpanded = expandedFolders[node.path];
    const isSelected = selectedFilePath === node.path;

    return (
      <div key={node.path || node.name} className="select-none font-mono text-xs">
        <div 
          onClick={() => {
            if (isFolder) {
              toggleFolder(node.path);
            } else {
              setSelectedFilePath(node.path);
            }
          }}
          className={`flex items-center space-x-1.5 py-1 px-2 rounded-md cursor-pointer transition-colors ${
            isSelected 
              ? 'bg-blue-500 text-white font-medium' 
              : 'text-gray-700 hover:bg-gray-100'
          }`}
        >
          {isFolder && (
            <span>
              {isExpanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
            </span>
          )}
          {!isFolder && <span className="w-3.5" />}
          
          {isFolder ? (
            isExpanded ? <FolderOpen className={`h-4 w-4 ${isSelected ? 'text-white' : 'text-blue-500'}`} /> : <Folder className={`h-4 w-4 ${isSelected ? 'text-white' : 'text-blue-400'}`} />
          ) : (
            <FileCode className={`h-4 w-4 ${isSelected ? 'text-white' : 'text-emerald-500'}`} />
          )}
          
          <span className="truncate">{node.name}</span>
        </div>

        {isFolder && isExpanded && node.children && (
          <div className="pl-4 border-l border-gray-200 ml-3.5 mt-0.5 space-y-0.5">
            {node.children.map(child => renderTree(child))}
          </div>
        )}
      </div>
    );
  };

  // Simulate Add Property inside AdminLTE 3 Form
  const handleSimulatedSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newPropName || !newPropAddress || !newPropPrice) {
      alert('Semua kolom wajib diisi di template AdminLTE!');
      return;
    }
    const newProperty = {
      id: 'p' + (properties.length + 1),
      name: newPropName,
      type: newPropType,
      address: newPropAddress,
      price: parseInt(newPropPrice) || 0,
      status: 'available',
      image: 'https://images.unsplash.com/photo-1564013799919-ab600027ffc6?auto=format&fit=crop&w=600&q=80'
    };
    setProperties([newProperty, ...properties]);
    setNewPropName('');
    setNewPropAddress('');
    setNewPropPrice('');
    setPreviewActiveTab('properties');
  };

  // Filter properties in AdminLTE 3 table
  const filteredProperties = properties.filter(p => {
    const matchesSearch = p.name.toLowerCase().includes(searchQuery.toLowerCase()) || p.address.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesType = typeFilter === '' || p.type === typeFilter;
    return matchesSearch && matchesType;
  });

  return (
    <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden" id="ci3-lte-wrapper">
      {/* Tab Header */}
      <div className="border-b border-gray-100 bg-gray-50 px-6 py-4 flex flex-col md:flex-row justify-between items-start md:items-center space-y-3 md:space-y-0">
        <div>
          <div className="flex items-center space-x-2">
            <span className="bg-orange-100 text-orange-800 text-[10px] font-extrabold uppercase px-2 py-0.5 rounded">CI3 + ADMINLTE3</span>
            <h2 className="font-sans font-bold text-lg text-gray-900">Sistem Eksplorasi Boilerplate & Template</h2>
          </div>
          <p className="text-xs text-gray-500 mt-1">Eksplorasi folder boilerplate MVC lengkap CodeIgniter 3 terintegrasi template AdminLTE 3 untuk aplikasi properti.</p>
        </div>

        {/* Tab Toggle */}
        <div className="bg-gray-200/80 p-0.5 rounded-xl flex">
          <button
            onClick={() => setActiveSubTab('explorer')}
            className={`px-4 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center space-x-1.5 cursor-pointer ${
              activeSubTab === 'explorer' 
                ? 'bg-white text-blue-600 shadow-xs' 
                : 'text-gray-600 hover:text-gray-900'
            }`}
          >
            <Folder className="h-3.5 w-3.5" />
            <span>📁 Struktur Folder CI3</span>
          </button>
          <button
            onClick={() => setActiveSubTab('preview')}
            className={`px-4 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center space-x-1.5 cursor-pointer ${
              activeSubTab === 'preview' 
                ? 'bg-white text-blue-600 shadow-xs' 
                : 'text-gray-600 hover:text-gray-900'
            }`}
          >
            <Layout className="h-3.5 w-3.5" />
            <span>🖥️ Preview AdminLTE 3</span>
          </button>
        </div>
      </div>

      {/* Main Body */}
      {activeSubTab === 'explorer' ? (
        <div className="grid grid-cols-1 lg:grid-cols-12 min-h-[580px]">
          {/* Left Column: Interactive Tree */}
          <div className="lg:col-span-4 border-r border-gray-100 p-4 overflow-y-auto max-h-[600px] bg-slate-50/50">
            <div className="flex items-center justify-between mb-3 border-b border-gray-200 pb-2">
              <span className="text-xs font-bold uppercase tracking-wider text-gray-500 flex items-center space-x-1">
                <Terminal className="h-3.5 w-3.5 text-gray-400" />
                <span>CI3 Project Files</span>
              </span>
              <span className="text-[10px] font-semibold text-gray-400 bg-white border px-2 py-0.5 rounded-full">Pure PHP v7.4</span>
            </div>
            <div className="space-y-1">
              {renderTree(ci3DirectoryTree)}
            </div>
          </div>

          {/* Right Column: Code Viewer / Documentation */}
          <div className="lg:col-span-8 flex flex-col max-h-[600px]">
            {/* Toolbar */}
            <div className="bg-gray-50 border-b border-gray-100 px-5 py-3 flex justify-between items-center text-xs">
              <div className="flex items-center space-x-2">
                <FileCode className="h-4 w-4 text-emerald-600" />
                <span className="font-mono font-bold text-gray-700">{selectedFilePath}</span>
              </div>
              <div className="flex items-center space-x-2">
                <button
                  onClick={handleCopyCode}
                  className="bg-white border border-gray-200 hover:border-gray-300 text-gray-700 font-medium px-3 py-1.5 rounded-lg flex items-center space-x-1 shadow-2xs cursor-pointer active:scale-95 transition-all"
                >
                  {copied ? <Check className="h-3.5 w-3.5 text-emerald-500" /> : <Copy className="h-3.5 w-3.5" />}
                  <span>{copied ? 'Copied' : 'Salin Kode'}</span>
                </button>
                <button
                  onClick={() => downloadFile(selectedFilePath)}
                  className="bg-white border border-gray-200 hover:border-gray-300 text-gray-700 font-medium px-3 py-1.5 rounded-lg flex items-center space-x-1 shadow-2xs cursor-pointer active:scale-95 transition-all"
                  title="Unduh File PHP ini"
                >
                  <Download className="h-3.5 w-3.5 text-blue-500" />
                  <span>Unduh</span>
                </button>
              </div>
            </div>

            {/* Code Block Wrapper */}
            <div className="flex-1 overflow-auto p-5 bg-slate-950 text-slate-100 font-mono text-xs leading-relaxed max-h-[480px]">
              {fileTemplates[selectedFilePath] ? (
                <pre className="whitespace-pre overflow-x-auto select-text selection:bg-blue-600 selection:text-white">
                  {fileTemplates[selectedFilePath]}
                </pre>
              ) : (
                <div className="h-full flex flex-col items-center justify-center text-slate-500 space-y-2">
                  <Database className="h-8 w-8 text-slate-600 animate-pulse" />
                  <p>Binary / library template file.</p>
                  <p className="text-[10px] text-center max-w-xs">AdminLTE style dependencies (jQuery, Bootstrap, & AdminLTE JS) dimuat eksternal via CDN di file footer.php.</p>
                </div>
              )}
            </div>

            {/* Info Footer */}
            <div className="bg-blue-50/50 border-t border-blue-100/50 px-5 py-3 text-xs text-blue-800 flex items-start space-x-2">
              <Info className="h-4 w-4 text-blue-500 shrink-0 mt-0.5" />
              <p className="leading-relaxed">
                <b>Tips Integrasi:</b> Pada CodeIgniter 3, view dipecah menjadi <code>header.php</code>, <code>sidebar.php</code>, dan <code>footer.php</code> agar halaman dinamis (seperti <code>dashboard.php</code>) dapat dipanggil bersih tanpa harus menulis ulang tag navigasi AdminLTE.
              </p>
            </div>
          </div>
        </div>
      ) : (
        /* CodeIgniter + AdminLTE 3 Interactive Live Preview Simulator */
        <div className="bg-slate-100 p-2 md:p-4 min-h-[580px] font-sans">
          {/* Header Controls for simulator */}
          <div className="bg-white p-3 rounded-xl shadow-xs border border-gray-200 mb-4 flex flex-col md:flex-row justify-between items-center space-y-2 md:space-y-0 text-xs">
            <span className="font-semibold text-gray-700 flex items-center space-x-1.5">
              <Activity className="h-4 w-4 text-orange-500 animate-spin" />
              <span>Simulasi Live View - Template Dashboard AdminLTE 3 (PropertyHub Portal)</span>
            </span>
            <div className="flex items-center space-x-3">
              <label className="font-medium text-gray-500">Ganti Hak Akses Akun:</label>
              <select 
                value={previewUserRole}
                onChange={(e) => setPreviewUserRole(e.target.value as 'owner' | 'guest')}
                className="bg-gray-100 border rounded-lg px-2.5 py-1 text-xs font-bold text-gray-800 cursor-pointer outline-none"
              >
                <option value="owner">Host / Pemilik Properti (Owner)</option>
                <option value="guest">Tamu / Pengunjung (Guest)</option>
              </select>
            </div>
          </div>

          {/* AdminLTE 3 Wrapper Mock */}
          <div className="bg-[#f4f6f9] border border-gray-300 rounded-lg shadow-xl overflow-hidden flex flex-col md:flex-row min-h-[500px]">
            
            {/* MOCK SIDEBAR: sidebar-dark-primary */}
            <div className="w-full md:w-64 bg-[#343a40] text-[#c2c6ca] flex flex-col select-none">
              {/* Brand Logo */}
              <div className="px-4 py-3 border-b border-[#4b545c] flex items-center space-x-2 bg-[#3f474e]">
                <div className="bg-blue-600 text-white font-black px-2 py-0.5 rounded text-sm">P</div>
                <span className="font-light text-white text-sm tracking-wide">Property<b>Hub</b></span>
              </div>

              {/* User Panel */}
              <div className="px-3 py-3 border-b border-[#4b545c] flex items-center space-x-2.5">
                <div className="h-8 w-8 rounded-full bg-info flex items-center justify-center font-bold text-xs text-white uppercase">
                  {previewUserRole === 'owner' ? 'O' : 'G'}
                </div>
                <div className="flex flex-col text-xs leading-tight">
                  <span className="text-white font-medium">{previewUserRole === 'owner' ? 'Yuga Nugraha' : 'Tamu Simulator'}</span>
                  <span className="text-[10px] text-emerald-400 font-semibold mt-0.5">
                    <span className="inline-block h-1.5 w-1.5 rounded-full bg-emerald-400 mr-1 align-middle"></span>
                    Online • {previewUserRole === 'owner' ? 'Owner' : 'Guest'}
                  </span>
                </div>
              </div>

              {/* Sidebar Menu Navigation Links */}
              <div className="flex-1 p-2 space-y-1 overflow-y-auto">
                <button
                  onClick={() => setPreviewActiveTab('dashboard')}
                  className={`w-full text-left px-3 py-2 rounded text-xs flex items-center space-x-2.5 transition-colors cursor-pointer ${
                    previewActiveTab === 'dashboard'
                      ? 'bg-blue-600 text-white font-semibold'
                      : 'hover:bg-gray-700/50 hover:text-white'
                  }`}
                >
                  <Layout className="h-4 w-4 shrink-0" />
                  <span className="flex-1">Dashboard Utama</span>
                </button>

                <button
                  onClick={() => setPreviewActiveTab('properties')}
                  className={`w-full text-left px-3 py-2 rounded text-xs flex items-center space-x-2.5 transition-colors cursor-pointer ${
                    previewActiveTab === 'properties'
                      ? 'bg-blue-600 text-white font-semibold'
                      : 'hover:bg-gray-700/50 hover:text-white'
                  }`}
                >
                  <Building2 className="h-4 w-4 shrink-0" />
                  <span className="flex-1">Jelajah Properti</span>
                </button>

                {previewUserRole === 'owner' && (
                  <button
                    onClick={() => setPreviewActiveTab('add')}
                    className={`w-full text-left px-3 py-2 rounded text-xs flex items-center space-x-2.5 transition-colors cursor-pointer ${
                      previewActiveTab === 'add'
                        ? 'bg-blue-600 text-white font-semibold'
                        : 'hover:bg-gray-700/50 hover:text-white'
                    }`}
                  >
                    <FolderOpen className="h-4 w-4 shrink-0" />
                    <span className="flex-1">Tambah Listing Baru</span>
                  </button>
                )}

                <div className="border-t border-[#4b545c] my-2 pt-2 text-[10px] uppercase font-bold text-gray-500 px-3 tracking-wider">
                  Utility Tools
                </div>

                <div className="px-3 py-1.5 text-[11px] text-gray-400 font-mono space-y-1">
                  <div>CI3 Driver: <span className="text-orange-400">mysqli</span></div>
                  <div>BaseURL: <span className="text-blue-400">localhost</span></div>
                </div>
              </div>

              {/* Footer mini */}
              <div className="p-2 border-t border-[#4b545c] text-[10px] text-center text-gray-500">
                AdminLTE v3.2.0 Mock
              </div>
            </div>

            {/* MOCK MAIN CONTENT AREA */}
            <div className="flex-1 flex flex-col overflow-x-hidden">
              {/* TOP NAVBAR */}
              <div className="bg-white border-b border-gray-200 px-4 py-2.5 flex justify-between items-center select-none shrink-0">
                <div className="flex items-center space-x-3">
                  <Menu className="h-4 w-4 text-gray-600 cursor-pointer" />
                  <span className="text-xs text-gray-600 font-semibold hover:text-blue-600 cursor-pointer">Home</span>
                  <span className="text-xs text-gray-400">|</span>
                  <span className="text-xs text-gray-500">CodeIgniter 3 Portal</span>
                </div>
                <div className="flex items-center space-x-4">
                  <Search className="h-4 w-4 text-gray-400 cursor-pointer" />
                  <MessageSquare className="h-4 w-4 text-gray-400 cursor-pointer" />
                  <div className="relative">
                    <Bell className="h-4 w-4 text-gray-400 cursor-pointer" />
                    <span className="absolute -top-1.5 -right-1.5 bg-yellow-500 text-white font-black text-[8px] h-3.5 w-3.5 rounded-full flex items-center justify-center">3</span>
                  </div>
                  <Maximize className="h-4 w-4 text-gray-400 cursor-pointer" />
                </div>
              </div>

              {/* MAIN BODY WRAPPER */}
              <div className="flex-1 p-4 overflow-y-auto">
                {/* Content Header */}
                <div className="flex justify-between items-center border-b border-gray-200 pb-3 mb-4 select-none">
                  <div>
                    <h3 className="font-sans font-bold text-base text-gray-800">
                      {previewActiveTab === 'dashboard' && 'Dashboard Analisis - PropertyHub'}
                      {previewActiveTab === 'properties' && 'Listing Properti Terintegrasi'}
                      {previewActiveTab === 'add' && 'Daftarkan Unit Properti Baru'}
                    </h3>
                  </div>
                  <div className="text-xs text-gray-500 font-mono">
                    Home / <span className="font-bold">{previewActiveTab}</span>
                  </div>
                </div>

                {/* Sub Tab Panel 1: Dashboard View */}
                {previewActiveTab === 'dashboard' && (
                  <div className="space-y-4">
                    {/* AdminLTE 3 Info Boxes */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-3">
                      {/* Box 1: Blue */}
                      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-3 flex items-center space-x-3">
                        <div className="bg-blue-600 text-white p-3 rounded-lg">
                          <Building2 className="h-5 w-5" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <span className="text-[10px] text-gray-400 uppercase font-bold tracking-wider">Total Listing</span>
                          <h4 className="font-bold text-sm text-gray-900 mt-0.5">{properties.length} Unit</h4>
                        </div>
                      </div>

                      {/* Box 2: Green */}
                      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-3 flex items-center space-x-3">
                        <div className="bg-emerald-600 text-white p-3 rounded-lg">
                          <DollarSign className="h-5 w-5" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <span className="text-[10px] text-gray-400 uppercase font-bold tracking-wider">Kotor Masuk</span>
                          <h4 className="font-bold text-sm text-gray-900 mt-0.5">Rp 145,2 Juta</h4>
                        </div>
                      </div>

                      {/* Box 3: Yellow */}
                      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-3 flex items-center space-x-3">
                        <div className="bg-amber-500 text-white p-3 rounded-lg">
                          <CalendarDays className="h-5 w-5" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <span className="text-[10px] text-gray-400 uppercase font-bold tracking-wider">Booking Aktif</span>
                          <h4 className="font-bold text-sm text-gray-900 mt-0.5">14 Transaksi</h4>
                        </div>
                      </div>

                      {/* Box 4: Red */}
                      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-3 flex items-center space-x-3">
                        <div className="bg-rose-600 text-white p-3 rounded-lg">
                          <Users className="h-5 w-5" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <span className="text-[10px] text-gray-400 uppercase font-bold tracking-wider">User Aktif</span>
                          <h4 className="font-bold text-sm text-gray-900 mt-0.5">28 Akun</h4>
                        </div>
                      </div>
                    </div>

                    {/* Lower Area Cards */}
                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
                      {/* Left: Table transactions */}
                      <div className="lg:col-span-8 bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden">
                        <div className="border-b border-gray-100 px-4 py-2.5 bg-gray-50 flex justify-between items-center">
                          <span className="text-xs font-bold text-gray-800">Aktivitas Transaksi Server Terkini</span>
                          <span className="bg-blue-100 text-blue-800 text-[9px] font-bold px-2 py-0.5 rounded-full">Query Active Record</span>
                        </div>
                        <div className="overflow-x-auto text-xs">
                          <table className="w-full text-left border-collapse">
                            <thead>
                              <tr className="border-b border-gray-200 bg-gray-100/50 text-gray-500 font-bold">
                                <th className="p-3">ID Tx</th>
                                <th className="p-3">Pemesan</th>
                                <th className="p-3">Properti</th>
                                <th className="p-3">Nominal</th>
                                <th className="p-3">Status</th>
                              </tr>
                            </thead>
                            <tbody>
                              <tr className="border-b border-gray-100 hover:bg-gray-50/50">
                                <td className="p-3 font-mono">#TX-908</td>
                                <td className="p-3">Budi Santoso</td>
                                <td className="p-3 font-semibold">Kost Premium Gading</td>
                                <td className="p-3 font-bold">Rp 2.500.000</td>
                                <td className="p-3"><span className="bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded text-[9px] font-bold">Paid</span></td>
                              </tr>
                              <tr className="border-b border-gray-100 hover:bg-gray-50/50">
                                <td className="p-3 font-mono">#TX-907</td>
                                <td className="p-3">Sri Lestari</td>
                                <td className="p-3 font-semibold">Hotel Grand Mercure</td>
                                <td className="p-3 font-bold">Rp 850.000</td>
                                <td className="p-3"><span className="bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded text-[9px] font-bold">Paid</span></td>
                              </tr>
                              <tr className="border-b border-gray-100 hover:bg-gray-50/50">
                                <td className="p-3 font-mono">#TX-906</td>
                                <td className="p-3">Dewi Siska</td>
                                <td className="p-3 font-semibold">Villa Bunga Indah</td>
                                <td className="p-3 font-bold">Rp 1.500.000</td>
                                <td className="p-3"><span className="bg-amber-100 text-amber-800 px-2 py-0.5 rounded text-[9px] font-bold">Pending</span></td>
                              </tr>
                            </tbody>
                          </table>
                        </div>
                      </div>

                      {/* Right: Server Status Diagnostics */}
                      <div className="lg:col-span-4 bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden p-4 space-y-3">
                        <h4 className="text-xs font-bold text-gray-800 border-b pb-2 flex items-center space-x-1">
                          <Server className="h-3.5 w-3.5 text-blue-500" />
                          <span>Status Server (Autoloaded)</span>
                        </h4>
                        <div className="space-y-2 text-[11px]">
                          <div className="flex justify-between">
                            <span className="text-gray-500">PHP Version</span>
                            <span className="font-mono font-semibold text-gray-800">7.4.33</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-gray-500">Framework Code</span>
                            <span className="font-mono font-semibold text-gray-800">CodeIgniter 3.1.13</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-gray-500">Database Driver</span>
                            <span className="font-mono font-semibold text-gray-800">mysqli (MySQL)</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-gray-500">Template Style</span>
                            <span className="font-mono font-semibold text-gray-800">AdminLTE v3.2.0</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-gray-500">CSRF Hash Protection</span>
                            <span className="font-mono text-emerald-600 font-bold">Enabled (Active)</span>
                          </div>
                        </div>
                        <div className="bg-slate-50 border p-2.5 rounded-lg text-[10px] text-gray-500 font-mono leading-relaxed mt-2">
                          <span className="text-blue-600 font-bold">$autoload['libraries']</span> = array('database', 'session', 'form_validation');
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {/* Sub Tab Panel 2: Properties Grid Simulator */}
                {previewActiveTab === 'properties' && (
                  <div className="space-y-4">
                    {/* Filters form */}
                    <div className="bg-white p-3 rounded-lg border border-gray-200 flex flex-col md:flex-row space-y-2 md:space-y-0 md:space-x-3 items-center text-xs">
                      <div className="flex-1 w-full">
                        <input
                          type="text"
                          placeholder="Cari properti..."
                          value={searchQuery}
                          onChange={(e) => setSearchQuery(e.target.value)}
                          className="w-full bg-gray-50 border rounded-lg px-3 py-1.5 outline-none focus:border-blue-500"
                        />
                      </div>
                      <div className="w-full md:w-48">
                        <select
                          value={typeFilter}
                          onChange={(e) => setTypeFilter(e.target.value)}
                          className="w-full bg-gray-50 border rounded-lg px-2.5 py-1.5 cursor-pointer outline-none"
                        >
                          <option value="">-- Semua Tipe --</option>
                          <option value="hotel">Hotel / Villa</option>
                          <option value="apartemen">Apartemen</option>
                          <option value="kos">Rumah Kos</option>
                        </select>
                      </div>
                    </div>

                    {/* Table / Cards row */}
                    <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                      {filteredProperties.map(p => (
                        <div key={p.id} className="bg-white rounded-lg border border-gray-200 overflow-hidden shadow-2xs flex flex-col">
                          <img src={p.image} className="h-32 w-full object-cover" alt="Property image" />
                          <div className="p-3 flex-1">
                            <span className="bg-orange-100 text-orange-800 text-[9px] font-bold uppercase px-1.5 py-0.5 rounded">
                              {p.type}
                            </span>
                            <h4 className="font-sans font-bold text-xs text-gray-800 mt-1.5">{p.name}</h4>
                            <p className="text-[10px] text-gray-400 mt-1 truncate">{p.address}</p>
                            <div className="mt-2.5 border-t pt-2 flex justify-between items-center text-xs font-semibold text-gray-900">
                              <span>Harga Unit:</span>
                              <span className="text-blue-600">Rp {p.price.toLocaleString('id-ID')}</span>
                            </div>
                          </div>
                          <div className="bg-gray-50 border-t border-gray-100 px-3 py-2 flex justify-between select-none">
                            <span className="text-[10px] text-gray-400 font-bold self-center">ID: {p.id}</span>
                            <span className="bg-emerald-50 text-emerald-700 text-[10px] font-bold px-2 py-0.5 rounded border border-emerald-100">
                              {p.status}
                            </span>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Sub Tab Panel 3: Add Form Simulator */}
                {previewActiveTab === 'add' && (
                  <div className="max-w-xl mx-auto bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden">
                    <div className="border-b border-gray-100 px-4 py-3 bg-gray-50 font-bold text-xs text-gray-800">
                      Formulir Tambah Properti (Active Record Save)
                    </div>
                    <form onSubmit={handleSimulatedSubmit} className="p-4 space-y-3 text-xs">
                      <div className="space-y-1">
                        <label className="font-semibold text-gray-700">Nama Properti *</label>
                        <input
                          type="text"
                          required
                          placeholder="Masukkan nama properti..."
                          value={newPropName}
                          onChange={(e) => setNewPropName(e.target.value)}
                          className="w-full bg-gray-50 border rounded-lg px-3 py-1.5 outline-none"
                        />
                      </div>

                      <div className="space-y-1">
                        <label className="font-semibold text-gray-700">Tipe Properti *</label>
                        <select
                          value={newPropType}
                          onChange={(e) => setNewPropType(e.target.value)}
                          className="w-full bg-gray-50 border rounded-lg px-2.5 py-1.5 outline-none cursor-pointer"
                        >
                          <option value="hotel">Hotel / Villa (Sewa Harian)</option>
                          <option value="apartemen">Apartemen (Sewa Bulanan)</option>
                          <option value="kos">Rumah Kos (Sewa Bulanan)</option>
                        </select>
                      </div>

                      <div className="space-y-1">
                        <label className="font-semibold text-gray-700">Alamat Lengkap *</label>
                        <textarea
                          required
                          rows={2}
                          placeholder="Masukkan alamat lengkap unit..."
                          value={newPropAddress}
                          onChange={(e) => setNewPropAddress(e.target.value)}
                          className="w-full bg-gray-50 border rounded-lg px-3 py-1.5 outline-none"
                        />
                      </div>

                      <div className="space-y-1">
                        <label className="font-semibold text-gray-700">Harga Unit (Rupiah) *</label>
                        <input
                          type="number"
                          required
                          placeholder="Contoh: 1500000"
                          value={newPropPrice}
                          onChange={(e) => setNewPropPrice(e.target.value)}
                          className="w-full bg-gray-50 border rounded-lg px-3 py-1.5 outline-none"
                        />
                      </div>

                      <div className="pt-3 border-t border-gray-100 flex justify-end space-x-2">
                        <button
                          type="button"
                          onClick={() => setPreviewActiveTab('dashboard')}
                          className="px-4 py-1.5 border rounded-lg hover:bg-gray-50 font-bold cursor-pointer"
                        >
                          Batal
                        </button>
                        <button
                          type="submit"
                          className="px-4 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-bold shadow-sm cursor-pointer"
                        >
                          Simpan ke Database
                        </button>
                      </div>
                    </form>
                  </div>
                )}
              </div>

              {/* FOOTER */}
              <div className="bg-white border-t border-gray-200 px-4 py-2 flex justify-between select-none text-[10px] text-gray-500 shrink-0">
                <span>Copyright &copy; 2026 PropertyHub. All rights reserved.</span>
                <span className="font-bold">CodeIgniter 3 + AdminLTE 3.2.0</span>
              </div>
            </div>

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