{% extends "base.html" %}

{% block title %}{{ page_title }}{% endblock %}

{% block extra_styles %}{% endblock %}

{% block content %}
<div class="local-wrap">

  <!-- Model Status Panel -->
  <div class="card mc-panel">
    <div class="card-header mc-panel-header">// LOCAL AI MODEL</div>
    <div class="model-status">
      <div class="model-status-row">
        <span class="model-status-label">STATUS</span>
        <span class="model-status-value offline" id="model-state">NOT LOADED</span>
      </div>
      <div class="model-status-row">
        <span class="model-status-label">BACKEND</span>
        <span class="model-status-value" id="model-backend">DETECTING...</span>
      </div>
      <div class="model-status-row">
        <span class="model-status-label">INFERENCE</span>
        <span class="model-status-value" id="inference-mode">--</span>
      </div>
    </div>

    <!-- Model selector -->
    <div class="model-select-wrap">
      <select class="model-select" id="model-select" aria-label="Select model"></select>
    </div>

    <!-- Progress bar -->
    <div class="progress-wrap" id="progress-wrap">
      <div class="progress-bar-outer">
        <div class="progress-bar-inner" id="progress-bar"></div>
      </div>
      <div class="progress-text" id="progress-text"></div>
    </div>

    <!-- Actions -->
    <div class="model-actions">
      <button class="model-btn primary" id="btn-load" onclick="loadModel()">LOAD MODEL</button>
      <button class="model-btn" id="btn-unload" onclick="unloadModel()" disabled>UNLOAD</button>
    </div>

    <!-- Stats -->
    <div class="model-stats" id="model-stats"></div>
  </div>

  <!-- Chat -->
  <div class="card mc-panel local-chat-wrap">
    <div class="card-header mc-panel-header">
      // TIMMY <span class="backend-badge local" id="chat-backend-badge" style="display:none">LOCAL</span>
    </div>
    <div class="local-chat-log" id="local-chat">
      <div class="local-msg system">
        <div class="meta">SYSTEM</div>
        <div class="bubble">
          Load a model above to chat with Timmy locally on your device.
          No server connection required.
          {% if browser_model_fallback %}
          Server fallback is enabled — if the local model fails, Timmy
          will try the server instead.
          {% endif %}
        </div>
      </div>
    </div>
    <form onsubmit="sendLocalMessage(event)" class="local-chat-input">
      <input type="text"
             id="local-message"
             placeholder="Message Timmy..."
             required
             autocomplete="off"
             autocapitalize="none"
             autocorrect="off"
             spellcheck="false"
             enterkeyhint="send" />
      <button type="submit" id="btn-send" disabled>SEND</button>
    </form>
  </div>

</div>

<script src="/static/local_llm.js"></script>
<script>
// ── State ──────────────────────────────────────────────────────────────────
let llm = null;
const serverFallback = {{ browser_model_fallback | tojson }};
const defaultModelId = {{ browser_model_id | tojson }};

// ── DOM refs ───────────────────────────────────────────────────────────────
const elState      = document.getElementById('model-state');
const elBackend    = document.getElementById('model-backend');
const elInference  = document.getElementById('inference-mode');
const elSelect     = document.getElementById('model-select');
const elProgress   = document.getElementById('progress-wrap');
const elBar        = document.getElementById('progress-bar');
const elProgressTx = document.getElementById('progress-text');
const elBtnLoad    = document.getElementById('btn-load');
const elBtnUnload  = document.getElementById('btn-unload');
const elBtnSend    = document.getElementById('btn-send');
const elChat       = document.getElementById('local-chat');
const elInput      = document.getElementById('local-message');
const elBadge      = document.getElementById('chat-backend-badge');
const elStats      = document.getElementById('model-stats');

// ── Populate model selector ────────────────────────────────────────────────
(function populateModels() {
  const catalogue = window.LOCAL_MODEL_CATALOGUE || [];
  catalogue.forEach(function(m) {
    const opt = document.createElement('option');
    opt.value = m.id;
    opt.textContent = m.label + ' (' + m.sizeHint + ')';
    if (m.id === defaultModelId) opt.selected = true;
    elSelect.appendChild(opt);
  });
})();

// ── Detect capabilities ────────────────────────────────────────────────────
(function detectCaps() {
  const supported = LocalLLM.isSupported();
  const hasGPU = typeof navigator !== 'undefined' && 'gpu' in navigator;
  elBackend.textContent = hasGPU ? 'WebGPU' : supported ? 'WASM' : 'UNSUPPORTED';
  if (!supported) {
    elBackend.classList.add('error');
    elBtnLoad.disabled = true;
    addSystemMessage('Your browser does not support WebGPU or WebAssembly. Update to iOS 26+ / Safari 26+ for local AI.');
  }
})();

// ── Load model ─────────────────────────────────────────────────────────────
async function loadModel() {
  if (llm && llm.ready) {
    await unloadModel();
  }

  const modelId = elSelect.value;
  elBtnLoad.disabled = true;
  elBtnUnload.disabled = true;
  elBtnSend.disabled = true;
  elProgress.classList.add('active');
  setState('loading', 'DOWNLOADING...');

  llm = new LocalLLM({
    modelId: modelId,
    onProgress: function(report) {
      if (report.progress !== undefined) {
        const pct = Math.round(report.progress * 100);
        elBar.style.width = pct + '%';
        elProgressTx.textContent = report.text || (pct + '%');
      } else if (report.text) {
        elProgressTx.textContent = report.text;
      }
    },
    onReady: function() {
      setState('ready', 'READY');
      elProgress.classList.remove('active');
      elBtnLoad.disabled = false;
      elBtnUnload.disabled = false;
      elBtnSend.disabled = false;
      elBadge.style.display = '';
      elBadge.className = 'backend-badge local';
      elBadge.textContent = 'LOCAL';
      elInference.textContent = 'ON-DEVICE';
      elInput.focus();
      addSystemMessage('Model loaded. Timmy is running locally on your device — fully offline, fully sovereign.');
      updateStats();
    },
    onError: function(err) {
      setState('error', 'FAILED');
      elProgress.classList.remove('active');
      elBtnLoad.disabled = false;
      addSystemMessage('Failed to load model: ' + err.message);
      if (serverFallback) {
        addSystemMessage('Server fallback enabled. Chat will use the server instead.');
        elBtnSend.disabled = false;
        elBadge.style.display = '';
        elBadge.className = 'backend-badge server';
        elBadge.textContent = 'SERVER';
        elInference.textContent = 'SERVER';
      }
    },
  });

  try {
    await llm.init();
  } catch (e) {
    // Error handled by onError callback
  }
}

// ── Unload model ───────────────────────────────────────────────────────────
async function unloadModel() {
  if (llm) {
    await llm.unload();
    llm = null;
  }
  setState('offline', 'NOT LOADED');
  elBtnUnload.disabled = true;
  elBtnSend.disabled = true;
  elBadge.style.display = 'none';
  elInference.textContent = '--';
  elStats.classList.remove('visible');
}

// ── Send message ───────────────────────────────────────────────────────────
async function sendLocalMessage(event) {
  event.preventDefault();
  const message = elInput.value.trim();
  if (!message) return;

  addMessage('user', 'YOU', message);
  elInput.value = '';
  elBtnSend.disabled = true;

  // Try local model first
  if (llm && llm.ready) {
    try {
      const replyBubble = addMessage('timmy', 'TIMMY (LOCAL)', '');
      let fullText = '';
      await llm.chat(message, {
        onToken: function(delta, accumulated) {
          fullText = accumulated;
          replyBubble.textContent = fullText;
          elChat.scrollTop = elChat.scrollHeight;
        }
      });
      if (!fullText) {
        replyBubble.textContent = await llm.chat(message);
      }
      elBtnSend.disabled = false;
      updateStats();
      return;
    } catch (err) {
      addSystemMessage('Local inference failed: ' + err.message);
      if (!serverFallback) {
        elBtnSend.disabled = false;
        return;
      }
    }
  }

  // Server fallback
  if (serverFallback) {
    try {
      const response = await fetch('/agents/timmy/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'message=' + encodeURIComponent(message)
      });
      const html = await response.text();
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      const timmyResponse = doc.querySelector('.chat-message.timmy, .msg-body');
      const text = timmyResponse ? timmyResponse.textContent.trim() : 'Response received.';
      addMessage('timmy', 'TIMMY (SERVER)', text);
    } catch (e) {
      addMessage('timmy', 'TIMMY', 'Sorry, both local and server inference failed. Check your connection.');
    }
  } else {
    addMessage('system', 'SYSTEM', 'Load a model to start chatting.');
  }
  elBtnSend.disabled = false;
}

// ── Helpers ────────────────────────────────────────────────────────────────
function setState(cls, text) {
  elState.className = 'model-status-value ' + cls;
  elState.textContent = text;
}

function addMessage(type, label, text) {
  const div = document.createElement('div');
  div.className = 'local-msg ' + type;
  const meta = document.createElement('div');
  meta.className = 'meta';
  meta.textContent = label;
  const bubble = document.createElement('div');
  bubble.className = 'bubble';
  bubble.textContent = text;
  div.appendChild(meta);
  div.appendChild(bubble);
  elChat.appendChild(div);
  elChat.scrollTop = elChat.scrollHeight;
  return bubble;
}

function addSystemMessage(text) {
  addMessage('system', 'SYSTEM', text);
}

async function updateStats() {
  if (!llm) return;
  try {
    const stats = await llm.getStats();
    if (stats) {
      elStats.textContent = stats;
      elStats.classList.add('visible');
    }
  } catch (e) {
    // Stats are optional
  }
}
</script>
{% endblock %}
