<!DOCTYPE html>
<html lang="en" class="dark">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
  <script>
    tailwind.config = {
      darkMode: 'class',
      theme: {
        extend: {
          colors: {
            studio_bg: 'var(--bg-canvas)',       
            studio_panel: 'var(--bg-panel)',      
            studio_border: 'var(--border-color)',    
            studio_editor: 'var(--bg-editor)',   
            t_text: 'var(--text-main)',
            t_subtext: 'var(--text-sub)',
            t_teal: '#00d4aa',
            t_teal_dim: 'var(--teal-dim)',
            t_blue: '#4a9eff',
          },
          fontFamily: {
            sans: ['Inter', 'sans-serif'],
            mono: ['JetBrains Mono', 'monospace'],
          }
        }
      }
    }
  </script>
  <style>
    :root {
      /* State -1: Light Mode */
      --bg-canvas: #F8FAFC;
      --bg-panel: #FFFFFF;
      --border-color: #CBD5E1;
      --bg-editor: #F1F5F9;
      --text-main: #0F172A;
      --text-sub: #1E293B; 
      --teal-dim: rgba(0, 212, 170, 0.15);
    }
    
    .dark {
      /* State +1: Dark Mode — matched to TernStudio --bg / --bg1 / --border */
      --bg-canvas: #0f172a;
      --bg-panel: #1e293b;
      --border-color: #334155;
      --bg-editor: #0f172a;
      --text-main: #f1f5f9;
      --text-sub: #cbd5e1;
      --teal-dim: rgba(0, 212, 170, 0.12);
    }

    body {
      background-color: var(--bg-canvas);
      color: var(--text-main);
      transition: background-color 0.2s ease, color 0.2s ease;
    }
    
    .glass-panel {
      background: var(--bg-panel);
      border: 1px solid var(--border-color);
      box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.3);
      transition: background-color 0.2s ease, border-color 0.2s ease;
    }

    .editor-pane {
      background: var(--bg-editor);
      box-shadow: inset 0 2px 15px rgba(0, 0, 0, 0.1);
      transition: background-color 0.2s ease;
    }
    .dark .editor-pane {
      box-shadow: inset 0 2px 15px rgba(0, 0, 0, 0.8);
    }

    textarea:focus { outline: none; }
    
    /* Strict scrollbar enforcement */
    ::-webkit-scrollbar { width: 8px; height: 8px; }
    ::-webkit-scrollbar-track { background: transparent; }
    ::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 4px; }
    ::-webkit-scrollbar-thumb:hover { background: #00d4aa; }
    
    .btn-glow:hover {
      box-shadow: 0 0 15px rgba(0, 212, 170, 0.3);
      background: rgba(0, 212, 170, 0.1);
    }
  </style>
</head>
<body class="antialiased min-h-screen flex flex-col p-0">

  <div class="w-full h-screen flex flex-col">

    <!-- Main Workspace -->
    <div class="glass-panel rounded-none flex flex-col flex-1 min-h-0">
      
      <!-- Top Toolbar -->
      <div class="flex flex-col md:flex-row border-b border-studio_border bg-studio_panel px-5 py-3 items-center justify-between gap-4">
        
        <div class="flex items-center gap-4 w-full md:w-auto flex-wrap">
          <div class="flex items-center gap-2">
            <div class="w-2 h-2 rounded-full bg-t_teal animate-pulse"></div>
            <span id="mode-label" class="text-t_text font-mono text-[13px] uppercase tracking-widest min-w-[110px]">Source Engine</span>
          </div>
          <select id="trans-lang" class="bg-studio_editor border border-studio_border text-t_text focus:text-t_teal focus:border-t_teal transition-colors font-mono text-[15px] px-3 py-1.5 rounded-md outline-none cursor-pointer">
            <option value="python">Python</option>
            <option value="rust">Rust</option>
            <option value="java">Java</option>
            <option value="cpp">C++</option>
            <option value="javascript">JavaScript</option>
          </select>
          
          <button id="swap-direction-btn" class="p-1.5 rounded-md border border-studio_border bg-studio_editor text-t_subtext hover:text-t_teal hover:border-t_teal transition-all group" title="Swap Translation Direction">
            <svg class="w-5 h-5 group-hover:rotate-180 transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path></svg>
          </button>
          
          <div class="h-4 w-px bg-studio_border hidden md:block"></div>
          
          <label class="cursor-pointer flex items-center gap-2 text-t_text hover:text-t_blue transition-colors font-mono text-[15px] group">
            <svg class="w-5 h-5 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"></path></svg>
            <span>Upload</span>
            <input type="file" id="trans-upload" class="hidden" accept=".py,.rs,.java,.cpp,.js,.ts,.html,.tern">
          </label>
        </div>

        <div class="flex items-center gap-4 w-full md:w-auto">
          <!-- Highly visible Theme Toggle -->
          <button id="theme-toggle" class="p-2 rounded-md border border-studio_border bg-studio_editor text-t_subtext hover:text-t_teal transition-colors" title="Toggle Polarity (+1 / -1)">
            <svg class="w-5 h-5 hidden dark:block" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"></path></svg>
            <svg class="w-5 h-5 block dark:hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path></svg>
          </button>

          <button id="trans-run-btn" class="flex-1 md:flex-none flex items-center justify-center gap-2 px-6 py-2 border border-t_teal/50 text-t_teal font-mono text-[15px] font-bold uppercase tracking-wider rounded-md transition-all btn-glow bg-t_teal_dim">
            <svg class="w-5 h-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg>
            <span id="trans-run-text">Translate</span>
          </button>
        </div>
      </div>

      <!-- Code Areas -->
      <div class="grid md:grid-cols-2 flex-1 divide-y md:divide-y-0 md:divide-x divide-studio_border min-h-0" style="height: calc(100vh - 110px)">
        
        <!-- Input -->
        <div class="flex flex-col relative group min-h-0">
          <div id="input-label" class="absolute top-3 right-4 font-mono text-[13px] text-t_subtext uppercase tracking-widest z-10 select-none bg-studio_editor/80 px-2 py-1 rounded border border-studio_border/50">Input // Binary</div>
          <textarea id="trans-input" class="editor-pane flex-1 w-full p-5 pt-12 font-mono text-[17px] text-t_subtext resize-none overflow-y-auto block" spellcheck="false" placeholder="// Paste architecture logic here..."></textarea>
        </div>
        
        <!-- Output -->
        <div class="flex flex-col relative min-h-0">
          <div id="output-label" class="absolute top-3 right-4 font-mono text-[13px] text-t_teal uppercase tracking-widest z-10 select-none bg-studio_editor/80 px-2 py-1 rounded border border-studio_border/50">Output // Ternary</div>
          <div id="trans-output" class="editor-pane flex-1 w-full p-5 pt-12 font-mono text-[17px] text-t_teal overflow-y-auto whitespace-pre block"></div>
        </div>
        
      </div>

      <!-- Insight Footer -->
      <div class="bg-studio_panel border-t border-studio_border p-5 shrink-0">
        <div class="flex items-center gap-2 mb-3">
          <svg class="w-4 h-4 text-t_blue" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
          <h4 class="text-t_text font-mono text-[13px] uppercase tracking-widest">Topology Insights</h4>
        </div>
        <div id="trans-insight" class="flex flex-wrap gap-2 text-[15px] text-t_subtext">
          <div class="px-3 py-1.5 bg-studio_editor border border-studio_border rounded font-mono">Awaiting logic vectors...</div>
        </div>
      </div>
    </div>

  </div>

  <script>
    // State Matrix
    let isTernToBinary = false;

    // UI Elements
    const themeToggle = document.getElementById('theme-toggle');
    const htmlElement = document.documentElement;
    const transInput = document.getElementById('trans-input');
    const transOutput = document.getElementById('trans-output');
    const transInsight = document.getElementById('trans-insight');
    const transBtn = document.getElementById('trans-run-btn');
    const transBtnText = document.getElementById('trans-run-text');
    const transUpload = document.getElementById('trans-upload');
    const swapBtn = document.getElementById('swap-direction-btn');
    
    // Auth Bridge
    let apiKey = '';
    window.addEventListener('message', (event) => {
      if (event.data.type === 'TIS_AUTH_BRIDGE') {
        apiKey = event.data.key;
        console.log('[TernTranslator] API Key received via bridge');
      }
    });

    // Labels
    const modeLabel = document.getElementById('mode-label');
    const inputLabel = document.getElementById('input-label');
    const outputLabel = document.getElementById('output-label');

    // Theme Toggle Logic
    themeToggle.addEventListener('click', () => {
      htmlElement.classList.toggle('dark');
    });

    // Swap Direction Logic
    swapBtn.addEventListener('click', () => {
      isTernToBinary = !isTernToBinary;
      
      // Physically swap the code buffers
      const tempBuffer = transInput.value;
      transInput.value = transOutput.textContent;
      transOutput.textContent = tempBuffer;

      // Update Polarity UI
      if (isTernToBinary) {
        modeLabel.textContent = "Target Engine";
        inputLabel.textContent = "Input // Ternary";
        inputLabel.classList.replace('text-t_subtext', 'text-t_teal');
        
        outputLabel.textContent = "Output // Binary";
        outputLabel.classList.replace('text-t_teal', 'text-t_subtext');
        
        transOutput.classList.replace('text-t_teal', 'text-t_subtext');
        transInput.classList.replace('text-t_subtext', 'text-t_teal');
      } else {
        modeLabel.textContent = "Source Engine";
        inputLabel.textContent = "Input // Binary";
        inputLabel.classList.replace('text-t_teal', 'text-t_subtext');
        
        outputLabel.textContent = "Output // Ternary";
        outputLabel.classList.replace('text-t_subtext', 'text-t_teal');

        transOutput.classList.replace('text-t_subtext', 'text-t_teal');
        transInput.classList.replace('text-t_teal', 'text-t_subtext');
      }
      
      transInsight.innerHTML = `<div class="px-3 py-1.5 bg-studio_editor border border-studio_border rounded font-mono text-[13px] text-t_subtext">Vector polarity reversed. Awaiting input...</div>`;
    });

    // Translation Matrices
    const TERN_RULES = [
      { regex: /\bbool\b/g, repl: 'trit', note: 'Mapped binary bool to triadic trit.' },
      { regex: /\btrue\b/g, repl: 'affirm', note: 'Mapped true to +1 (affirm).' },
      { regex: /\bfalse\b/g, repl: 'reject', note: 'Mapped false to -1 (reject).' },
      { regex: /\bNone\b|\bnull\b|\bundefined\b/g, repl: 'tend', note: 'Mapped null/empty to 0 (tend).' },
      { regex: /if\s*\((.*)\)\s*\{/g, repl: 'match $1 {', note: 'Converted if-statement to exhaustive match block.' },
      { regex: /if\s+(.*):/g, repl: 'match $1 {', note: 'Python-style if converted to match.' },
      { regex: /else\s*\{|else:/g, repl: 'tend => { // auto-injected safety hold\n    }\n    reject => {', note: 'Injected state 0 (tend) for logic exhaustiveness.' },
      { regex: /return\s+1\b|return\s+True\b/gi, repl: 'return affirm', note: 'Normalised positive return.' },
      { regex: /return\s+0\b|return\s+False\b/gi, repl: 'return reject', note: 'Normalised negative return.' },
      { regex: /\bvoid\b|\bdef\b|\bfn\b/g, repl: 'fn', note: 'Unified function declaration.' },
    ];

    const REVERSE_RULES = [
      { regex: /\btrit\b/g, repl: 'bool', note: 'De-resolved triadic trit back to binary bool.' },
      { regex: /\baffirm\b/g, repl: 'true', note: 'Flattened +1 (affirm) to binary true.' },
      { regex: /\breject\b/g, repl: 'false', note: 'Flattened -1 (reject) to binary false.' },
      { regex: /\btend\b/g, repl: 'null', note: 'Collapsed 0 (tend) to null/None dependency.' },
      { regex: /match\s+(.*)\s*\{/g, repl: 'switch ($1) {', note: 'Reverted exhaustive match to standard switch/if.' },
      { regex: /tend\s*=>\s*\{[\s\S]*?\}\s*reject\s*=>\s*\{/g, repl: 'default: {', note: 'Collapsed safety hold (tend) back into binary default/else block.' },
      { regex: /return\s+affirm\b/g, repl: 'return true', note: 'Restored boolean positive return.' },
      { regex: /return\s+reject\b/g, repl: 'return false', note: 'Restored boolean negative return.' },
      { regex: /\bfn\b/g, repl: 'function', note: 'Reverted generic function declaration.' },
    ];

    function translate() {
      let code = transInput.value;
      if (!code.trim()) return;

      transBtn.disabled = true;
      transBtnText.textContent = 'Parsing...';
      const originalSvg = transBtn.querySelector('svg').outerHTML;
      transBtn.innerHTML = `<svg class="w-5 h-5 shrink-0 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg><span id="trans-run-text">Parsing...</span>`;
      
      const insights = new Set();
      let translated = code;
      const activeRules = isTernToBinary ? REVERSE_RULES : TERN_RULES;

      activeRules.forEach(rule => {
        if (rule.regex.test(translated)) {
          translated = translated.replace(rule.regex, rule.repl);
          insights.add(rule.note);
        }
      });

      // Signature header adjustment based on polarity
      if (!isTernToBinary && !translated.includes('fn main')) {
        translated = "// Translated via Ternlang BET VM Protocol\n\n" + translated;
      } else if (isTernToBinary && !translated.includes('function main')) {
        translated = "// De-resolved from Ternlang BET VM Protocol\n\n" + translated;
      }

      setTimeout(() => {
        transOutput.textContent = translated;
        
        if (insights.size > 0) {
          transInsight.innerHTML = Array.from(insights).map(note => 
            `<div class="px-3 py-1.5 bg-studio_editor border border-studio_border rounded flex items-center gap-2">
              <span class="w-1.5 h-1.5 rounded-full bg-t_teal"></span>
              <span class="text-t_text font-mono text-[13px]">${note}</span>
            </div>`
          ).join('');
        } else {
          transInsight.innerHTML = `<div class="px-3 py-1.5 bg-studio_editor border border-studio_border rounded font-mono text-[13px] text-t_text">System baseline logic detected. No morphing required.</div>`;
        }
        
        transBtn.disabled = false;
        transBtn.innerHTML = `${originalSvg}<span id="trans-run-text">Translate</span>`;
      }, 400);
    }

    transBtn.addEventListener('click', translate);

    transUpload.addEventListener('change', (e) => {
      const file = e.target.files[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = (e) => {
        transInput.value = e.target.result;
        translate();
      };
      reader.readAsText(file);
    });
  </script>
</body>
</html>
