{% extends "base.html" %}

{% block title %}Audyt SEO - {{ company.name }} - Norda Biznes Hub{% endblock %}

{% block extra_css %}
<style>
    .audit-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: var(--spacing-xl);
        flex-wrap: wrap;
        gap: var(--spacing-md);
    }

    .audit-header-info h1 {
        font-size: var(--font-size-2xl);
        color: var(--text-primary);
        margin-bottom: var(--spacing-xs);
    }

    .audit-header-info p {
        color: var(--text-secondary);
        font-size: var(--font-size-sm);
    }

    .data-source-info {
        display: inline-flex;
        align-items: center;
        gap: var(--spacing-xs);
        margin-top: var(--spacing-sm);
        padding: var(--spacing-xs) var(--spacing-sm);
        background: var(--success-light, #dcfce7);
        border-radius: var(--radius);
        font-size: var(--font-size-sm);
        color: var(--success, #16a34a);
    }

    .header-actions {
        display: flex;
        gap: var(--spacing-sm);
        align-items: center;
    }

    /* Score Section */
    .score-section {
        display: grid;
        grid-template-columns: auto 1fr;
        gap: var(--spacing-xl);
        margin-bottom: var(--spacing-xl);
        background: var(--surface);
        padding: var(--spacing-xl);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow);
    }

    @media (max-width: 768px) {
        .score-section {
            grid-template-columns: 1fr;
            text-align: center;
        }
    }

    .score-circle {
        width: 180px;
        height: 180px;
        border-radius: 50%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        position: relative;
        background: conic-gradient(
            var(--score-color, var(--secondary)) calc(var(--score-percent, 0) * 3.6deg),
            #e2e8f0 0deg
        );
        margin: 0 auto;
    }

    .score-circle::before {
        content: '';
        position: absolute;
        width: 150px;
        height: 150px;
        border-radius: 50%;
        background: var(--surface);
    }

    .score-value {
        position: relative;
        z-index: 1;
        font-size: 3rem;
        font-weight: 700;
        line-height: 1;
    }

    /* Unified 5-level color scale: 0-29 red, 30-49 orange, 50-69 amber, 70-89 lime, 90-100 green */
    .score-value.score-excellent { color: #10b981; }
    .score-value.score-good { color: #84cc16; }
    .score-value.score-average { color: #f59e0b; }
    .score-value.score-needs-work { color: #f97316; }
    .score-value.score-poor { color: #ef4444; }

    .score-label {
        position: relative;
        z-index: 1;
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        margin-top: var(--spacing-xs);
    }

    .score-details {
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .score-category {
        font-size: var(--font-size-xl);
        font-weight: 600;
        margin-bottom: var(--spacing-sm);
    }

    /* Unified 5-level color scale */
    .score-category.excellent { color: #10b981; }
    .score-category.good { color: #84cc16; }
    .score-category.average { color: #f59e0b; }
    .score-category.needs-work { color: #f97316; }
    .score-category.poor { color: #ef4444; }

    .score-description {
        color: var(--text-secondary);
        line-height: 1.6;
        margin-bottom: var(--spacing-md);
    }

    .audit-meta {
        display: flex;
        gap: var(--spacing-lg);
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        flex-wrap: wrap;
    }

    .audit-meta-item {
        display: flex;
        align-items: center;
        gap: var(--spacing-xs);
    }

    /* Metrics Grid */
    .metrics-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
        gap: var(--spacing-md);
        margin-bottom: var(--spacing-xl);
    }

    .metric-card {
        background: var(--surface);
        border-radius: var(--radius-lg);
        padding: var(--spacing-lg);
        box-shadow: var(--shadow-sm);
        text-align: center;
        border-left: 4px solid var(--border);
    }

    .metric-card.good { border-left-color: var(--success); }
    .metric-card.medium { border-left-color: var(--warning); }
    .metric-card.poor { border-left-color: var(--error); }
    .metric-card.none { border-left-color: var(--border); }

    .metric-icon {
        width: 48px;
        height: 48px;
        margin: 0 auto var(--spacing-sm);
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .metric-icon.good { background: #dcfce7; color: #16a34a; }
    .metric-icon.medium { background: #fef3c7; color: #d97706; }
    .metric-icon.poor { background: #fee2e2; color: #dc2626; }
    .metric-icon.none { background: var(--bg-tertiary); color: var(--text-tertiary); }

    .metric-name {
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        margin-bottom: var(--spacing-xs);
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .metric-value {
        font-size: var(--font-size-2xl);
        font-weight: 700;
    }

    .metric-value.good { color: var(--success); }
    .metric-value.medium { color: var(--warning); }
    .metric-value.poor { color: var(--error); }
    .metric-value.none { color: var(--text-tertiary); }

    /* No Audit State */
    .no-audit-state {
        text-align: center;
        padding: var(--spacing-2xl);
        background: var(--surface);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow);
    }

    .no-audit-state svg {
        width: 80px;
        height: 80px;
        color: var(--text-secondary);
        opacity: 0.5;
        margin-bottom: var(--spacing-md);
    }

    .no-audit-state h2 {
        font-size: var(--font-size-xl);
        color: var(--text-primary);
        margin-bottom: var(--spacing-sm);
    }

    .no-audit-state p {
        color: var(--text-secondary);
        margin-bottom: var(--spacing-lg);
    }

    /* Section Title */
    .section-title {
        font-size: var(--font-size-xl);
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: var(--spacing-md);
        display: flex;
        align-items: center;
        gap: var(--spacing-sm);
    }

    /* Breadcrumb */
    .breadcrumb {
        display: flex;
        align-items: center;
        gap: var(--spacing-sm);
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        margin-bottom: var(--spacing-md);
    }

    .breadcrumb a {
        color: var(--primary);
        text-decoration: none;
    }

    .breadcrumb a:hover {
        text-decoration: underline;
    }

    .breadcrumb-separator {
        color: var(--border);
    }

    /* Loading Overlay */
    .loading-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.95);
        z-index: 1000;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        gap: var(--spacing-lg);
    }

    .loading-overlay.active {
        display: flex;
    }

    .loading-content {
        background: var(--surface);
        padding: var(--spacing-xl);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-lg);
        max-width: 400px;
        width: 90%;
        text-align: center;
    }

    .loading-spinner {
        width: 48px;
        height: 48px;
        border: 4px solid var(--border);
        border-top-color: var(--primary);
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto var(--spacing-md);
    }

    @keyframes spin {
        to { transform: rotate(360deg); }
    }

    /* Modal */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 1000;
        align-items: center;
        justify-content: center;
    }

    .modal.active {
        display: flex;
    }

    .modal-content {
        background: var(--surface);
        padding: var(--spacing-xl);
        border-radius: var(--radius-lg);
        max-width: 480px;
        width: 90%;
        box-shadow: var(--shadow-lg);
    }

    .modal-header {
        display: flex;
        align-items: center;
        gap: var(--spacing-md);
        margin-bottom: var(--spacing-md);
    }

    .modal-icon {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .modal-icon.success { background: #dcfce7; color: #16a34a; }
    .modal-icon.info { background: #dbeafe; color: #2563eb; }

    .modal-title {
        font-size: var(--font-size-xl);
        font-weight: 600;
    }

    .modal-body {
        color: var(--text-secondary);
        margin-bottom: var(--spacing-lg);
    }

    .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: var(--spacing-sm);
    }

    /* Website URL display */
    .website-url {
        display: inline-flex;
        align-items: center;
        gap: var(--spacing-xs);
        padding: var(--spacing-xs) var(--spacing-sm);
        background: var(--bg-tertiary);
        border-radius: var(--radius);
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        margin-top: var(--spacing-sm);
    }

    .website-url a {
        color: var(--primary);
        text-decoration: none;
    }

    .website-url a:hover {
        text-decoration: underline;
    }
</style>
{% endblock %}

{% block content %}
<!-- Breadcrumb -->
<div class="breadcrumb">
    <a href="{{ url_for('index') }}">Firmy</a>
    <span class="breadcrumb-separator">/</span>
    <a href="{{ url_for('company_detail', company_id=company.id) }}">{{ company.name }}</a>
    <span class="breadcrumb-separator">/</span>
    <span>Audyt SEO</span>
</div>

<div class="audit-header">
    <div class="audit-header-info">
        <h1>Audyt SEO Strony WWW</h1>
        <p>{{ company.name }}</p>
        <div class="data-source-info">
            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
            </svg>
            <span>Analiza SEO i wydajnosci strony WWW (Google PageSpeed Insights)</span>
        </div>
        {% if company.website %}
        <div class="website-url">
            <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"/>
            </svg>
            <a href="{{ company.website }}" target="_blank" rel="noopener">{{ company.website }}</a>
        </div>
        {% endif %}
    </div>
    <div class="header-actions">
        <a href="{{ url_for('company_detail', company_id=company.id) }}" class="btn btn-outline btn-sm">
            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
            </svg>
            Profil firmy
        </a>
        {% if can_audit and company.website %}
        <button class="btn btn-primary btn-sm" onclick="runAudit()" id="runAuditBtn">
            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
            </svg>
            Uruchom audyt
        </button>
        {% endif %}
    </div>
</div>

{% if seo_data %}
<!-- Score Section -->
{# Unified 5-level color scale: 0-29 red, 30-49 orange, 50-69 amber, 70-89 lime, 90-100 green #}
{% set score = seo_data.seo_score or 0 %}
<div class="score-section">
    <div class="score-circle" style="--score-percent: {{ score }}; --score-color: {% if score >= 90 %}#10b981{% elif score >= 70 %}#84cc16{% elif score >= 50 %}#f59e0b{% elif score >= 30 %}#f97316{% else %}#ef4444{% endif %};">
        <span class="score-value" style="color: {% if score >= 90 %}#10b981{% elif score >= 70 %}#84cc16{% elif score >= 50 %}#f59e0b{% elif score >= 30 %}#f97316{% else %}#ef4444{% endif %};">{{ score }}</span>
        <span class="score-label">/ 100</span>
    </div>
    <div class="score-details">
        <div class="score-category" style="color: {% if score >= 90 %}#10b981{% elif score >= 70 %}#84cc16{% elif score >= 50 %}#f59e0b{% elif score >= 30 %}#f97316{% else %}#ef4444{% endif %};">
            {% if score >= 90 %}
            Doskonaly wynik SEO
            {% elif score >= 70 %}
            Dobry wynik SEO
            {% elif score >= 50 %}
            Przecietny wynik SEO
            {% elif score >= 30 %}
            Wynik SEO wymaga poprawy
            {% else %}
            Slaby wynik SEO
            {% endif %}
        </div>
        <p class="score-description">
            {% if score >= 90 %}
            Strona jest bardzo dobrze zoptymalizowana pod katem SEO. Utrzymuj wysoki standard i monitoruj zmiany.
            {% elif score >= 70 %}
            Strona ma dobra optymalizacje SEO, ale sa obszary do poprawy. Skup sie na wydajnosci i dostepnosci.
            {% elif score >= 50 %}
            Strona wymaga pracy nad optymalizacja SEO. Warto poprawic wydajnosc i dostepnosc.
            {% else %}
            Strona ma powazne problemy z SEO. Priorytetowo popraw wydajnosc i optymalizacje.
            {% endif %}
        </p>
        <div class="audit-meta">
            <div class="audit-meta-item">
                <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                </svg>
                <span>Ostatni audyt: {{ seo_data.audited_at.strftime('%d.%m.%Y %H:%M') if seo_data.audited_at else 'Brak danych' }}</span>
            </div>
            {% if seo_data.url %}
            <div class="audit-meta-item">
                <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/>
                </svg>
                <span>{{ seo_data.url|truncate(40) }}</span>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- Metrics Grid -->
<h2 class="section-title">
    <svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/>
    </svg>
    Szczegolowe metryki
</h2>

<div class="metrics-grid">
    <!-- SEO Score -->
    {% set seo = seo_data.seo_score %}
    {% set seo_class = 'good' if seo and seo >= 90 else ('medium' if seo and seo >= 50 else ('poor' if seo else 'none')) %}
    <div class="metric-card {{ seo_class }}">
        <div class="metric-icon {{ seo_class }}">
            <svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
            </svg>
        </div>
        <div class="metric-name">Wynik SEO</div>
        <div class="metric-value {{ seo_class }}">{{ seo if seo else '-' }}</div>
    </div>

    <!-- Performance -->
    {% set perf = seo_data.performance_score %}
    {% set perf_class = 'good' if perf and perf >= 90 else ('medium' if perf and perf >= 50 else ('poor' if perf else 'none')) %}
    <div class="metric-card {{ perf_class }}">
        <div class="metric-icon {{ perf_class }}">
            <svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
            </svg>
        </div>
        <div class="metric-name">Wydajnosc</div>
        <div class="metric-value {{ perf_class }}">{{ perf if perf else '-' }}</div>
    </div>

    <!-- Accessibility -->
    {% set acc = seo_data.accessibility_score %}
    {% set acc_class = 'good' if acc and acc >= 90 else ('medium' if acc and acc >= 50 else ('poor' if acc else 'none')) %}
    <div class="metric-card {{ acc_class }}">
        <div class="metric-icon {{ acc_class }}">
            <svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
            </svg>
        </div>
        <div class="metric-name">Dostepnosc</div>
        <div class="metric-value {{ acc_class }}">{{ acc if acc else '-' }}</div>
    </div>

    <!-- Best Practices -->
    {% set bp = seo_data.best_practices_score %}
    {% set bp_class = 'good' if bp and bp >= 90 else ('medium' if bp and bp >= 50 else ('poor' if bp else 'none')) %}
    <div class="metric-card {{ bp_class }}">
        <div class="metric-icon {{ bp_class }}">
            <svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
        </div>
        <div class="metric-name">Best Practices</div>
        <div class="metric-value {{ bp_class }}">{{ bp if bp else '-' }}</div>
    </div>
</div>

{% else %}
<!-- No Audit State -->
<div class="no-audit-state">
    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
    </svg>
    <h2>Brak danych audytu SEO</h2>
    {% if company.website %}
    <p>Nie przeprowadzono jeszcze audytu SEO dla strony tej firmy. Uruchom audyt, aby sprawdzic optymalizacje strony.</p>
    {% if can_audit %}
    <button class="btn btn-primary" onclick="runAudit()">
        <svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
        </svg>
        Uruchom pierwszy audyt
    </button>
    {% endif %}
    {% else %}
    <p>Ta firma nie ma zdefiniowanej strony WWW. Dodaj adres strony w profilu firmy, aby moc przeprowadzic audyt SEO.</p>
    <a href="{{ url_for('company_detail', company_id=company.id) }}" class="btn btn-outline">
        Przejdz do profilu firmy
    </a>
    {% endif %}
</div>
{% endif %}

<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-content">
        <div class="loading-spinner"></div>
        <h3>Analiza SEO w toku...</h3>
        <p>Pobieranie danych z Google PageSpeed Insights. Moze to potrwac do 30 sekund.</p>
    </div>
</div>

<!-- Info Modal -->
<div class="modal" id="infoModal">
    <div class="modal-content">
        <div class="modal-header">
            <div class="modal-icon success" id="modalIcon">
                <svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                </svg>
            </div>
            <div class="modal-title" id="modalTitle">Informacja</div>
        </div>
        <div class="modal-body" id="modalBody">
            Tresc informacji.
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" onclick="closeInfoModal()">OK</button>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
const csrfToken = '{{ csrf_token() }}';
const companySlug = '{{ company.slug }}';

function showLoading() {
    document.getElementById('loadingOverlay').classList.add('active');
}

function hideLoading() {
    document.getElementById('loadingOverlay').classList.remove('active');
}

function showInfoModal(title, body, isSuccess) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').textContent = body;
    const icon = document.getElementById('modalIcon');
    icon.className = 'modal-icon ' + (isSuccess ? 'success' : 'info');
    document.getElementById('infoModal').classList.add('active');
}

function closeInfoModal() {
    document.getElementById('infoModal').classList.remove('active');
}

document.getElementById('infoModal')?.addEventListener('click', (e) => {
    if (e.target.id === 'infoModal') closeInfoModal();
});

async function runAudit() {
    const btn = document.getElementById('runAuditBtn');
    if (btn) {
        btn.disabled = true;
    }
    showLoading();

    try {
        const response = await fetch('/api/seo/audit', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify({ slug: companySlug })
        });

        const data = await response.json();

        hideLoading();

        if (response.ok && data.success) {
            showInfoModal('Audyt zakonczony', 'Audyt SEO zostal zakonczony pomyslnie. Strona zostanie odswiezona.', true);
            setTimeout(() => location.reload(), 1500);
        } else {
            showInfoModal('Blad', data.error || 'Wystapil nieznany blad podczas audytu.', false);
            if (btn) btn.disabled = false;
        }
    } catch (error) {
        hideLoading();
        showInfoModal('Blad polaczenia', 'Nie udalo sie polaczyc z serwerem: ' + error.message, false);
        if (btn) btn.disabled = false;
    }
}
{% endblock %}
