<?php
declare(strict_types=1);
session_start();
if (!isset($_SESSION['user_id']) || (int)$_SESSION['user_id'] <= 0) {
  header('Location: login.html');
  exit;
}
$userId = (int)$_SESSION['user_id'];
$username = (string)($_SESSION['username'] ?? 'User');

$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

try {
  $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  ]);
} catch (Throwable $e) {
  http_response_code(500);
  echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Database connection failed.');window.location.href='index-2.php';</script></body></html>";
  exit;
}

try {
  $pdo->exec('CREATE TABLE IF NOT EXISTS chat_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT UNSIGNED NOT NULL,
    sender ENUM("user","admin") NOT NULL,
    content TEXT NOT NULL,
    is_read TINYINT(1) NOT NULL DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}

if (isset($_GET['action'])) {
  header('Content-Type: application/json');
  $action = (string)$_GET['action'];
  if ($action === 'list') {
    try {
      $stmt = $pdo->prepare('SELECT id,sender,content,is_read,created_at FROM chat_messages WHERE user_id=:u ORDER BY created_at ASC LIMIT 500');
      $stmt->execute([':u' => $userId]);
      $items = $stmt->fetchAll();
      // mark admin messages as read
      $pdo->prepare("UPDATE chat_messages SET is_read=1 WHERE user_id=:u AND sender='admin' AND is_read=0")->execute([':u'=>$userId]);
    } catch (Throwable $e) { $items = []; }
    echo json_encode(['items' => $items]);
    exit;
  }
  if ($action === 'send') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['ok'=>false]); exit; }
    $content = trim((string)($_POST['content'] ?? ''));
    if ($content === '') { echo json_encode(['ok'=>false,'error'=>'Empty']); exit; }
    try {
      $st = $pdo->prepare("INSERT INTO chat_messages(user_id,sender,content) VALUES(:u,'user',:c)");
      $st->execute([':u'=>$userId, ':c'=>$content]);
      echo json_encode(['ok'=>true]);
    } catch (Throwable $e) { echo json_encode(['ok'=>false]); }
    exit;
  }
  echo json_encode(['ok'=>false]);
  exit;
}
?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>Chat - ListBnb</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="shortcut icon" type="image/x-icon" href="assets/img/logo/favicon.png">
  <link rel="stylesheet" href="assets/css/bootstrap.css">
  <link rel="stylesheet" href="assets/css/animate.css">
  <link rel="stylesheet" href="assets/css/swiper-bundle.css">
  <link rel="stylesheet" href="assets/css/slick.css">
  <link rel="stylesheet" href="assets/css/magnific-popup.css">
  <link rel="stylesheet" href="assets/css/font-awesome-pro.css">
  <link rel="stylesheet" href="assets/css/spacing.css">
  <link rel="stylesheet" href="assets/css/custom-animation.css">
  <link rel="stylesheet" href="assets/css/main.css">
  <style>
    :root {
      /* Modern Color Scheme */
      --primary: #2563eb;
      --primary-light: #dbeafe;
      --primary-dark: #1d4ed8;
      --secondary: #4f46e5;
      --success: #059669;
      --danger: #dc2626;
      --warning: #d97706;
      --info: #0284c7;
      --dark: #111827;
      --darker: #0f172a;
      --light: #f8fafc;
      --lighter: #f1f5f9;
      --border: #e2e8f0;
      --text: #1e293b;
      --text-light: #64748b;
      --text-lighter: #94a3b8;
      --radius: 12px;
      --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
      --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
      --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
      --transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    }

    body {
      background-color: #f8fafc;
      color: var(--text);
      font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      line-height: 1.6;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }

    .chat-layout {
      display: grid;
      grid-template-columns: 320px 1fr;
      gap: 0;
      max-width: 1400px;
      margin: 0 auto;
      height: calc(100vh - 80px);
      background: #fff;
      border-radius: var(--radius);
      overflow: hidden;
      box-shadow: var(--shadow-lg);
      border: 1px solid var(--border);
    }

    @media (max-width: 991px) {
      .chat-layout {
        grid-template-columns: 1fr;
        height: auto;
        min-height: calc(100vh - 200px);
      }
    }

    .chat-list {
      background: #fff;
      border-right: 1px solid var(--border);
      display: flex;
      flex-direction: column;
      height: 100%;
      overflow: hidden;
    }

    .chat-list-header {
      padding: 20px;
      border-bottom: 1px solid var(--border);
      background: #fff;
      z-index: 2;
    }

    .chat-list-header h3 {
      margin: 0;
      font-size: 18px;
      color: var(--dark);
    }

    .chat-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 14px 20px;
      cursor: pointer;
      transition: var(--transition);
      border-bottom: 1px solid var(--border);
      background: #fff;
      position: relative;
    }
    
    .chat-item:last-child {
      border-bottom: none;
    }

    .chat-item:hover {
      background: var(--lighter);
    }

    .chat-item.active {
      background: var(--primary-light);
      border-left: 3px solid var(--primary);
    }
    
    .chat-item.active .chat-item-name {
      color: var(--primary-dark);
      font-weight: 600;
    }

    .chat-avatar {
      width: 44px;
      height: 44px;
      border-radius: 12px;
      background: linear-gradient(135deg, var(--primary), var(--secondary));
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 600;
      font-size: 16px;
      flex-shrink: 0;
      box-shadow: var(--shadow);
    }

    .chat-item-details {
      flex: 1;
      min-width: 0;
    }

    .chat-item-name {
      font-weight: 600;
      color: var(--dark);
      margin-bottom: 4px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .chat-item-preview {
      font-size: 13px;
      color: var(--text-light);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .chat-room {
      background: #f8fafc;
      display: flex;
      flex-direction: column;
      height: 100%;
      position: relative;
    }

    .chat-head {
      padding: 18px 24px;
      border-bottom: 1px solid var(--border);
      font-weight: 600;
      font-size: 16px;
      color: var(--dark);
      background: #fff;
      display: flex;
      align-items: center;
      gap: 12px;
      position: sticky;
      top: 0;
      z-index: 10;
      box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    }

    .chat-head-avatar {
      width: 36px;
      height: 36px;
      border-radius: 8px;
      background: var(--primary);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 600;
      font-size: 14px;
    }

    .chat-body {
      flex: 1;
      overflow-y: auto;
      padding: 24px;
      background: #f8fafc;
      display: flex;
      flex-direction: column;
      gap: 16px;
      background-image: url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z' fill='%23e2e8f0' fill-opacity='0.4' fill-rule='evenodd'/%3E%3C/svg%3E");
    }

    .msg {
      max-width: 75%;
      margin: 4px 0;
      padding: 12px 16px;
      border-radius: 18px;
      position: relative;
      line-height: 1.6;
      animation: messageIn 0.3s ease-out;
      box-shadow: var(--shadow);
      font-size: 15px;
      word-wrap: break-word;
    }

    @keyframes messageIn {
      from {
        opacity: 0;
        transform: translateY(10px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .msg.me {
      margin-left: auto;
      background: var(--primary);
      color: white;
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
      border-top-left-radius: 18px;
      border-bottom-left-radius: 18px;
    }

    .msg.other {
      background: white;
      border: 1px solid var(--border);
      border-top-left-radius: 4px;
      border-bottom-left-radius: 4px;
      border-top-right-radius: 18px;
      border-bottom-right-radius: 18px;
    }

    .msg-time {
      font-size: 11px;
      color: rgba(255, 255, 255, 0.8);
      margin-top: 4px;
      text-align: right;
    }

    .msg.me .msg-time {
      color: rgba(255, 255, 255, 0.8);
    }

    .msg.other .msg-time {
      color: var(--text-light);
    }

    .chat-input-container {
      padding: 20px 24px;
      border-top: 1px solid var(--border);
      background: #fff;
      position: sticky;
      bottom: 0;
      z-index: 10;
      box-shadow: 0 -1px 3px rgba(0,0,0,0.05);
    }

    .chat-input {
      display: flex;
      gap: 12px;
      align-items: flex-end;
    }

    .chat-input input {
      flex: 1;
      height: 48px;
      border: 2px solid var(--border);
      border-radius: 24px;
      padding: 0 20px;
      font-size: 15px;
      transition: var(--transition);
      outline: none;
      background: #fff;
      box-shadow: var(--shadow-sm);
    }
    
    .chat-input input:focus {
      border-color: var(--primary);
      box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
    }

    .chat-input input:focus {
      border-color: var(--primary);
      box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
    }

    .chat-input button {
      height: 48px;
      border-radius: 24px;
      border: none;
      background: var(--primary);
      color: white;
      padding: 0 24px;
      font-weight: 500;
      cursor: pointer;
      transition: var(--transition);
      display: flex;
      align-items: center;
      gap: 8px;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    }
    
    .chat-input button:hover {
      background: var(--primary-dark);
      transform: translateY(-1px);
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    }
    
    .chat-input button:active {
      transform: translateY(0);
    }

    .chat-input button:hover {
      background: var(--primary-dark);
      transform: translateY(-1px);
    }

    .chat-input button:active {
      transform: translateY(0);
    }

    .chat-input button i {
      font-size: 16px;
    }

    /* Custom scrollbar */
    ::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }

    ::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 4px;
    }

    ::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 4px;
    }

    ::-webkit-scrollbar-thumb:hover {
      background: #a8a8a8;
    }

    /* Empty state */
    .chat-empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      text-align: center;
      padding: 40px 20px;
      color: var(--text-light);
    }

    .chat-empty-state i {
      font-size: 48px;
      margin-bottom: 16px;
      color: var(--border);
    }

    .chat-empty-state h4 {
      margin: 0 0 8px;
      color: var(--dark);
    }

    /* Typing indicator */
    .typing-indicator {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 12px 18px;
      background: white;
      border: 1px solid var(--border);
      border-radius: 24px;
      margin-top: 8px;
      max-width: 120px;
      box-shadow: var(--shadow-sm);
    }

    .typing-dot {
      width: 8px;
      height: 8px;
      background: var(--primary);
      border-radius: 50%;
      display: inline-block;
      animation: typing 1.4s infinite ease-in-out both;
    }

    .typing-dot:nth-child(1) { 
      animation-delay: -0.32s; 
      background: var(--primary);
    }
    .typing-dot:nth-child(2) { 
      animation-delay: -0.16s; 
      background: var(--primary);
      opacity: 0.8;
    }
    .typing-dot:nth-child(3) { 
      background: var(--primary);
      opacity: 0.6;
    }

    @keyframes typing {
      0%, 80%, 100% { 
        transform: scale(0.8);
        opacity: 0.5;
      }
      40% { 
        transform: scale(1.1);
        opacity: 1;
      }
    }
    
    /* Image preview in messages */
    .message-image {
      max-width: 100%;
      max-height: 300px;
      border-radius: 12px;
      margin: 8px 0;
      cursor: pointer;
      transition: transform 0.2s ease;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .message-image:hover {
      transform: scale(1.02);
    }
    
    /* Scrollbar styling */
    ::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }
    
    ::-webkit-scrollbar-track {
      background: rgba(0,0,0,0.03);
      border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb {
      background: rgba(0,0,0,0.1);
      border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb:hover {
      background: rgba(0,0,0,0.2);
    }
  </style>
 </head>
 <body>
   <header class="tp-header-height">
     <div id="header-sticky" class="tp-header-area tp-header-inner-style">
       <div class="container">
         <div class="row align-items-center">
           <div class="col-xl-3 col-lg-6 col-md-6 col-6">
            <div class="tp-header-logo">
               <a href="index-2.php" class="brand-text">ReWear</a>
             </div>
           </div>
           <div class="col-xl-6 col-lg-4 d-none d-xl-block">
             <div class="tp-header-menu">
               <nav class="tp-main-menu-content">
                 <ul>
                   <li class="has-dropdown"><a href="index-2.php">Home</a></li>
                   <li class="has-dropdown">
                     <a href="#">Categories</a>
                     <ul class="submenu tp-submenu">
                       <li><a href="category.php?category=Summer%20Clothing">Summer Clothing</a></li>
                       <li><a href="category.php?category=Winter%20Clothing">Winter Clothing</a></li>
                       <li><a href="category.php?category=Party%20%26%20Formal%20Wear">Party & Formal Wear</a></li>
                       <li><a href="category.php?category=Active%20Wear%20%2F%20Gym%20Wear">Active Wear / Gym Wear</a></li>
                       <li><a href="category.php?category=Nightwear%20%2F%20Sleepwear">Nightwear / Sleepwear</a></li>
                       <li><a href="category.php?category=Modest%20Wear">Modest Wear</a></li>
                       <li><a href="category.php?category=Casual%20Wear">Casual Wear</a></li>
                     </ul>
                   </li>
                   <li><a href="about-us.html">About Us</a></li>
                   <li class="has-dropdown"><a href="#site-contact">Contact</a></li>
                 </ul>
               </nav>
             </div>
           </div>
           <div class="col-xl-3 col-lg-6 col-md-6 col-6">
             <div class="tp-header-right d-flex align-items-center justify-content-end">
               <div class="tp-header-btn d-none d-xl-block">
                 <a class="tp-btn-theme" href="listing-ads.php"><span>Post Your Ad <i class="fa-sharp fa-regular fa-arrow-right-long"></i></span></a>
               </div>
               <div class="tp-header-bar d-xl-none">
                 <button class="tp-menu-bar"><i class="fa-sharp fa-regular fa-bars-staggered"></i></button>
               </div>
             </div>
           </div>
         </div>
       </div>
     </div>
   </header>

  <main>
    <section class="tp-profile-area z-index pb-120 pt-60">
      <div class="container">
        <div class="chat-layout">
          <div class="chat-list">
            <div class="chat-list-header">
              <h3>Conversations</h3>
            </div>
            <div class="chat-item active" id="admin-entry">
              <div class="chat-avatar">SA</div>
              <div class="chat-item-details">
                <div class="chat-item-name">System Admin</div>
                <div class="chat-item-preview">Official support</div>
              </div>
            </div>
          </div>
          <div class="chat-room">
            <div class="chat-head">
              <div class="chat-head-avatar">SA</div>
              <div>
                <div>System Admin</div>
                <div style="font-size: 12px; color: var(--text-light); margin-top: 2px;">Online</div>
              </div>
            </div>
            <div class="chat-body" id="chat-body">
              <div class="chat-empty-state" id="empty-state">
                <i class="fa-regular fa-comment-dots"></i>
                <h4>Start a conversation</h4>
                <p>Send a message to our support team</p>
              </div>
            </div>
            <div class="chat-input-container">
              <div class="chat-input">
                <input type="text" id="chat-text" placeholder="Type your message...">
                <button id="chat-send" type="button">
                  <i class="fa-regular fa-paper-plane"></i>
                  <span>Send</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </main>

  <footer>
    <div class="tp-footer-area z-index black-bg fix p-relative pt-115 pb-70" id="site-contact">
      <div class="tp-footer-big-text d-none d-md-block">
        <span>ReWear</span>
      </div>
      <div class="container">
        <div class="row">
          <div class="col-xl-6 col-lg-6 mb-50">
            <div class="tp-footer-widget">
              <div class="tp-form-box">
                <div class="tp-footer-title-box pb-50">
                  <span class="tp-section-subtitle-2 mb-10">support email</span>
                  <h4 class="tp-form-title"><a href="mailto:info@listbnb.com">info@listbnb.com</a></h4>
                </div>
                <form action="contact_submit.php" method="post" id="footer-contact-form">
                  <div class="row">
                    <div class="col-xl-6 col-lg-6 col-md-6 col-12">
                      <div class="tp-form-input-box">
                        <label>full name</label>
                        <input type="text" name="full_name" placeholder="Your name" required>
                      </div>
                    </div>
                    <div class="col-xl-6 col-lg-6 col-md-6 col-12">
                      <div class="tp-form-input-box">
                        <label>email address</label>
                        <input type="email" name="email" placeholder="Your email" required>
                      </div>
                    </div>
                    <div class="col-12">
                      <div class="tp-form-textarea-box">
                        <label>message</label>
                        <textarea name="message" placeholder="Your message" required></textarea>
                      </div>
                    </div>
                  </div>
                </form>
                <div class="tp-form-button">
                  <button class="tp-btn-black theme-bg" type="submit" form="footer-contact-form"><span>Submit <i class="fa-sharp fa-regular fa-arrow-right-long"></i></span></button>
                </div>
              </div>
            </div>
          </div>
          <div class="col-xl-6 col-lg-6 mb-50">
            <div class="tp-footer-widget">
              <div class="tp-footer-right">
                <h4 class="tp-form-title pb-30">Essential</h4>
                <div class="tp-footer-list pb-65">
                  <ul>
                    <li><a href="#">Company & Contact Info</a></li>
                    <li><a href="sitemap.html">Sitemap</a></li>
                    <li><a href="privacy.html">Privacy Policy</a></li>
                    <li><a href="faq.html">FAQ Page</a></li>
                    <li><a href="terms.html">Terms & Conditions</a></li>
                  </ul>
                </div>
                <div class="tp-footer-content tp-footer-content-border">
                  <p><i>ReWear</i> a Largest Classified Listing Marketplace offers perfect WordPress Ads classified Themes to build your own classified websites.</p>
                  <a href="contact.html"><i class="fal fa-arrow-right-long"></i> Get It Now</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="tp-copyright-area black-bg">
      <div class="container">
        <div class="tp-copyright-ptb">
          <div class="row align-items-center">
            <div class="col-xl-7 col-lg-6 col-md-6 col-sm-7">
              <div class="tp-copyright-left d-flex align-items-center justify-content-center justify-content-md-start">
                <div class="tp-copyright-text text-center text-md-start">
                  <p>ReWear</p>
                </div>
              </div>
            </div>
            <div class="col-xl-5 col-lg-6 col-md-6 col-sm-5">
              <div class="tp-copyright-right justify-content-center d-flex justify-content-sm-end align-items-center">
                <div class="tp-copyright-social">
                  <a href="#"><i class="fa-brands fa-facebook-f"></i></a>
                  <a href="#"><i class="fa-brands fa-twitter"></i></a>
                  <a href="#"><i class="fa-brands fa-youtube"></i></a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </footer>

  <script src="assets/js/vendor/jquery.js"></script>
  <script src="assets/js/bootstrap-bundle.js"></script>
  <script src="assets/js/swiper-bundle.js"></script>
  <script src="assets/js/slick.js"></script>
  <script src="assets/js/magnific-popup.js"></script>
  <script src="assets/js/nice-select.js"></script>
  <script src="assets/js/purecounter.js"></script>
  <script src="assets/js/countdown.js"></script>
  <script src="assets/js/wow.js"></script>
  <script src="assets/js/isotope-pkgd.js"></script>
  <script src="assets/js/imagesloaded-pkgd.js"></script>
  <script src="assets/js/ajax-form.js"></script>
  <script src="assets/js/main.js"></script>
  <script>
    (function(){
      var bodyEl = document.getElementById('chat-body');
      function fmtTime(s){ try{ var d = new Date(s); return d.toLocaleString(); }catch(e){ return s; } }
      function render(items) {
        if (!items || items.length === 0) {
          document.getElementById('empty-state').style.display = 'flex';
          bodyEl.innerHTML = '';
          return;
        }
        document.getElementById('empty-state').style.display = 'none';
        
        bodyEl.innerHTML = items.map(function(it) {
          var me = it.sender === 'user';
          return `
            <div class="msg ${me ? 'me' : 'other'}">
              <div>${escapeHtml(it.content)}</div>
              <div class="msg-time">${fmtTime(it.created_at)}</div>
            </div>
          `;
        }).join('');
        
        // Auto-scroll to bottom
        bodyEl.scrollTop = bodyEl.scrollHeight;
      }
      function escapeHtml(str){ return (str||'').replace(/[&<>"']/g,function(ch){return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#39;'})[ch];}); }
      function load(){ fetch('chat.php?action=list').then(function(r){return r.json()}).then(function(d){ render(d.items||[]); }); }
      function send() {
        var t = document.getElementById('chat-text');
        var v = (t.value || '').trim();
        if (!v) return;
        
        // Disable input and button while sending
        t.disabled = true;
        document.getElementById('chat-send').disabled = true;
        
        fetch('chat.php?action=send', {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: 'content=' + encodeURIComponent(v)
        })
        .then(function(r) { return r.json(); })
        .then(function(d) {
          if (d && d.ok) {
            t.value = '';
            load();
          }
        })
        .finally(function() {
          // Re-enable input and button
          t.disabled = false;
          document.getElementById('chat-send').disabled = false;
          t.focus();
        });
      }
      // Send message on button click
      document.getElementById('chat-send').addEventListener('click', send);
      
      // Send message on Enter key
      document.getElementById('chat-text').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
          send();
        }
      });
      
      // Load chat history when clicking on admin entry
      document.getElementById('admin-entry').addEventListener('click', load);
      
      // Initial load
      load();
      
      // Auto-refresh messages every 3 seconds
      setInterval(load, 3000);
      
      // Focus the input field on page load
      document.getElementById('chat-text').focus();
    })();
  </script>
</body>
</html>
