/* Self-hosted home view — scan form + recent history.
   Shown when NOT in demo mode. Demo mode uses LandingView instead. */
const HomeView = {
    async render() {
        const app = document.getElementById('app');
        let history = [];
        try {
            history = await complyApi.getHistory();
        } catch (e) { /* empty is fine */ }

        const hasScans = history.length > 0;
        const frameworks = await complyApi.getFrameworks();
        const fwOptions = frameworks.map(f =>
            `<option value="${f.id}">${f.label || f.id}</option>`
        ).join('');

        app.innerHTML = `
        <div class="home-container">
            <div class="home-header">
                <h1>Comply</h1>
                <p class="home-subtitle">Compliance gap analysis for your codebase</p>
            </div>

            <div class="home-scan card">
                <h2>New Scan</h2>
                <form id="home-scan-form" class="home-scan-form">
                    <div class="form-row">
                        <div class="form-group" style="flex:3">
                            <label for="home-target">Repository or path</label>
                            <input type="text" id="home-target" placeholder="/path/to/repo or https://github.com/org/repo" required />
                        </div>
                        <div class="form-group" style="flex:1">
                            <label for="home-framework">Framework</label>
                            <select id="home-framework">${fwOptions}</select>
                        </div>
                        <div class="form-group" style="flex:1">
                            <label for="home-depth">Depth</label>
                            <select id="home-depth">
                                <option value="structure">Structure</option>
                                <option value="content" selected>Content</option>
                                <option value="semantic">Semantic</option>
                            </select>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary" id="home-scan-btn">Scan</button>
                </form>
                <div id="home-scan-progress" style="display:none">
                    <div class="loading"><span class="spinner"></span> <span id="home-scan-status">Scanning...</span></div>
                </div>
            </div>

            ${hasScans ? this._renderRecentScans(history) : this._renderWelcome()}
        </div>`;

        this._bindEvents();
    },

    _renderWelcome() {
        return `
        <div class="home-welcome card">
            <h2>Getting Started</h2>
            <div class="home-steps">
                <div class="home-step">
                    <span class="step-num">1</span>
                    <div>
                        <strong>Scan a repo</strong>
                        <p>Enter a local path or GitHub URL above. Structure scans are free and take 30-60 seconds.</p>
                    </div>
                </div>
                <div class="home-step">
                    <span class="step-num">2</span>
                    <div>
                        <strong>Review findings</strong>
                        <p>See per-control status (met/partial/gap) with evidence from your code.</p>
                    </div>
                </div>
                <div class="home-step">
                    <span class="step-num">3</span>
                    <div>
                        <strong>Fix and rescan</strong>
                        <p>Follow the remediation roadmap, then rescan to track progress.</p>
                    </div>
                </div>
            </div>
            <div class="home-tip">
                <strong>Tip:</strong> For semantic depth, set your LLM API key:
                <code>bespoketracker-comply config set llm_api_key sk-...</code>
            </div>
        </div>`;
    },

    _renderRecentScans(history) {
        const rows = history.slice(0, 10).map(s => {
            const score = s.score != null ? `${Math.round(s.score)}%` : '-';
            const repo = (s.repo_url || s.repo_path || '').replace(/.*\//, '.../')
            const date = (s.created_at || '').slice(0, 10);
            return `<tr class="clickable-row" data-scan-id="${s.id}">
                <td>${repo}</td>
                <td>${s.framework || '-'}</td>
                <td>${score}</td>
                <td>${s.scan_depth || '-'}</td>
                <td>${date}</td>
            </tr>`;
        }).join('');

        return `
        <div class="home-history card">
            <div class="home-history-header">
                <h2>Recent Scans</h2>
                <a href="#/history" class="btn btn-sm btn-secondary">View All</a>
            </div>
            <table class="table">
                <thead>
                    <tr><th>Repository</th><th>Framework</th><th>Score</th><th>Depth</th><th>Date</th></tr>
                </thead>
                <tbody>${rows}</tbody>
            </table>
        </div>`;
    },

    _bindEvents() {
        const form = document.getElementById('home-scan-form');
        if (form) form.addEventListener('submit', (e) => {
            e.preventDefault();
            this._runScan();
        });

        // Clickable history rows
        document.querySelectorAll('.clickable-row').forEach(row => {
            row.addEventListener('click', () => {
                const id = row.dataset.scanId;
                if (id) Router.navigate(`/detail/${id}`);
            });
        });
    },

    async _runScan() {
        const target = document.getElementById('home-target').value.trim();
        const framework = document.getElementById('home-framework').value;
        const depth = document.getElementById('home-depth').value;
        if (!target) return;

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

        try {
            const res = await complyApi.startScan(target, framework, depth);
            const scanId = res.scan_id || res.scanId;
            if (!scanId) throw new Error('No scan ID returned');

            // Poll for completion
            let poll;
            const check = async () => {
                try {
                    const s = await complyApi.getScanProgress(scanId);
                    status.textContent = s.message || s.status || 'Scanning...';
                    if (s.status === 'complete') {
                        clearInterval(poll);
                        Router.navigate(`/detail/${scanId}`);
                    } else if (s.status === 'error') {
                        clearInterval(poll);
                        status.textContent = s.error || 'Scan failed';
                        btn.disabled = false;
                    }
                } catch (e) {
                    // might not be ready yet
                }
            };
            poll = setInterval(check, 2000);
            check();
        } catch (e) {
            status.textContent = e.message || 'Scan failed';
            btn.disabled = false;
        }
    }
};
