<div class="">
  <h4><span style="color: green; font-family: sans-serif; font-size: 1.1em"><b>{{ title }}</b>{% if platform %} <span style="color: #666; font-size: 0.8em;">({{ platform }})</span>{% endif %} <!-- ({{ title.version_current }}) --></span>
	<!-- <span style="float: right; font-size: 15px"><a href="#" onclick="(confirm('Close {{ title.title }}?')) ? (function(){window.open('','_self').close()}()) : (function(){return false;}())">&#x274C; Close App and End Session</a></span> -->
        <span style="float: center; font-size: 15px">
            <a class='btn btn-normal'  href="/instruction" target="_blank" rel="noopener" data-toggle="tooltip" title="Instruction for preparing your
                      device for a scan."><u>Scan Instructions</u></a>
            <a class='btn btn-normal' href="/form/edit" target="_blank" rel="noopener" data-toggle="tooltip" title="Edit previously submitted consult forms."><u>Edit previous consult forms</u></a>
            <a class='btn btn-normal' href="/privacy" target="_blank" rel="noopener" data-toggle="tooltip" title="Review the built-in sharing feature settings of your device with this."><u>Privacy Checkup</u></a>
            <a href="/kill" onclick="window.open('','_self').close();">&#x274C; Close App and End Session</a>
        </span> 
    </h4>
    <!-- <form id="kill-server" method="POST" action="/kill" name="form-kill">
	 <button value="submit" class="btn btn-primary mx-2">Close App</button>
	 </form> -->
</div>
<div class="row  h-100">
    <div class="col-md-3 border py-2" style="height:90vh;">
        <div align="center">
            <p><!-- {{ title.title }} is  -->An <a href="https://github.com/rchatterjee/phone_scanner" target="_blank" rel="noopener">open-source</a> app
                for scanning Android and iOS devices to find apps that
                can be used to spy, track, or otherwise monitor a person.
            </p>
            <hr/>
            <label class="font-weight-bold lead">What type of device is this?</label>
            <form id="scan_select" method="GET" action="/scan">
                <div class="btn-group btn-group-toggle" data-toggle="buttons">
		    {% for a in ["Android", "iOS"] %}
                    <label class="btn btn-outline-secondary {% if device==a.lower() %} active {% endif %}">
                        <input type="radio" name="device" id="{{ a | lower }}"
			       value="{{ a | lower }}" autocomplete="off"
			       {% if device==a.lower() %} checked {% endif %}
			> {{ a }}
                    </label>
		    {% endfor %}
                </div>
                <br/><br/>
                <input class="form-control" name="device_owner" id="device_owner" 
                       placeholder="Nickname for device? Whose is it?"
                       rows="2" value="{% if device_primary_user_sel %}{{ device_primary_user_sel }}{% endif %}"/>
		<br>
                <button class="btn btn-primary mx-2">Scan now</button>
            </form>
            <br/>
            {% if is_termux or is_debug %}
            <div id="termux-usb-section">
                <button type="button" id="btn-termux-usb" class="btn btn-warning btn-sm">
                    📱 Request USB Access
                </button>
                <div id="termux-usb-msg" class="small mt-2" style="display:none;"></div>
            </div>
            {% endif %}
            <script>
                (function() {
                    var btn = document.getElementById('btn-termux-usb');
                    if (!btn) {
                        console.error('USB button not found');
                        return;
                    }
                    
                    btn.addEventListener('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        console.log('requestTermuxUSBPermission called');
                        var msgDiv = document.getElementById('termux-usb-msg');
                        
                        btn.disabled = true;
                        btn.textContent = 'Requesting...';
                        msgDiv.style.display = 'none';
                        
                        console.log('Sending POST request to /termux-usb-permission');
                        
                        var xhr = new XMLHttpRequest();
                        xhr.open('POST', '/termux-usb-permission', true);
                        xhr.setRequestHeader('Content-Type', 'application/json');
                        
                        xhr.onload = function() {
                            console.log('Response received:', xhr.status, xhr.statusText);
                            var result;
                            try {
                                result = JSON.parse(xhr.responseText);
                            } catch (e) {
                                console.error('Failed to parse response:', e);
                                result = { error: 'Invalid response from server' };
                            }
                            
                            btn.disabled = false;
                            btn.textContent = '📱 Request USB Access';
                            msgDiv.style.display = 'block';
                            
                            if (xhr.status === 200 && result.success) {
                                msgDiv.className = 'small mt-2 text-success';
                                msgDiv.textContent = '✓ ' + result.message;
                            } else {
                                msgDiv.className = 'small mt-2 text-danger';
                                msgDiv.textContent = '✗ ' + (result.error || 'Failed to request USB permission');
                            }
                        };
                        
                        xhr.onerror = function() {
                            console.error('Error requesting USB permission');
                            btn.disabled = false;
                            btn.textContent = '📱 Request USB Access';
                            msgDiv.style.display = 'block';
                            msgDiv.className = 'small mt-2 text-danger';
                            msgDiv.textContent = '✗ Network error occurred';
                        };
                        
                        xhr.send();
                        
                        return false;
                    });
                })();
            </script>
	    <!-- {% for t in ["Android", "iOS", "test"] %} -->
            <!-- button onclick="fetch('/scan/{{ t.lower() }}', '{{ t.lower() }}')" id="btn-android"
                 class="btn btn-primary mx-2">{{ t }}</button -->
	    <!-- {% endfor %} -->
            <hr/>
        </div>
        <div class="border-warning visible" align="center">
	    {% if currently_scanned %}
      <label class="font-weight-bold lead">Devices scanned for this client:</label><br><br>
		    {% for scanned in currently_scanned %}
      <a target="_blank" href="/scan?device={{ scanned.device }}&device_owner={{ scanned.device_primary_user }}&devid={{ scanned.serial }}&from_dump=1">
          {{ scanned.device_model }} ({{ scanned.device_primary_user }})
      </a><br>
		    {% endfor %}

	    {% endif %}
	    {% if False %}
            <form id="session_scans" method="GET" action="/view_results">
              <label class="font-weight-bold lead">Devices scanned for this client:<br><br>
                <div class="btn-group-vertical btn-group-toggle" data-toggle="buttons">
		    {% for scanned in currently_scanned %}
		    <label class="btn btn-outline-secondary">
          <input type="radio" name="scan_res" id="{{ scanned.id }}" value="{{ scanned.id }}"
			       autocomplete="off">
                        {{ scanned.device_model }} ({{ scanned.device_primary_user }})
		    </label>
		    {% endfor %}
		</div>
		    <button class="btn btn-group-vertical btn-primary btn-sm">Review Scan Results</button>
	    </form>
	    {% endif %}
        </div>
    </div>
    <div class="col-md-9 border py-2" style="height: 90vh">
        <div id="msg" class="alert alert-primary">  {{ error | safe }}   </div>
        <div class="w-100" style="height: 80vh; overflow: auto;">
            {% if device_name %}
            <label>Scanned: <b>{{ device_name }}</b></label>
  	    <label>Jailbroken or rooted? {{ isrooted | safe }}</label>
            {% endif %}
            <style>
                @media (max-width: 768px) {
                    .applist-table thead {
                        display: none;
                    }
                    .applist-table,
                    .applist-table tbody,
                    .applist-table tr,
                    .applist-table td {
                        display: block;
                        width: 100%;
                    }
                    .applist-table tr {
                        border: 1px solid #e0e0e0;
                        border-radius: 8px;
                        margin-bottom: 12px;
                        padding: 6px 10px;
                        background: #fff;
                    }
                    .applist-table td {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        padding: 6px 0;
                        border: none;
                    }
                    .applist-table td::before {
                        content: attr(data-label);
                        font-weight: 600;
                        color: #555;
                        padding-right: 12px;
                        flex: 0 0 40%;
                    }
                    .applist-table td > * {
                        flex: 1 1 60%;
                        text-align: right;
                    }
                }
            </style>
            <table class="table table-bordered w-100 applist-table">
                <thead>
                    <tr class="something">
                        <th class="col-md-1" style="width: 3%">Uninstall?</th>
                        <th class="col-md-2" style="width: 23%">App Name</th>
                        <th class="col-md-2" style="width: 23%">App ID</th>
                        <th class="col-md-2" style="width: 20%">Flags</th>
                        <th class="col-md-1" style="width: 8%">Score</th>
                        <th class="col-md-1" style="width: 8%">Class</th>
                    </tr>
                </thead>
                <form style="font-size: 76px;" id="form-applist" onsubmit="" method="post" name="form-applist" >
                    <tbody id="applist" class="h-100">
                        {% set app_items = apps_sorted if apps_sorted is defined else apps.items() %}
                        {% for appId, info in app_items %}
                        <tr id="{{ appId.replace('.', '-') }}">
                            {% if appId in sysapps %}
                            <td align="center" data-label="Uninstall"><a class="h4" onclick="" href="javascript:;" data-toggle="tooltip"
                                                   title="System App! Cannot delete">&otimes;</a></td>
                            {%  else %}
                            <td align="center" data-label="Uninstall"><a class="h4" onclick="delete_app('{{ appId }}', this)" href="javascript:;" data-toggle="tooltip"
                                                  title="Delete app">&otimes;</a></td>
                            {% endif %}
                            {% if info['title'] %}
                            <td data-label="App Name"><a href="/details/app/{{ device }}?appId={{ appId }}&serial={{ serial }}" target="_blank" rel="noopener"
		                   class="text text-dark">{{ info['title'] }}</a></td>
                            {% else %}
                            <td data-label="App Name"><a href="/details/app/{{ device }}?appId={{ appId }}&serial={{ serial }}" target="_blank" rel="noopener"
                                   class="text text-dark"> &lt;Unknown&gt;</a></td>
                            {% endif %}
                            <td data-label="App ID"><a class="{{ info.class_ }} appid" href="https://www.google.com/search?q={{ appId }}"
                                   target="_blank" rel="noopener"><code>{{ appId }}</code></a></td>
                            <td data-label="Flags">{{ info['html_flags'] | safe }}</td>
                            <td data-label="Score">{{ '%.2f'|format(info['score']) if info['score'] is not none else '' }}</td>
                            <td data-label="Class">{{ info['class_'] }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </form>
            </table>
            <!-- <button onclick="postform(this)" id="btn-submit"
                 class="btn btn-primary btn-lg">Submit</button> -->
        </div>
        <div class="progress">
            <div id='scan-prog' class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar"
                 aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
            </div>
        </div>
    </div>
</div>
