/* Scan view — start a new compliance scan */
const ScanView = {
    _pollTimer: null,
    _scanId: null,

    async render() {
        const app = document.getElementById('app');
        let frameworks = [];
        let tier = {};
        try {
            frameworks = await complyApi.getFrameworks();
            tier = await complyApi.getTier();
        } catch (e) { /* use defaults */ }

        const fwOptions = (frameworks || []).map(fw => {
            const id = fw.framework || fw.id || '';
            const label = fw.label || fw.name || id;
            return `<option value="${id}">${label}</option>`;
        }).join('');

        app.innerHTML = `
        <div class="page-header">
            <h2>New Compliance Scan</h2>
            <p>Analyse a codebase against regulatory frameworks</p>
        </div>
        <div class="card" id="scan-form-card">
            <div class="form-group">
                <label>Repository URL or path</label>
                <input class="form-input" id="scan-url" placeholder="https://github.com/org/repo or /path/to/code" autofocus>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Framework</label>
                    <select class="form-select" id="scan-framework">
                        ${fwOptions || '<option value="eu-ai-act">EU AI Act</option>'}
                    </select>
                </div>
                <div class="form-group">
                    <label>Scan Depth</label>
                    <select class="form-select" id="scan-depth">
                        <option value="structure">Structure</option>
                        <option value="content" selected>Content</option>
                        <option value="semantic">Semantic (LLM)</option>
                    </select>
                </div>
            </div>
            <div class="form-group" id="llm-row" style="display:none">
                <label>LLM API Key (for semantic analysis)</label>
                <input class="form-input" type="password" id="scan-llm-key" placeholder="sk-...">
            </div>
            <div class="btn-group">
                <button class="btn btn-primary" id="scan-btn" onclick="ScanView.startScan()">Start Scan</button>
            </div>
        </div>
        <div id="scan-progress" style="display:none">
            <div class="card">
                <div class="card-header">Scan Progress</div>
                <div id="progress-stepper"></div>
                <div id="progress-detail" class="loading"><span class="spinner"></span> Starting...</div>
            </div>
        </div>`;

        document.getElementById('scan-depth').addEventListener('change', (e) => {
            document.getElementById('llm-row').style.display = e.target.value === 'semantic' ? 'block' : 'none';
        });
    },

    async startScan() {
        const url = document.getElementById('scan-url').value.trim();
        if (!url) return;

        const framework = document.getElementById('scan-framework').value;
        const depth = document.getElementById('scan-depth').value;
        const llmKey = document.getElementById('scan-llm-key')?.value || '';

        document.getElementById('scan-btn').disabled = true;
        document.getElementById('scan-progress').style.display = 'block';

        try {
            const result = await complyApi.startScan(url, framework, depth, llmKey);
            this._scanId = result.scanId;
            this._startPolling();
        } catch (e) {
            document.getElementById('progress-detail').innerHTML =
                `<div class="alert alert-error">Error: ${e.message}</div>`;
            document.getElementById('scan-btn').disabled = false;
        }
    },

    _startPolling() {
        const stepMap = {
            pending: 'Clone', cloning: 'Clone', scanning: 'Scan',
            building: 'Build', evaluating: 'Evaluate', complete: 'Done',
        };

        this._pollTimer = setInterval(async () => {
            try {
                const status = await complyApi.getScanStatus(this._scanId);
                const step = stepMap[status.status] || status.status;
                document.getElementById('progress-stepper').innerHTML =
                    Components.renderProgressStepper(null, step);
                document.getElementById('progress-detail').innerHTML =
                    `<span class="spinner"></span> ${status.progress_step || status.status}: ${status.progress_detail || ''}`;

                if (status.status === 'complete') {
                    clearInterval(this._pollTimer);
                    App.setLastResult(this._scanId);
                    Router.navigate(`/detail/${this._scanId}`);
                } else if (status.status === 'error') {
                    clearInterval(this._pollTimer);
                    document.getElementById('progress-detail').innerHTML =
                        `<div class="alert alert-error">${status.error || 'Scan failed'}</div>`;
                    document.getElementById('scan-btn').disabled = false;
                }
            } catch (e) {
                clearInterval(this._pollTimer);
                document.getElementById('progress-detail').innerHTML =
                    `<div class="alert alert-error">Polling error: ${e.message}</div>`;
            }
        }, 2000);
    },
};
