<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GEO Optimizer — AI Search Visibility Audit</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
background:#0f172a;color:#e2e8f0;min-height:100vh;display:flex;flex-direction:column;
align-items:center;justify-content:center;padding:2rem}
.container{max-width:600px;width:100%;text-align:center}
h1{font-size:2.5rem;margin-bottom:.5rem;background:linear-gradient(135deg,#60a5fa,#a78bfa);
-webkit-background-clip:text;-webkit-text-fill-color:transparent}
.subtitle{color:#94a3b8;margin-bottom:2rem;font-size:1.1rem}
.form-group{display:flex;gap:.5rem;margin-bottom:1.5rem}
input[type="url"]{flex:1;padding:.75rem 1rem;border:2px solid #334155;border-radius:8px;
background:#1e293b;color:#e2e8f0;font-size:1rem;outline:none;transition:border-color .2s}
input[type="url"]:focus{border-color:#60a5fa}
button{padding:.75rem 1.5rem;border:none;border-radius:8px;background:#3b82f6;
color:#fff;font-size:1rem;font-weight:600;cursor:pointer;transition:background .2s}
button:hover{background:#2563eb}
button:disabled{opacity:.5;cursor:not-allowed}
.result{background:#1e293b;border-radius:12px;padding:1.5rem;margin-top:1rem;
text-align:left;display:none}
.score-display{text-align:center;margin:1rem 0}
.score-number{font-size:3rem;font-weight:700}
.score-band{font-size:1.2rem;font-weight:600;margin-top:.25rem}
.checks{margin:1rem 0}
.check-row{display:flex;justify-content:space-between;padding:.5rem 0;
border-bottom:1px solid #334155}
.recs{margin-top:1rem}
.recs li{margin:.25rem 0;color:#94a3b8}
.links{margin-top:2rem;color:#64748b;font-size:.85rem}
.links a{color:#60a5fa;text-decoration:none}
.spinner{display:none;margin:1rem auto}
.spinner.active{display:block}
.error{color:#ef4444;margin-top:1rem;display:none}
.report-link{margin-top:1rem;text-align:center}
.report-link a{color:#60a5fa;text-decoration:none;font-size:.9rem}
.stats{display:flex;justify-content:center;gap:1.5rem;margin-bottom:1.5rem;flex-wrap:wrap}
.stat{background:#1e293b;padding:.4rem .8rem;border-radius:6px;font-size:.85rem;color:#94a3b8}
</style>
</head>
<body>
<div class="container">
    <nav style="text-align:center;margin-bottom:1.5rem">
        <a href="/" style="color:#60a5fa;text-decoration:none;margin:0 .75rem;font-size:.9rem">Audit</a>
        <a href="/roadmap" style="color:#60a5fa;text-decoration:none;margin:0 .75rem;font-size:.9rem">Roadmap</a>
        <a href="/research" style="color:#60a5fa;text-decoration:none;margin:0 .75rem;font-size:.9rem">Research</a>
        <a href="/compare" style="color:#60a5fa;text-decoration:none;margin:0 .75rem;font-size:.9rem">Compare</a>
        <a href="/docs/" style="color:#60a5fa;text-decoration:none;margin:0 .75rem;font-size:.9rem">Docs</a>
    </nav>
    <h1>GEO Optimizer</h1>
    <p class="subtitle">Audit your website's visibility to AI search engines</p>

    <div class="form-group">
        <input type="url" id="url-input" placeholder="https://example.com" required>
        <button id="btn">Audit</button>
    </div>

    <div class="spinner" id="spinner">Analyzing...</div>
    <div class="error" id="error"></div>

    <div class="result" id="result">
        <div class="score-display">
            <div class="score-number" id="score"></div>
            <div class="score-band" id="band"></div>
        </div>
        <div class="checks" id="checks"></div>
        <div class="recs"><ol id="recs"></ol></div>
        <div class="report-link" id="report-link"></div>
    </div>

    <div class="stats" id="stats-bar">
        <span class="stat" id="stat-stars">⭐ <span id="stars-count">—</span> stars</span>
        <span class="stat" id="stat-downloads">📦 <span id="downloads-count">—</span> downloads/mo</span>
        <span class="stat" id="stat-audits">🔍 <span id="audits-count">—</span> audits run</span>
    </div>

    <div class="links">
        <p>CLI: <code>pip install geo-optimizer-skill</code></p>
        <p><a href="https://github.com/auriti-labs/geo-optimizer-skill">GitHub</a> &middot;
           <a href="/docs">API Docs</a> &middot;
           <a href="https://github.com/auriti-labs/geo-optimizer-skill/issues">Issues</a></p>
    </div>
</div>

<script__NONCE_ATTR__>
async function runAudit() {
    const url = document.getElementById('url-input').value;
    if (!url) return;

    const btn = document.getElementById('btn');
    const spinner = document.getElementById('spinner');
    const errorEl = document.getElementById('error');
    const resultEl = document.getElementById('result');

    btn.disabled = true;
    spinner.classList.add('active');
    errorEl.style.display = 'none';
    resultEl.style.display = 'none';

    try {
        const res = await fetch('/api/audit?url=' + encodeURIComponent(url));
        const data = await res.json();

        if (!res.ok) {
            throw new Error(data.detail || 'Errore audit');
        }

        const colors = {excellent:'#22c55e',good:'#06b6d4',foundation:'#eab308',critical:'#ef4444'};
        const color = colors[data.band] || '#888';

        // Usa textContent per prevenire XSS
        const scoreEl = document.getElementById('score');
        scoreEl.textContent = data.score + '/100';
        scoreEl.style.color = color;

        const bandEl = document.getElementById('band');
        bandEl.textContent = data.band.toUpperCase();
        bandEl.style.color = color;

        // Costruisci check rows con metodi DOM sicuri
        const checksEl = document.getElementById('checks');
        checksEl.textContent = '';
        const checkNames = {robots_txt:'Robots.txt',llms_txt:'llms.txt',
            schema_jsonld:'Schema JSON-LD',meta_tags:'Meta Tags',content:'Content Quality'};
        const checks = data.checks;
        for (const [key, label] of Object.entries(checkNames)) {
            const c = checks[key];
            const ok = key === 'robots_txt' ? c.citation_bots_ok :
                       key === 'llms_txt' ? c.found :
                       key === 'schema_jsonld' ? c.has_website :
                       key === 'meta_tags' ? (c.has_title && c.has_description) :
                       c.has_h1;
            const row = document.createElement('div');
            row.className = 'check-row';
            const nameSpan = document.createElement('span');
            nameSpan.textContent = label;
            const statusSpan = document.createElement('span');
            statusSpan.textContent = ok ? '\u2705' : '\u274c';
            row.appendChild(nameSpan);
            row.appendChild(statusSpan);
            checksEl.appendChild(row);
        }

        // Raccomandazioni con metodi DOM sicuri
        const recsEl = document.getElementById('recs');
        recsEl.textContent = '';
        for (const rec of data.recommendations) {
            const li = document.createElement('li');
            li.textContent = rec;
            recsEl.appendChild(li);
        }

        // Link report con metodi DOM sicuri
        const reportLinkEl = document.getElementById('report-link');
        reportLinkEl.textContent = '';
        if (data.report_url) {
            const a = document.createElement('a');
            a.href = data.report_url;
            a.target = '_blank';
            a.rel = 'noopener';
            a.textContent = 'View full HTML report';
            reportLinkEl.appendChild(a);

            // Bottone Download PDF
            const pdfLink = document.createElement('a');
            pdfLink.href = '/api/audit/pdf?url=' + encodeURIComponent(url);
            pdfLink.textContent = '📄 Download PDF';
            pdfLink.style.cssText = 'margin-left:1rem;color:#f59e0b;text-decoration:none;font-size:.9rem';
            reportLinkEl.appendChild(pdfLink);
        }

        resultEl.style.display = 'block';
    } catch (e) {
        errorEl.textContent = e.message;
        errorEl.style.display = 'block';
    } finally {
        btn.disabled = false;
        spinner.classList.remove('active');
    }
}

// Event listener per il bottone Audit (al posto di onclick inline, bloccato dalla CSP)
document.getElementById('btn').addEventListener('click', runAudit);
document.getElementById('url-input').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') runAudit();
});

// Carica le statistiche all'avvio della pagina
(async function loadStats() {
    try {
        const res = await fetch('/api/stats');
        if (!res.ok) return;
        const data = await res.json();
        const fmt = (n) => n >= 1000 ? (n/1000).toFixed(1) + 'k' : String(n);
        document.getElementById('stars-count').textContent = fmt(data.github_stars);
        document.getElementById('downloads-count').textContent = fmt(data.pypi_downloads_month);
        document.getElementById('audits-count').textContent = fmt(data.audits_run);
    } catch (e) { /* silenzioso se le stats non sono disponibili */ }
})();
</script>
</body>
</html>
