{% extends 'base.html' %}

{% block content %}
<style>
@keyframes blink-fade {
  0% { background-color: rgba(255, 193, 7, 0.4); box-shadow: 0 0 15px rgba(255, 193, 7, 0.6); }
  50% { background-color: rgba(255, 193, 7, 0); box-shadow: 0 0 0 rgba(255, 193, 7, 0); }
  100% { background-color: rgba(255, 193, 7, 0.4); box-shadow: 0 0 15px rgba(255, 193, 7, 0.6); }
}
.animate-blink {
  animation: blink-fade 0.8s ease-in-out 4;
  border: 2px solid #ffc107 !important;
  border-radius: 8px;
}
.transition-style {
  transition: all 0.3s ease;
}
</style>
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><i class="bi bi-file-earmark-plus text-primary me-2"></i>{{ _('Prepare Print') }}</h1>
    <div>
        <button type="button" class="btn btn-outline-primary btn-sm rounded shadow-sm fw-bold" onclick="document.getElementById('gcodeUploadInput').click();">
            <i class="bi bi-upload me-1"></i>{{ _('Upload External GCode') }}
        </button>
        <input type="file" id="gcodeUploadInput" style="display: none;" accept=".gcode,.gco,.g" onchange="uploadExternalGcode(this)">
    </div>
</div>

{% if error %}
<div class="alert alert-danger" role="alert">
    <i class="bi bi-exclamation-triangle me-2"></i>{{ error }}
</div>
{% else %}
<div class="card shadow-sm">
    <div class="card-header bg-light fw-bold text-secondary">
        <i class="bi bi-card-text me-1"></i>{{ _('Available Files on Printer') }}
    </div>
    <div class="list-group list-group-flush">
        {% for f in files %}
            {% if f.type == 'machinecode' %}
            <div id="file-{{ f.id }}" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center py-3 transition-style">
                <div class="me-auto text-truncate" style="max-width: 80%;">
                    <h6 class="mb-1"><i class="bi bi-file-earmark-code text-primary me-2"></i>{{ f.name }}</h6>
                    <small class="text-muted d-block">{{ _('Size:') }} {{ f.size }} bytes, {{ _('Time:') }} {{ f.gcodeAnalysis.estimatedPrintTime if f.gcodeAnalysis else 'Unknown' }}s</small>
                </div>
                <div>
                    <a href="{{ url_for('main.preview_gcode', file_id=f.id) }}" class="btn btn-sm btn-outline-info rounded-pill px-3 shadow-sm me-2"><i class="bi bi-eye me-1"></i>{{ _('Preview') }}</a>
                    <button class="btn btn-sm btn-outline-success rounded-pill px-3 shadow-sm" onclick="printFile('{{ f.origin }}', '{{ f.path }}')"><i class="bi bi-play-fill me-1"></i>{{ _('Print Now') }}</button>
                    <!-- <button class="btn btn-sm btn-outline-secondary rounded-pill ms-2" onclick="selectFile('{{ f.origin }}', '{{ f.path }}')">{{ _('Select') }}</button> -->
                </div>
            </div>
            {% endif %}
        {% else %}
            <div class="list-group-item text-center py-5 text-muted">
                <i class="bi bi-inbox display-4 d-block mb-3"></i>
                <p>{{ _('No printable files found. Go slice some G-Code first!') }}</p>
            </div>
        {% endfor %}
    </div>
</div>

<script>
function printFile(origin, path) {
    window.customConfirm("{{ _('Send this file to print immediately?') }}<br><small>" + path + "</small>", () => {
        fetch('{{ url_for("printer.api_print_file") }}', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ origin: origin, path: path })
        })
        .then(response => response.json())
        .then(data => {
            if(data.success) {
                window.showToast("{{ _('Print starting! Going to dashboard...') }}", "success");
                setTimeout(() => {
                    window.location.href = "{{ url_for('printer.status') }}";
                }, 1500);
            } else {
                window.customAlert("Error: " + data.error);
            }
        })
        .catch(err => window.customAlert("Error: " + err));
    });
}

function uploadExternalGcode(input) {
    if (!input.files || input.files.length === 0) return;
    
    let file = input.files[0];
    let formData = new FormData();
    formData.append('file', file);
    
    window.showToast("{{ _('Uploading and linking GCode...') }}", "info");
    let btn = document.querySelector('button[onclick="document.getElementById(\'gcodeUploadInput\').click();"]');
    let oldBtnHtml = btn.innerHTML;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Upload/Sync...';
    btn.disabled = true;
    
    fetch("{{ url_for('printer.upload_gcode') }}", {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if(data.success) {
            window.location.reload();
        } else {
            window.customAlert("Upload failed: " + data.error);
            btn.innerHTML = oldBtnHtml;
            btn.disabled = false;
        }
    }).catch(e => {
        window.customAlert("Error: " + e);
        btn.innerHTML = oldBtnHtml;
        btn.disabled = false;
    });
}

window.addEventListener('DOMContentLoaded', (event) => {
    if(window.location.hash) {
        let el = document.querySelector(window.location.hash);
        if(el) {
            setTimeout(() => {
                el.scrollIntoView({ behavior: 'smooth', block: 'center' });
                el.classList.add('animate-blink');
                
                // fallback to remove class later
                setTimeout(() => el.classList.remove('animate-blink'), 3500);
            }, 300);
        }
    }
});
</script>
{% endif %}
{% endblock %}