/**
 * Aravali Homecare - Smart AI Chatbot Widget
 * Powered by Gemini 3.6 Flash via Express Server (/api/chat)
 */

interface ChatMessage {
  role: 'user' | 'model';
  text: string;
  time?: string;
}

class AravaliChatbot {
  private history: ChatMessage[] = [];
  private isOpen: boolean = false;
  private isThinking: boolean = false;

  // DOM Elements
  private container!: HTMLElement;
  private chatWindow!: HTMLElement;
  private messagesBox!: HTMLElement;
  private inputField!: HTMLInputElement;
  private sendBtn!: HTMLButtonElement;
  private toggleBtn!: HTMLElement;
  private badgeEl!: HTMLElement;

  constructor() {
    this.loadHistory();
    this.injectStyles();
    this.createWidgetDOM();
    this.bindEvents();
    this.renderMessages();
  }

  private loadHistory() {
    try {
      const saved = localStorage.getItem('aravali_ai_chat_history');
      if (saved) {
        this.history = JSON.parse(saved);
      }
    } catch (e) {
      console.warn('Failed to load chat history', e);
      this.history = [];
    }

    if (this.history.length === 0) {
      this.history.push({
        role: 'model',
        text: `👋 **Namaste! Welcome to Aravali Homecare Jaipur.**\n\nI am **Aravali AI**, your smart assistant. I can answer **every question** about our services, calculate cost estimates, explain our 5-year warranty, or help you with color combinations and home improvement ideas!\n\nHow can I help you today?`,
        time: this.getFormattedTime(),
      });
    }
  }

  private saveHistory() {
    try {
      localStorage.setItem('aravali_ai_chat_history', JSON.stringify(this.history));
    } catch (e) {
      console.warn('Failed to save chat history', e);
    }
  }

  private getFormattedTime(): string {
    const now = new Date();
    return now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }

  private injectStyles() {
    if (document.getElementById('aravali-chat-styles')) return;

    const style = document.createElement('style');
    style.id = 'aravali-chat-styles';
    style.textContent = `
      /* ARAVALI AI CHATBOT STYLES */
      #aravali-chat-widget {
        position: fixed;
        bottom: 24px;
        right: 24px;
        z-index: 99999;
        font-family: 'Poppins', system-ui, -apple-system, sans-serif;
      }

      /* Trigger Button */
      .aravali-chat-trigger {
        position: relative;
        width: 62px;
        height: 62px;
        border-radius: 50%;
        background: linear-gradient(135deg, #F26522 0%, #ff7a3c 100%);
        color: #ffffff;
        border: none;
        box-shadow: 0 8px 30px rgba(242, 101, 34, 0.45);
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 26px;
        transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), box-shadow 0.3s;
      }
      .aravali-chat-trigger:hover {
        transform: scale(1.08);
        box-shadow: 0 12px 35px rgba(242, 101, 34, 0.6);
      }
      .aravali-chat-trigger .badge-callout {
        position: absolute;
        top: -10px;
        right: -8px;
        background: #10b981;
        color: #ffffff;
        font-size: 10px;
        font-weight: 800;
        padding: 3px 8px;
        border-radius: 20px;
        border: 2px solid #ffffff;
        letter-spacing: 0.5px;
        box-shadow: 0 4px 10px rgba(0,0,0,0.15);
        animation: floatBadge 2.5s ease-in-out infinite;
      }
      @keyframes floatBadge {
        0%, 100% { transform: translateY(0); }
        50% { transform: translateY(-3px); }
      }

      .aravali-chat-trigger .unread-dot {
        position: absolute;
        top: 2px;
        left: 2px;
        width: 14px;
        height: 14px;
        background: #ef4444;
        border: 2px solid #ffffff;
        border-radius: 50%;
      }

      /* Chat Window Modal */
      .aravali-chat-window {
        position: absolute;
        bottom: 76px;
        right: 0;
        width: 380px;
        max-width: 92vw;
        height: 570px;
        max-height: 82vh;
        background: #ffffff;
        border-radius: 24px;
        box-shadow: 0 20px 60px rgba(15, 23, 42, 0.22), 0 0 0 1px rgba(0,0,0,0.06);
        display: flex;
        flex-direction: column;
        overflow: hidden;
        opacity: 0;
        visibility: hidden;
        transform: translateY(20px) scale(0.95);
        transition: all 0.35s cubic-bezier(0.16, 1, 0.3, 1);
        transform-origin: bottom right;
      }
      .aravali-chat-window.open {
        opacity: 1;
        visibility: visible;
        transform: translateY(0) scale(1);
      }

      /* Header */
      .aravali-chat-header {
        background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
        color: #ffffff;
        padding: 16px 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 2px solid rgba(242, 101, 34, 0.3);
      }
      .aravali-chat-header-info {
        display: flex;
        align-items: center;
        gap: 12px;
      }
      .aravali-bot-avatar {
        width: 42px;
        height: 42px;
        border-radius: 50%;
        background: linear-gradient(135deg, #F26522, #ff7a3c);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        color: #ffffff;
        position: relative;
        box-shadow: 0 4px 12px rgba(242, 101, 34, 0.4);
      }
      .aravali-bot-avatar::after {
        content: '';
        position: absolute;
        bottom: 0;
        right: 0;
        width: 11px;
        height: 11px;
        background: #10b981;
        border: 2px solid #0f172a;
        border-radius: 50%;
      }
      .aravali-chat-header-title h4 {
        font-size: 15px;
        font-weight: 700;
        margin: 0;
        color: #ffffff;
        display: flex;
        align-items: center;
        gap: 6px;
      }
      .aravali-chat-header-title span {
        font-size: 11px;
        color: rgba(255, 255, 255, 0.7);
        display: block;
      }

      .aravali-chat-actions {
        display: flex;
        align-items: center;
        gap: 8px;
      }
      .aravali-chat-action-btn {
        background: rgba(255, 255, 255, 0.1);
        border: none;
        color: rgba(255, 255, 255, 0.85);
        width: 32px;
        height: 32px;
        border-radius: 50%;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 13px;
        transition: 0.2s;
      }
      .aravali-chat-action-btn:hover {
        background: rgba(242, 101, 34, 0.8);
        color: #ffffff;
      }

      /* Quick Starter Chips */
      .aravali-chat-chips {
        padding: 10px 14px;
        background: #f8fafc;
        border-bottom: 1px solid #e2e8f0;
        display: flex;
        gap: 8px;
        overflow-x: auto;
        white-space: nowrap;
        scrollbar-width: none;
      }
      .aravali-chat-chips::-webkit-scrollbar { display: none; }
      .aravali-chip {
        background: #ffffff;
        color: #334155;
        border: 1px solid #cbd5e1;
        padding: 6px 14px;
        border-radius: 20px;
        font-size: 11.5px;
        font-weight: 600;
        cursor: pointer;
        transition: 0.2s;
        display: inline-flex;
        align-items: center;
        gap: 5px;
        flex-shrink: 0;
      }
      .aravali-chip:hover {
        background: #fff3eb;
        color: #F26522;
        border-color: #F26522;
      }

      /* Messages Box */
      .aravali-chat-messages {
        flex: 1;
        padding: 16px;
        overflow-y: auto;
        display: flex;
        flex-direction: column;
        gap: 14px;
        background: #f8fafc;
      }

      .aravali-msg {
        display: flex;
        flex-direction: column;
        max-width: 85%;
        animation: msgIn 0.3s ease-out forwards;
      }
      @keyframes msgIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
      }

      .aravali-msg.user {
        align-self: flex-end;
      }
      .aravali-msg.model {
        align-self: flex-start;
      }

      .aravali-msg-bubble {
        padding: 12px 16px;
        border-radius: 18px;
        font-size: 13.5px;
        line-height: 1.55;
        word-wrap: break-word;
      }

      .aravali-msg.user .aravali-msg-bubble {
        background: linear-gradient(135deg, #F26522, #ff7a3c);
        color: #ffffff;
        border-bottom-right-radius: 4px;
        box-shadow: 0 4px 12px rgba(242, 101, 34, 0.25);
      }

      .aravali-msg.model .aravali-msg-bubble {
        background: #ffffff;
        color: #1e293b;
        border: 1px solid #e2e8f0;
        border-left: 3.5px solid #F26522;
        border-bottom-left-radius: 4px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.03);
      }

      .aravali-msg-bubble p {
        margin: 0 0 8px 0;
      }
      .aravali-msg-bubble p:last-child {
        margin-bottom: 0;
      }
      .aravali-msg-bubble ul {
        margin: 6px 0 6px 18px;
        padding: 0;
      }
      .aravali-msg-bubble li {
        margin-bottom: 4px;
      }
      .aravali-msg-time {
        font-size: 10px;
        color: #94a3b8;
        margin-top: 4px;
        align-self: flex-end;
      }
      .aravali-msg.model .aravali-msg-time {
        align-self: flex-start;
      }

      /* Quick CTA Buttons inside Chat */
      .aravali-chat-cta-group {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-top: 10px;
      }
      .aravali-chat-cta-btn {
        background: linear-gradient(135deg, #0f172a, #1e293b);
        color: #ffffff !important;
        text-decoration: none;
        padding: 7px 14px;
        border-radius: 30px;
        font-size: 11.5px;
        font-weight: 700;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        transition: 0.2s;
        border: 1px solid rgba(255,255,255,0.1);
      }
      .aravali-chat-cta-btn:hover {
        background: #F26522;
        transform: translateY(-1px);
      }

      /* Typing Indicator */
      .aravali-typing {
        display: flex;
        align-items: center;
        gap: 5px;
        padding: 12px 18px;
        background: #ffffff;
        border-radius: 18px;
        border-bottom-left-radius: 4px;
        width: fit-content;
        border: 1px solid #e2e8f0;
        border-left: 3.5px solid #F26522;
      }
      .aravali-typing-dot {
        width: 7px;
        height: 7px;
        background: #F26522;
        border-radius: 50%;
        animation: typingBounce 1.4s infinite ease-in-out both;
      }
      .aravali-typing-dot:nth-child(1) { animation-delay: -0.32s; }
      .aravali-typing-dot:nth-child(2) { animation-delay: -0.16s; }
      @keyframes typingBounce {
        0%, 80%, 100% { transform: scale(0); }
        40% { transform: scale(1); }
      }

      /* Input Footer */
      .aravali-chat-footer {
        padding: 12px 16px;
        background: #ffffff;
        border-top: 1px solid #e2e8f0;
        display: flex;
        align-items: center;
        gap: 10px;
      }
      .aravali-chat-input-wrap {
        flex: 1;
        position: relative;
      }
      .aravali-chat-input {
        width: 100%;
        padding: 12px 16px;
        border: 1.5px solid #cbd5e1;
        border-radius: 25px;
        font-size: 13.5px;
        font-family: inherit;
        outline: none;
        transition: 0.2s;
        background: #f8fafc;
      }
      .aravali-chat-input:focus {
        border-color: #F26522;
        background: #ffffff;
        box-shadow: 0 0 0 3px rgba(242, 101, 34, 0.15);
      }
      .aravali-chat-send {
        width: 44px;
        height: 44px;
        border-radius: 50%;
        background: linear-gradient(135deg, #F26522, #ff7a3c);
        color: #ffffff;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        transition: 0.2s;
        flex-shrink: 0;
        box-shadow: 0 4px 12px rgba(242, 101, 34, 0.3);
      }
      .aravali-chat-send:hover {
        transform: scale(1.05);
        box-shadow: 0 6px 16px rgba(242, 101, 34, 0.45);
      }
      .aravali-chat-send:disabled {
        opacity: 0.5;
        cursor: not-allowed;
        transform: none;
      }

      /* Mobile responsiveness */
      @media(max-width: 480px) {
        #aravali-chat-widget {
          bottom: 16px;
          right: 16px;
        }
        .aravali-chat-window {
          width: calc(100vw - 32px);
          height: 80vh;
          bottom: 70px;
        }
      }
    `;
    document.head.appendChild(style);
  }

  private createWidgetDOM() {
    this.container = document.createElement('div');
    this.container.id = 'aravali-chat-widget';

    this.container.innerHTML = `
      <!-- Trigger Button -->
      <button class="aravali-chat-trigger" id="aravaliChatTrigger" title="Ask Aravali AI">
        <i class="fa-solid fa-robot" id="aravaliTriggerIcon"></i>
        <div class="badge-callout">✦ ASK AI</div>
        <div class="unread-dot" id="aravaliUnreadDot"></div>
      </button>

      <!-- Chat Modal Window -->
      <div class="aravali-chat-window" id="aravaliChatWindow">
        <!-- Header -->
        <div class="aravali-chat-header">
          <div class="aravali-chat-header-info">
            <div class="aravali-bot-avatar">
              <i class="fa-solid fa-wand-magic-sparkles"></i>
            </div>
            <div class="aravali-chat-header-title">
              <h4>Aravali AI <i class="fa-solid fa-circle-check" style="color:#10b981;font-size:12px;"></i></h4>
              <span>Smart Concierge • Online 24/7</span>
            </div>
          </div>
          <div class="aravali-chat-actions">
            <button class="aravali-chat-action-btn" id="aravaliResetBtn" title="Reset Conversation">
              <i class="fa-solid fa-rotate-right"></i>
            </button>
            <button class="aravali-chat-action-btn" id="aravaliCloseBtn" title="Close Chat">
              <i class="fa-solid fa-xmark"></i>
            </button>
          </div>
        </div>

        <!-- Quick Starter Chips -->
        <div class="aravali-chat-chips">
          <button class="aravali-chip" data-query="How much will interior painting cost for my home?"><i class="fa-solid fa-calculator"></i> Painting Cost</button>
          <button class="aravali-chip" data-query="Explain your 5-Year Warranty details"><i class="fa-solid fa-shield-halved"></i> 5-Yr Guarantee</button>
          <button class="aravali-chip" data-query="How do I book a free site measurement visit?"><i class="fa-solid fa-calendar-check"></i> Book Free Visit</button>
          <button class="aravali-chip" data-query="What are the best trending color combinations for living room?"><i class="fa-solid fa-palette"></i> Color Ideas</button>
          <button class="aravali-chip" data-query="Do you provide waterproofing for terrace dampness?"><i class="fa-solid fa-droplet-slash"></i> Waterproofing</button>
        </div>

        <!-- Messages Box -->
        <div class="aravali-chat-messages" id="aravaliChatMessages"></div>

        <!-- Footer Input -->
        <div class="aravali-chat-footer">
          <div class="aravali-chat-input-wrap">
            <input type="text" class="aravali-chat-input" id="aravaliChatInput" placeholder="Ask Aravali AI anything..." autocomplete="off">
          </div>
          <button class="aravali-chat-send" id="aravaliChatSend" title="Send Message">
            <i class="fa-solid fa-paper-plane"></i>
          </button>
        </div>
      </div>
    `;

    document.body.appendChild(this.container);

    this.toggleBtn = document.getElementById('aravaliChatTrigger') as HTMLElement;
    this.chatWindow = document.getElementById('aravaliChatWindow') as HTMLElement;
    this.messagesBox = document.getElementById('aravaliChatMessages') as HTMLElement;
    this.inputField = document.getElementById('aravaliChatInput') as HTMLInputElement;
    this.sendBtn = document.getElementById('aravaliChatSend') as HTMLButtonElement;
    this.badgeEl = document.getElementById('aravaliUnreadDot') as HTMLElement;
  }

  private bindEvents() {
    this.toggleBtn.addEventListener('click', () => this.toggleChat());
    document.getElementById('aravaliCloseBtn')?.addEventListener('click', () => this.toggleChat(false));
    document.getElementById('aravaliResetBtn')?.addEventListener('click', () => this.resetChat());

    this.sendBtn.addEventListener('click', () => this.handleUserSend());
    this.inputField.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') this.handleUserSend();
    });

    // Delegate Quick Chips click
    const chips = this.container.querySelectorAll('.aravali-chip');
    chips.forEach((chip) => {
      chip.addEventListener('click', (e) => {
        const query = (e.currentTarget as HTMLElement).getAttribute('data-query');
        if (query) {
          this.inputField.value = query;
          this.handleUserSend();
        }
      });
    });
  }

  private toggleChat(forceState?: boolean) {
    this.isOpen = forceState !== undefined ? forceState : !this.isOpen;
    const triggerIcon = document.getElementById('aravaliTriggerIcon');

    if (this.isOpen) {
      this.chatWindow.classList.add('open');
      if (triggerIcon) triggerIcon.className = 'fa-solid fa-xmark';
      if (this.badgeEl) this.badgeEl.style.display = 'none';
      setTimeout(() => this.inputField.focus(), 300);
      this.scrollToBottom();
    } else {
      this.chatWindow.classList.remove('open');
      if (triggerIcon) triggerIcon.className = 'fa-solid fa-robot';
    }
  }

  private resetChat() {
    localStorage.removeItem('aravali_ai_chat_history');
    this.history = [
      {
        role: 'model',
        text: `👋 **Chat history reset.**\n\nI am **Aravali AI**, ready for your new questions! How can I assist you with interior design, painting, wood polish, or waterproofing today?`,
        time: this.getFormattedTime(),
      },
    ];
    this.saveHistory();
    this.renderMessages();
    this.scrollToBottom();
    if (this.inputField) {
      this.inputField.value = '';
      this.inputField.focus();
    }
  }

  private async handleUserSend() {
    const text = this.inputField.value.trim();
    if (!text || this.isThinking) return;

    // Add user message
    const userMsg: ChatMessage = {
      role: 'user',
      text: text,
      time: this.getFormattedTime(),
    };

    this.history.push(userMsg);
    this.inputField.value = '';
    this.renderMessages();
    this.saveHistory();

    // Show typing state
    this.showTyping(true);

    try {
      // Call backend Express route
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message: text,
          history: this.history,
        }),
      });

      const data = await response.json();
      this.showTyping(false);

      if (response.ok && data.reply) {
        this.history.push({
          role: 'model',
          text: data.reply,
          time: this.getFormattedTime(),
        });
      } else {
        // Fallback to offline engine
        const offlineReply = this.generateOfflineReply(text);
        this.history.push({
          role: 'model',
          text: offlineReply,
          time: this.getFormattedTime(),
        });
      }
    } catch (err) {
      console.warn('Backend Chat API unreachable, using offline AI engine:', err);
      this.showTyping(false);
      // Seamless offline fallback
      const offlineReply = this.generateOfflineReply(text);
      this.history.push({
        role: 'model',
        text: offlineReply,
        time: this.getFormattedTime(),
      });
    }

    this.renderMessages();
    this.saveHistory();
  }

  private generateOfflineReply(query: string): string {
    const q = query.toLowerCase().trim();

    // Vastu Shastra
    if (q.includes('vastu') || q.includes('direction') || q.includes('north') || q.includes('south') || q.includes('east') || q.includes('west')) {
      return `🧭 **Vastu Shastra Colors & Room Directions Guide:**\n\n` +
        `• **Master Bedroom (South-West):** Earthy tones, Warm Taupe, Almond, or Muted Brown (enhances stability & grounding).\n` +
        `• **Living Room (North-East / North):** Light Green, Pure White, Soft Sky Blue, or Beige (attracts prosperity & light).\n` +
        `• **Kitchen (South-East - Agni Corner):** Warm Coral, Terracotta, Peach, or Warm Saffron accents.\n` +
        `• **Pooja / Meditation Room (North-East):** Light Yellow, Cream, or Pearl White (represents purity & calm).\n` +
        `• **Children / Study Room (West / North-West):** Pastel Green, Light Blue, or Lavender (improves concentration).\n\n` +
        `Our architectural team can align color palettes and layouts with Vastu principles during your site visit!`;
    }

    // Material Comparison & Brands
    if (q.includes('asian paint') || q.includes('berger') || q.includes('dulux') || q.includes('royale') || q.includes('tractor') || q.includes('apex') || q.includes('brand') || q.includes('material')) {
      return `🎨 **Paint Materials & Finishes Comparison:**\n\n` +
        `1. **Asian Paints Royale Luxury Emulsion (₹23-₹28/sq.ft):**\n` +
        `   • 100% Washable, anti-fungal, Teflon surface protection, silky sheen.\n` +
        `2. **Royale Glitz / Aspira (₹30-₹36/sq.ft):**\n` +
        `   • Ultra-luxurious velvet Teflon finish with high crack-bridging ability.\n` +
        `3. **Tractor Emulsion / Apcolite (₹16-₹20/sq.ft):**\n` +
        `   • Smooth matt economy finish, 2x coverage of traditional distemper.\n` +
        `4. **Apex Ultima Weatherproof Exterior (₹22-₹35/sq.ft):**\n` +
        `   • Advanced anti-algae silicone formula with 7-year performance warranty.\n` +
        `5. **Birla Opus & JSW Paints:** Available with direct manufacturer warranty.\n\n` +
        `We supply 100% genuine factory-sealed buckets verified in front of you!`;
    }

    // Paint Area / Quantity Calculation Formula
    if (q.includes('calculate') || q.includes('formula') || q.includes('quantity') || q.includes('how many liter') || q.includes('how much paint') || q.includes('litre')) {
      return `📐 **Paint Area & Quantity Calculation Guide:**\n\n` +
        `• **Room Carpet to Wall Area Formula:** Carpet Area (sq.ft) × 3.5 = Total Paintable Wall + Ceiling Area (sq.ft).\n` +
        `  *(e.g., A 100 sq.ft room has approx ~350 sq.ft of paintable surface area)*.\n\n` +
        `• **Paint Consumption (2 Coats):**\n` +
        `  - Emulsion Paint: 1 Litre covers ~55 to 65 sq.ft (for 2 coats).\n` +
        `  - Primer: 1 Litre covers ~100 to 120 sq.ft.\n` +
        `  - Wall Putty: 1 Kg covers ~10 to 12 sq.ft (for 2 coats of 1.5mm).\n\n` +
        `Our free site inspection uses digital laser meters for 99.9% exact measurement!`;
    }

    // Modular Kitchen & Interior Work
    if (q.includes('kitchen') || q.includes('wardrobe') || q.includes('interior') || q.includes('cabinet') || q.includes('plywood') || q.includes('laminate') || q.includes('acrylic') || q.includes('hafele') || q.includes('hettich')) {
      return `✨ **Modular Interiors & Kitchen Solutions:**\n\n` +
        `• **Carcass & Core:** BWP Marine Grade Plywood (IS 710) with boiling waterproof guarantee.\n` +
        `• **Shutters & Finishes:** High-Gloss Acrylic, Anti-Fingerprint Matte Laminate, or PU Lacquer.\n` +
        `• **Fittings & Hardware:** Soft-close Blum, Hafele, and Hettich hinges & tandem drawers with lifetime warranty.\n` +
        `• **Countertops:** Quartz, Corian, or Granites tailored to Jaipur kitchen ergonomics.\n\n` +
        `Book a free 3D design consultation on **book.html** to view customized 3D renders!`;
    }

    // Wood Polish & Textures
    if (q.includes('wood') || q.includes('polish') || q.includes('pu') || q.includes('melamine') || q.includes('duco') || q.includes('texture') || q.includes('stucco')) {
      return `🪵 **Wood Polish & Wall Texture Specializations:**\n\n` +
        `• **Italian / Indian PU Finish (₹180–₹320/sq.ft):** Crystal-clear UV-resistant polyurethane for teak, oak, and veneers.\n` +
        `• **Polyester High-Gloss (₹500/sq.ft):** Piano glass finish with 100% mirror reflection.\n` +
        `• **Melamine Polish (₹140/sq.ft):** Semi-gloss or matte heat-resistant coating.\n` +
        `• **Italian Stucco & Concrete Wall Texture (₹65–₹150/sq.ft):** Seamless Venetian marble finish for feature walls.`;
    }

    // Weather / Monsoon & Jaipur Specific
    if (q.includes('jaipur') || q.includes('weather') || q.includes('monsoon') || q.includes('summer') || q.includes('winter') || q.includes('rajasthan')) {
      return `☀️ **Jaipur Weather & Climate Care Advice:**\n\n` +
        `• **High Summer Heat (May–July):** We apply elastomeric heat-reflective roof coatings (Cool Roof) reducing internal temperature by up to 5°C.\n` +
        `• **Monsoon Dampness (July–Sept):** Pre-monsoon waterproofing with fiber-reinforced chemical membranes prevents roof seepage and efflorescence (shora).\n` +
        `• **Best Time for Painting:** October through April offers ideal humidity and fast curing time in Jaipur!`;
    }

    // Cost / Pricing / Estimator / Discounts
    if (q.includes('cost') || q.includes('price') || q.includes('rate') || q.includes('estimate') || q.includes('calculator') || q.includes('how much') || q.includes('rupee') || q.includes('discount') || q.includes('coupon') || q.includes('offer')) {
      return `📊 **Aravali Homecare Standard Pricing & Discount Guide (2026):**\n\n` +
        `• **Economy Painting:** ₹16–₹18 / sq.ft (Durable, smooth finish)\n` +
        `• **Premium Painting:** ₹23–₹25 / sq.ft (100% Washable, Asian Paints Royale)\n` +
        `• **Luxury PU Finish:** ₹27–₹32 / sq.ft (Ultra high-gloss velvet touch)\n` +
        `• **Waterproofing:** Roof ₹35–₹55 / sq.ft | Tank & Swimming Pool ₹100 / sq.ft\n` +
        `• **Wood Polish:** Enamel ₹30 / sq.ft | Melamine ₹140 / sq.ft | Water-based ₹320 / sq.ft | Polyester High Gloss ₹500 / sq.ft\n` +
        `• **Modular Kitchens:** ₹1,400–₹1,800 / sq.ft\n\n` +
        `🎁 **Active 2026 Special Discounts:**\n` +
        `• **10% Festive Discount:** Active on Holi (HOLI10), Eid (EID10), Navratri (NAVRATRI10), Dussehra (DUSSEHRA10), Diwali (DIWALI10), Christmas (XMAS10).\n` +
        `• **10% First Login Offer:** Code **ARAVALI10** unlocked upon signing up or logging in!\n\n` +
        `💡 **Formula:** Total = Total Area (sq.ft) × Selected Rate (₹/sq.ft) + 18% GST.\n\n` +
        `Try our interactive **Cost Estimator** tool (estimator.html) to calculate your exact project quote instantly!`;
    }

    // Warranty / Guarantee
    if (q.includes('warranty') || q.includes('guarantee') || q.includes('quality') || q.includes('durable')) {
      return `🛡️ **Our 5-Year Service Warranty Guarantee:**\n\n` +
        `Every Aravali Homecare project comes with an official written **5-Year Warranty** card covering:\n` +
        `1. Protection against paint peeling, flaking, or fading\n` +
        `2. Zero dampness & seepage guarantee on waterproofing\n` +
        `3. Free touch-up & inspection support within 24 hours of request\n` +
        `4. Authentic Asian Paints, Berger & Nerolac original materials used\n\n` +
        `Would you like to book a **Free Site Inspection** to check your wall condition?`;
    }

    // Free Visit / Booking / Measurement
    if (q.includes('book') || q.includes('visit') || q.includes('appointment') || q.includes('free') || q.includes('measurement') || q.includes('inspection')) {
      return `📅 **Book a 100% FREE Site Measurement Visit:**\n\n` +
        `Our senior paint expert will visit your doorstep anywhere in Jaipur within 24 hours:\n` +
        `• Precision Laser Distance Measurement\n` +
        `• Wall Moisture / Dampness Meter Testing\n` +
        `• On-site Shade Card Selection & Color Consultation\n` +
        `• Exact Itemized Written Quote (Zero hidden charges)\n\n` +
        `📍 **Service Coverage:** Vaishali Nagar, Malviya Nagar, Mansarovar, C-Scheme, Raja Park, Jagatpura, Tonk Road, and all areas across Jaipur!`;
    }

    // Color Ideas / Combinations
    if (q.includes('color') || q.includes('colour') || q.includes('combination') || q.includes('shade') || q.includes('living room') || q.includes('bedroom')) {
      return `🎨 **Trending Color Combinations for Indian Homes (2026):**\n\n` +
        `1. **Modern Living Room:** Warm Terracotta + Muted Cream Accent\n` +
        `2. **Master Bedroom:** Royal Indigo Navy + Soft Ivory\n` +
        `3. **Serene Atmosphere:** Sage Green + Natural Beige\n` +
        `4. **Contemporary Luxury:** Warm Greige + Metallic Gold Texture\n\n` +
        `We provide **3D Visualizer preview** and physical shade cards during our free site measurement visit!`;
    }

    // Waterproofing / Seepage
    if (q.includes('waterproof') || q.includes('seepage') || q.includes('damp') || q.includes('leak') || q.includes('terrace') || q.includes('roof')) {
      return `💧 **Advanced Waterproofing & Anti-Damp Solutions:**\n\n` +
        `• **Terrace Roofs:** 3-Coat Elastomeric Chemical Membrane + Glass Fiber Mesh\n` +
        `• **Internal Wall Dampness:** PU Injection Grouting & Salt-Resistant Barrier\n` +
        `• **Bathroom Leakage:** Tile Joint Epoxy Injection (No breaking required!)\n\n` +
        `All waterproofing work is backed by our official **10-Year Anti-Leakage Guarantee**.`;
    }

    // Contact / Phone / Email / Founder
    if (q.includes('contact') || q.includes('phone') || q.includes('number') || q.includes('call') || q.includes('mohit') || q.includes('email') || q.includes('address') || q.includes('owner')) {
      return `📞 **Aravali Homecare Contact Details:**\n\n` +
        `• **Owner & Founder:** Mohit Niganiya (Direct: mohit@aravalihomecare.com)\n` +
        `• **Official Company Email:** info@aravalihomecare.com\n` +
        `• **Phone / WhatsApp:** +91 92511 11069\n` +
        `• **Office Address:** Main Ajmer Road, Near 200 Ft Bypass, Jaipur, Rajasthan\n` +
        `• **Working Hours:** Monday – Sunday (9:00 AM – 8:00 PM)\n\n` +
        `Feel free to call or WhatsApp us at +91 92511 11069 anytime!`;
    }

    // Admin / Portal
    if (q.includes('admin') || q.includes('login') || q.includes('portal') || q.includes('profile')) {
      return `🔐 **Aravali Homecare Portals:**\n\n` +
        `• **Client Dashboard & Active Projects:** Access your personal profile at \`profile.html\` to track ongoing projects, view saved estimates, and manage contact details.\n` +
        `• **Admin Portal:** Accessible at \`admin.html\` exclusively for authorized administrative and management staff.\n\n` +
        `You can log in or create your client account on \`login.html\`.`;
    }

    // Greetings
    if (q.includes('hi') || q.includes('hello') || q.includes('namaste') || q.includes('hey') || q.includes('good morning') || q.includes('good evening') || q.includes('how are you')) {
      return `👋 **Namaste! Welcome to Aravali Homecare Jaipur.**\n\n` +
        `I am your intelligent assistant. I can help you with:\n` +
        `• Instant renovation & painting cost estimates\n` +
        `• Booking a 100% Free laser site measurement\n` +
        `• Exploring trending colors, Vastu tips & textures\n` +
        `• Understanding our 5-Year Warranty & waterproofing methods\n` +
        `• Any general questions or homecare guidance!`;
    }

    // General query response
    return `Hello! Regarding **"${query}"**:\n\n` +
      `Aravali Homecare is Jaipur's leading luxury interior design, premium painting, and architectural renovation specialist.\n\n` +
      `• **Key Highlights:** Free site inspection, itemized quotes, dust-free sanding, genuine Asian Paints / Greenply / Hafele materials, and a written **5-Year Warranty**.\n` +
      `• **WhatsApp / Direct Call:** +91 9251111069\n` +
      `• **Instant Calculation:** Check our **Smart Estimator** (estimator.html) or book an on-site visit (book.html).\n\n` +
      `Is there anything specific you would like to know about our finishes, timelines, or pricing?`;
  }

  private showTyping(show: boolean) {
    this.isThinking = show;
    this.sendBtn.disabled = show;

    let typingEl = document.getElementById('aravaliTypingIndicator');
    if (show) {
      if (!typingEl) {
        typingEl = document.createElement('div');
        typingEl.id = 'aravaliTypingIndicator';
        typingEl.className = 'aravali-typing';
        typingEl.innerHTML = `
          <div class="aravali-typing-dot"></div>
          <div class="aravali-typing-dot"></div>
          <div class="aravali-typing-dot"></div>
          <span style="font-size:11px;color:#64748b;margin-left:6px;font-weight:600;">Aravali AI is thinking...</span>
        `;
        this.messagesBox.appendChild(typingEl);
      }
      this.scrollToBottom();
    } else {
      if (typingEl) typingEl.remove();
    }
  }

  private formatMarkdown(text: string): string {
    // Escape HTML tags for security
    let escaped = text
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;');

    // Bold **text**
    escaped = escaped.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');

    // Italic *text*
    escaped = escaped.replace(/\*(.*?)\*/g, '<em>$1</em>');

    // Bullet points (- or *)
    const lines = escaped.split('\n');
    let inList = false;
    let formattedLines: string[] = [];

    lines.forEach((line) => {
      const trimmed = line.trim();
      if (trimmed.startsWith('- ') || trimmed.startsWith('* ')) {
        if (!inList) {
          formattedLines.push('<ul>');
          inList = true;
        }
        formattedLines.push(`<li>${trimmed.substring(2)}</li>`);
      } else {
        if (inList) {
          formattedLines.push('</ul>');
          inList = false;
        }
        if (trimmed.length > 0) {
          formattedLines.push(`<p>${trimmed}</p>`);
        }
      }
    });
    if (inList) formattedLines.push('</ul>');

    let result = formattedLines.join('');

    // Append quick CTA action buttons if relevant keywords present in bot output
    if (text.includes('Estimator') || text.includes('estimate') || text.includes('cost')) {
      if (!result.includes('aravali-chat-cta-group')) {
        result += `
          <div class="aravali-chat-cta-group">
            <a href="estimator.html" class="aravali-chat-cta-btn"><i class="fa-solid fa-calculator"></i> Launch Smart Estimator</a>
            <a href="book.html" class="aravali-chat-cta-btn"><i class="fa-solid fa-calendar-check"></i> Book Free Site Visit</a>
          </div>
        `;
      }
    } else if (text.includes('book') || text.includes('visit') || text.includes('appointment')) {
      if (!result.includes('aravali-chat-cta-group')) {
        result += `
          <div class="aravali-chat-cta-group">
            <a href="book.html" class="aravali-chat-cta-btn"><i class="fa-solid fa-calendar-check"></i> Book Free Site Measurement</a>
          </div>
        `;
      }
    }

    return result;
  }

  private renderMessages() {
    this.messagesBox.innerHTML = '';

    this.history.forEach((msg) => {
      const div = document.createElement('div');
      div.className = `aravali-msg ${msg.role}`;

      const bubble = document.createElement('div');
      bubble.className = 'aravali-msg-bubble';
      bubble.innerHTML = this.formatMarkdown(msg.text);

      const timeSpan = document.createElement('span');
      timeSpan.className = 'aravali-msg-time';
      timeSpan.textContent = msg.time || '';

      div.appendChild(bubble);
      div.appendChild(timeSpan);
      this.messagesBox.appendChild(div);
    });

    this.scrollToBottom();
  }

  private scrollToBottom() {
    setTimeout(() => {
      this.messagesBox.scrollTop = this.messagesBox.scrollHeight;
    }, 50);
  }
}

// Auto Initialize Chatbot on Page Load
if (typeof window !== 'undefined') {
  window.addEventListener('DOMContentLoaded', () => {
    new AravaliChatbot();
  });
}
