<%# Ruby Calculator - Enhanced Interactive calculator with advanced features %>
<%# Author: RSK World (Molla Samser, Founder | Rima Khatun, Designer & Tester) %>
<%# Contact: help@rskworld.in | +91 93305 39277 %>
<%# Website: https://rskworld.in %>
<%# Year: 2026 %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ruby Calculator Pro - RSK World</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" rel="stylesheet">
    <style>
        :root {
            --theme-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --theme-secondary: #4a5568;
            --theme-accent: #ed8936;
            --theme-success: #48bb78;
            --theme-danger: #e53e3e;
            --theme-warning: #ecc94b;
            --theme-info: #4299e1;
            --theme-background: #f7fafc;
            --theme-text: #2d3748;
            --theme-display: #2d3748;
        }
        
        body {
            background: var(--theme-background);
            color: var(--theme-text);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            transition: all 0.3s ease;
        }
        
        .calculator-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .calculator {
            background: var(--theme-primary);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }
        
        .calculator:hover {
            transform: translateY(-5px);
            box-shadow: 0 25px 50px rgba(0,0,0,0.15);
        }
        
        .display {
            background: var(--theme-display);
            color: white;
            border: none;
            border-radius: 15px;
            padding: 25px;
            font-size: 2.5em;
            text-align: right;
            margin-bottom: 20px;
            min-height: 100px;
            font-family: 'Courier New', monospace;
            box-shadow: inset 0 2px 10px rgba(0,0,0,0.3);
            transition: all 0.3s ease;
        }
        
        .display:focus {
            outline: none;
            box-shadow: inset 0 2px 15px rgba(0,0,0,0.5);
        }
        
        .btn-calc {
            border-radius: 12px;
            font-weight: bold;
            margin: 3px;
            border: none;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .btn-calc:before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(255,255,255,0.3);
            transform: translate(-50%, -50%);
            transition: width 0.6s, height 0.6s;
        }
        
        .btn-calc:active:before {
            width: 300px;
            height: 300px;
        }
        
        .btn-calc:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(0,0,0,0.2);
        }
        
        .btn-number { background: var(--theme-secondary); color: white; }
        .btn-operator { background: var(--theme-accent); color: white; }
        .btn-scientific { background: var(--theme-info); color: white; }
        .btn-memory { background: var(--theme-success); color: white; }
        .btn-clear { background: var(--theme-danger); color: white; }
        .btn-equals { background: var(--theme-success); color: white; }
        
        .theme-selector {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .theme-btn {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin: 5px;
            border: 3px solid transparent;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .theme-btn:hover {
            transform: scale(1.1);
            border-color: #333;
        }
        
        .theme-btn.active {
            border-color: #007bff;
            transform: scale(1.15);
        }
        
        .converter-panel {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .favorites-panel {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .history-panel {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .memory-display {
            background: var(--theme-display);
            color: var(--theme-success);
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            text-align: center;
            font-weight: bold;
            font-size: 1.1em;
        }
        
        .tab-content {
            animation: fadeIn 0.5s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .nav-pills .nav-link.active {
            background: var(--theme-primary);
        }
        
        .footer-info {
            background: var(--theme-secondary);
            color: white;
            padding: 25px;
            border-radius: 15px;
            margin-top: 30px;
            text-align: center;
        }
        
        .keyboard-hint {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 10px;
            margin: 10px 0;
            font-size: 0.9em;
            color: #6c757d;
        }
        
        .favorite-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin: 10px 0;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .favorite-item:hover {
            background: #e9ecef;
            transform: translateX(5px);
        }
        
        @media (max-width: 768px) {
            .calculator {
                margin: 10px;
                padding: 20px;
            }
            
            .btn-calc {
                margin: 2px;
                font-size: 0.9em;
            }
            
            .display {
                font-size: 2em;
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid calculator-container">
        <!-- Header -->
        <div class="text-center mb-4 animate__animated animate__fadeInDown">
            <h1 class="display-4">
                <i class="fas fa-gem text-danger"></i> Ruby Calculator Pro
            </h1>
            <p class="lead">Advanced Calculator with Currency Converter, Unit Converter & More</p>
        </div>

        <!-- Theme Selector -->
        <div class="theme-selector animate__animated animate__fadeInUp">
            <h5><i class="fas fa-palette"></i> Choose Theme</h5>
            <div class="d-flex flex-wrap justify-content-center">
                <div class="theme-btn active" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)" data-theme="default" title="Default Purple"></div>
                <div class="theme-btn" style="background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%)" data-theme="dark" title="Dark Mode"></div>
                <div class="theme-btn" style="background: linear-gradient(135deg, #0077be 0%, #004d7a 100%)" data-theme="ocean" title="Ocean Blue"></div>
                <div class="theme-btn" style="background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%)" data-theme="sunset" title="Sunset Orange"></div>
                <div class="theme-btn" style="background: linear-gradient(135deg, #27ae60 0%, #16a085 100%)" data-theme="forest" title="Forest Green"></div>
                <div class="theme-btn" style="background: linear-gradient(135deg, #ff6ec7 0%, #c471ed 100%)" data-theme="candy" title="Candy Pink"></div>
            </div>
        </div>

        <!-- Navigation Tabs -->
        <ul class="nav nav-pills justify-content-center mb-4" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" data-bs-toggle="pill" href="#calculator-tab">
                    <i class="fas fa-calculator"></i> Calculator
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="pill" href="#converter-tab">
                    <i class="fas fa-exchange-alt"></i> Converter
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="pill" href="#favorites-tab">
                    <i class="fas fa-star"></i> Favorites
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="pill" href="#history-tab">
                    <i class="fas fa-history"></i> History
                </a>
            </li>
        </ul>

        <!-- Tab Content -->
        <div class="tab-content">
            <!-- Calculator Tab -->
            <div class="tab-pane fade show active" id="calculator-tab">
                <div class="calculator animate__animated animate__fadeIn">
                    <!-- Memory Display -->
                    <div class="memory-display">
                        <i class="fas fa-memory"></i> Memory: <span id="memory-value"><%= @memory %></span>
                    </div>

                    <!-- Display -->
                    <input type="text" id="display" class="display form-control" value="0" readonly>

                    <!-- Keyboard Hints -->
                    <div class="keyboard-hint">
                        <i class="fas fa-keyboard"></i> Keyboard shortcuts: Numbers (0-9), Operations (+,-,*,/), Enter (=), Escape (C), Backspace (←)
                    </div>

                    <!-- Scientific Functions -->
                    <div class="row mb-2">
                        <div class="col-3"><button class="btn btn-scientific btn-calc w-100" onclick="scientificFunction('sin')">sin</button></div>
                        <div class="col-3"><button class="btn btn-scientific btn-calc w-100" onclick="scientificFunction('cos')">cos</button></div>
                        <div class="col-3"><button class="btn btn-scientific btn-calc w-100" onclick="scientificFunction('tan')">tan</button></div>
                        <div class="col-3"><button class="btn btn-scientific btn-calc w-100" onclick="scientificFunction('sqrt')">√</button></div>
                    </div>

                    <div class="row mb-2">
                        <div class="col-3"><button class="btn btn-scientific btn-calc w-100" onclick="scientificFunction('log')">log</button></div>
                        <div class="col-3"><button class="btn btn-scientific btn-calc w-100" onclick="scientificFunction('ln')">ln</button></div>
                        <div class="col-3"><button class="btn btn-scientific btn-calc w-100" onclick="scientificFunction('factorial')">n!</button></div>
                        <div class="col-3"><button class="btn btn-scientific btn-calc w-100" onclick="appendToDisplay('^')">x^y</button></div>
                    </div>

                    <!-- Memory Functions -->
                    <div class="row mb-2">
                        <div class="col-3"><button class="btn btn-memory btn-calc w-100" onclick="memoryFunction('recall')">MR</button></div>
                        <div class="col-3"><button class="btn btn-memory btn-calc w-100" onclick="memoryFunction('add')">M+</button></div>
                        <div class="col-3"><button class="btn btn-memory btn-calc w-100" onclick="memoryFunction('subtract')">M-</button></div>
                        <div class="col-3"><button class="btn btn-memory btn-calc w-100" onclick="memoryFunction('clear')">MC</button></div>
                    </div>

                    <!-- Numbers and Operators -->
                    <div class="row mb-2">
                        <div class="col-3"><button class="btn btn-clear btn-calc w-100" onclick="clearDisplay()">C</button></div>
                        <div class="col-3"><button class="btn btn-operator btn-calc w-100" onclick="appendToDisplay('/')">÷</button></div>
                        <div class="col-3"><button class="btn btn-operator btn-calc w-100" onclick="appendToDisplay('*')">×</button></div>
                        <div class="col-3"><button class="btn btn-operator btn-calc w-100" onclick="deleteLastDigit()">←</button></div>
                    </div>

                    <div class="row mb-2">
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="appendToDisplay('7')">7</button></div>
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="appendToDisplay('8')">8</button></div>
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="appendToDisplay('9')">9</button></div>
                        <div class="col-3"><button class="btn btn-operator btn-calc w-100" onclick="appendToDisplay('-')">−</button></div>
                    </div>

                    <div class="row mb-2">
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="appendToDisplay('4')">4</button></div>
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="appendToDisplay('5')">5</button></div>
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="appendToDisplay('6')">6</button></div>
                        <div class="col-3"><button class="btn btn-operator btn-calc w-100" onclick="appendToDisplay('+')">+</button></div>
                    </div>

                    <div class="row mb-2">
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="appendToDisplay('1')">1</button></div>
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="appendToDisplay('2')">2</button></div>
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="appendToDisplay('3')">3</button></div>
                        <div class="col-3"><button class="btn btn-equals btn-calc w-100" onclick="calculate()">=</button></div>
                    </div>

                    <div class="row">
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="appendToDisplay('0')">0</button></div>
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="appendToDisplay('.')">.</button></div>
                        <div class="col-3"><button class="btn btn-number btn-calc w-100" onclick="changeSign()">±</button></div>
                        <div class="col-3"><button class="btn btn-equals btn-calc w-100" onclick="calculate()">=</button></div>
                    </div>
                </div>
            </div>

            <!-- Converter Tab -->
            <div class="tab-pane fade" id="converter-tab">
                <div class="converter-panel">
                    <h4><i class="fas fa-exchange-alt"></i> Currency & Unit Converter</h4>
                    
                    <!-- Currency Converter -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h5>Currency Converter</h5>
                            <div class="mb-3">
                                <input type="number" class="form-control" id="currency-amount" placeholder="Amount" step="0.01">
                            </div>
                            <div class="row">
                                <div class="col-6">
                                    <select class="form-select" id="from-currency">
                                        <option value="USD">USD - US Dollar</option>
                                        <option value="EUR">EUR - Euro</option>
                                        <option value="GBP">GBP - British Pound</option>
                                        <option value="INR">INR - Indian Rupee</option>
                                        <option value="JPY">JPY - Japanese Yen</option>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <select class="form-select" id="to-currency">
                                        <option value="EUR">EUR - Euro</option>
                                        <option value="USD">USD - US Dollar</option>
                                        <option value="GBP">GBP - British Pound</option>
                                        <option value="INR">INR - Indian Rupee</option>
                                        <option value="JPY">JPY - Japanese Yen</option>
                                    </select>
                                </div>
                            </div>
                            <button class="btn btn-primary mt-3" onclick="convertCurrency()">
                                <i class="fas fa-exchange-alt"></i> Convert
                            </button>
                            <div id="currency-result" class="mt-3"></div>
                        </div>
                        
                        <!-- Unit Converter -->
                        <div class="col-md-6">
                            <h5>Unit Converter</h5>
                            <div class="mb-3">
                                <input type="number" class="form-control" id="unit-amount" placeholder="Amount" step="0.01">
                            </div>
                            <div class="mb-3">
                                <select class="form-select" id="unit-category" onchange="loadUnits()">
                                    <option value="length">Length</option>
                                    <option value="weight">Weight</option>
                                    <option value="temperature">Temperature</option>
                                    <option value="volume">Volume</option>
                                    <option value="area">Area</option>
                                    <option value="speed">Speed</option>
                                    <option value="data">Data Storage</option>
                                </select>
                            </div>
                            <div class="row">
                                <div class="col-6">
                                    <select class="form-select" id="from-unit"></select>
                                </div>
                                <div class="col-6">
                                    <select class="form-select" id="to-unit"></select>
                                </div>
                            </div>
                            <button class="btn btn-primary mt-3" onclick="convertUnit()">
                                <i class="fas fa-exchange-alt"></i> Convert
                            </button>
                            <div id="unit-result" class="mt-3"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Favorites Tab -->
            <div class="tab-pane fade" id="favorites-tab">
                <div class="favorites-panel">
                    <h4><i class="fas fa-star"></i> Favorite Calculations</h4>
                    <div class="mb-3">
                        <button class="btn btn-success" onclick="saveAsFavorite()">
                            <i class="fas fa-plus"></i> Save Current as Favorite
                        </button>
                    </div>
                    <div id="favorites-list">
                        <div class="favorite-item">
                            <strong>Pythagorean Theorem</strong><br>
                            <code>a² + b² = c²</code><br>
                            <small>Mathematical Formula</small>
                        </div>
                        <div class="favorite-item">
                            <strong>Area of Circle</strong><br>
                            <code>π × r²</code><br>
                            <small>Mathematical Formula</small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- History Tab -->
            <div class="tab-pane fade" id="history-tab">
                <div class="history-panel">
                    <h4><i class="fas fa-history"></i> Calculation History</h4>
                    <div class="mb-3">
                        <input type="text" class="form-control" placeholder="Search history..." id="history-search">
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Expression</th>
                                    <th>Result</th>
                                    <th>Operation</th>
                                    <th>Time</th>
                                </tr>
                            </thead>
                            <tbody id="history-tbody">
                                <% @history.each do |calc| %>
                                    <tr>
                                        <td><code><%= calc.expression %></code></td>
                                        <td><strong><%= calc.result %></strong></td>
                                        <td><span class="badge bg-primary"><%= calc.operation %></span></td>
                                        <td><small><%= calc.created_at.strftime("%H:%M:%S") %></small></td>
                                    </tr>
                                <% end %>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <div class="footer-info animate__animated animate__fadeInUp">
            <h6><i class="fas fa-gem text-danger"></i> Ruby Calculator Pro</h6>
            <p class="mb-1">Advanced Calculator with Currency Converter, Unit Converter & More</p>
            <p class="mb-1">© 2026 <a href="https://rskworld.in" target="_blank" class="text-white">RSK World</a></p>
            <p class="mb-0">Developed by: Molla Samser (Founder) | Rima Khatun (Designer & Tester)</p>
            <p class="mb-0">Contact: <a href="mailto:help@rskworld.in" class="text-white">help@rskworld.in</a> | +91 93305 39277</p>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentInput = '0';
        let shouldResetDisplay = false;

        // Theme Management
        document.querySelectorAll('.theme-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const theme = this.dataset.theme;
                applyTheme(theme);
                
                document.querySelectorAll('.theme-btn').forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                // Save theme preference
                fetch('/theme/update', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ theme: theme })
                });
            });
        });

        function applyTheme(themeName) {
            const themes = {
                default: { primary: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', display: '#2d3748' },
                dark: { primary: 'linear-gradient(135deg, #1a202c 0%, #2d3748 100%)', display: '#2d3748' },
                ocean: { primary: 'linear-gradient(135deg, #0077be 0%, #004d7a 100%)', display: '#1a365d' },
                sunset: { primary: 'linear-gradient(135deg, #ff6b6b 0%, #feca57 100%)', display: '#d63031' },
                forest: { primary: 'linear-gradient(135deg, #27ae60 0%, #16a085 100%)', display: '#145a32' },
                candy: { primary: 'linear-gradient(135deg, #ff6ec7 0%, #c471ed 100%)', display: '#e84393' }
            };
            
            const theme = themes[themeName] || themes.default;
            document.documentElement.style.setProperty('--theme-primary', theme.primary);
            document.documentElement.style.setProperty('--theme-display', theme.display);
        }

        // Calculator Functions
        function updateDisplay() {
            document.getElementById('display').value = currentInput;
        }

        function appendToDisplay(value) {
            if (shouldResetDisplay) {
                currentInput = '0';
                shouldResetDisplay = false;
            }
            
            if (currentInput === '0' && value !== '.') {
                currentInput = value;
            } else {
                currentInput += value;
            }
            updateDisplay();
            playButtonSound();
        }

        function clearDisplay() {
            currentInput = '0';
            updateDisplay();
            playButtonSound();
        }

        function deleteLastDigit() {
            if (currentInput.length > 1) {
                currentInput = currentInput.slice(0, -1);
            } else {
                currentInput = '0';
            }
            updateDisplay();
            playButtonSound();
        }

        function changeSign() {
            if (currentInput !== '0') {
                if (currentInput.startsWith('-')) {
                    currentInput = currentInput.slice(1);
                } else {
                    currentInput = '-' + currentInput;
                }
                updateDisplay();
            }
        }

        function calculate() {
            try {
                const expression = currentInput.replace(/×/g, '*').replace(/÷/g, '/').replace(/−/g, '-');
                const result = eval(expression);
                currentInput = result.toString();
                shouldResetDisplay = true;
                updateDisplay();
                playSuccessSound();
                
                // Save to server
                saveCalculation(expression, result);
            } catch (error) {
                currentInput = 'Error';
                shouldResetDisplay = true;
                updateDisplay();
                playErrorSound();
            }
        }

        function scientificFunction(func) {
            const value = parseFloat(currentInput);
            let result;
            
            switch(func) {
                case 'sin': result = Math.sin(value * Math.PI / 180); break;
                case 'cos': result = Math.cos(value * Math.PI / 180); break;
                case 'tan': result = Math.tan(value * Math.PI / 180); break;
                case 'sqrt': result = Math.sqrt(Math.abs(value)); break;
                case 'log': result = Math.log10(value); break;
                case 'ln': result = Math.log(value); break;
                case 'factorial': result = factorial(Math.floor(value)); break;
            }
            
            currentInput = result.toString();
            shouldResetDisplay = true;
            updateDisplay();
            playSuccessSound();
        }

        function factorial(n) {
            if (n <= 1) return 1;
            return n * factorial(n - 1);
        }

        function memoryFunction(action) {
            const value = parseFloat(currentInput);
            
            fetch('/calculator/memory', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ memory_action: action, value: value })
            }).then(response => response.json())
              .then(data => {
                  document.getElementById('memory-value').textContent = data.memory;
              });
        }

        // Converter Functions
        function convertCurrency() {
            const amount = parseFloat(document.getElementById('currency-amount').value);
            const from = document.getElementById('from-currency').value;
            const to = document.getElementById('to-currency').value;
            
            fetch('/converter/convert_currency', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ amount, from_currency: from, to_currency: to })
            }).then(response => response.json())
              .then(data => {
                  if (data.result) {
                      document.getElementById('currency-result').innerHTML = 
                          `<div class="alert alert-success">${amount} ${from} = ${data.result} ${to}</div>`;
                  } else {
                      document.getElementById('currency-result').innerHTML = 
                          `<div class="alert alert-danger">Conversion failed</div>`;
                  }
              });
        }

        function convertUnit() {
            const amount = parseFloat(document.getElementById('unit-amount').value);
            const from = document.getElementById('from-unit').value;
            const to = document.getElementById('to-unit').value;
            const category = document.getElementById('unit-category').value;
            
            fetch('/converter/convert_unit', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ amount, from_unit: from, to_unit: to, category })
            }).then(response => response.json())
              .then(data => {
                  if (data.result) {
                      document.getElementById('unit-result').innerHTML = 
                          `<div class="alert alert-success">${amount} ${from} = ${data.result} ${to}</div>`;
                  } else {
                      document.getElementById('unit-result').innerHTML = 
                          `<div class="alert alert-danger">Conversion failed</div>`;
                  }
              });
        }

        function loadUnits() {
            const category = document.getElementById('unit-category').value;
            fetch(`/converter/get_units?category=${category}`)
                .then(response => response.json())
                .then(data => {
                    const fromSelect = document.getElementById('from-unit');
                    const toSelect = document.getElementById('to-unit');
                    
                    fromSelect.innerHTML = '';
                    toSelect.innerHTML = '';
                    
                    data.units.forEach(unit => {
                        fromSelect.innerHTML += `<option value="${unit}">${unit}</option>`;
                        toSelect.innerHTML += `<option value="${unit}">${unit}</option>`;
                    });
                });
        }

        // Keyboard Shortcuts
        document.addEventListener('keydown', function(e) {
            if (e.key >= '0' && e.key <= '9') appendToDisplay(e.key);
            else if (e.key === '.') appendToDisplay('.');
            else if (e.key === '+') appendToDisplay('+');
            else if (e.key === '-') appendToDisplay('-');
            else if (e.key === '*') appendToDisplay('*');
            else if (e.key === '/') appendToDisplay('/');
            else if (e.key === 'Enter') calculate();
            else if (e.key === 'Escape') clearDisplay();
            else if (e.key === 'Backspace') deleteLastDigit();
        });

        // Sound Effects (Web Audio API)
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();

        function playButtonSound() {
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            oscillator.frequency.value = 800;
            oscillator.type = 'sine';
            gainNode.gain.value = 0.1;
            
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.05);
        }

        function playSuccessSound() {
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            oscillator.frequency.value = 1200;
            oscillator.type = 'sine';
            gainNode.gain.value = 0.15;
            
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.1);
        }

        function playErrorSound() {
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            oscillator.frequency.value = 300;
            oscillator.type = 'sawtooth';
            gainNode.gain.value = 0.1;
            
            oscillator.start();
            oscillator.stop(audioContext.currentTime + 0.2);
        }

        // Save calculation to server
        function saveCalculation(expression, result) {
            fetch('/calculator/calculate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ expression, result })
            });
        }

        // Initialize
        updateDisplay();
        loadUnits();
    </script>
</body>
</html>
