{% extends "base.html" %}

{% block title %}Audyt Google Business Profile - {{ company.name }} - Norda Biznes Partner{% 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(--info-light, #e0f2fe);
        border-radius: var(--radius);
        font-size: var(--font-size-sm);
        color: var(--info, #0284c7);
    }

    .data-source-info svg {
        flex-shrink: 0;
    }

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

    /* Score Display */
    .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);
    }

    /* Fields Section */
    .fields-section {
        margin-bottom: var(--spacing-xl);
    }

    .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);
    }

    .fields-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: var(--spacing-md);
    }

    .field-card {
        background: var(--surface);
        border-radius: var(--radius-lg);
        padding: var(--spacing-md);
        box-shadow: var(--shadow-sm);
        border-left: 4px solid var(--border);
        transition: var(--transition);
    }

    .field-card:hover {
        box-shadow: var(--shadow);
    }

    .field-card.complete {
        border-left-color: var(--success);
    }

    .field-card.partial {
        border-left-color: var(--warning);
    }

    .field-card.missing {
        border-left-color: var(--error);
    }

    .field-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: var(--spacing-sm);
    }

    .field-name {
        font-weight: 600;
        color: var(--text-primary);
        display: flex;
        align-items: center;
        gap: var(--spacing-xs);
    }

    .field-status-badge {
        font-size: 11px;
        font-weight: 500;
        padding: 2px 8px;
        border-radius: var(--radius-sm);
        text-transform: uppercase;
    }

    .field-status-badge.complete {
        background: #dcfce7;
        color: #166534;
    }

    .field-status-badge.partial {
        background: #fef3c7;
        color: #92400e;
    }

    .field-status-badge.missing {
        background: #fee2e2;
        color: #991b1b;
    }

    .field-value {
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        margin-bottom: var(--spacing-sm);
        word-break: break-word;
    }

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

    .field-score-bar {
        flex: 1;
        height: 6px;
        background: var(--border);
        border-radius: 3px;
        overflow: hidden;
    }

    .field-score-fill {
        height: 100%;
        border-radius: 3px;
        transition: width 0.3s ease;
    }

    .field-score-fill.complete { background: var(--success); }
    .field-score-fill.partial { background: var(--warning); }
    .field-score-fill.missing { background: var(--error); }

    .field-score-text {
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        min-width: 60px;
        text-align: right;
    }

    .field-scoring-info.reviews-scoring {
        margin-top: var(--spacing-sm);
        padding: var(--spacing-sm);
        background: var(--bg-tertiary);
        border-radius: var(--radius-sm);
        font-size: var(--font-size-sm);
    }

    .scoring-message {
        display: block;
    }

    .scoring-message.success {
        color: var(--success);
    }

    .scoring-message.hint {
        color: var(--warning);
    }

    .scoring-message.progress {
        color: var(--primary);
    }

    .scoring-breakdown-line {
        margin-top: var(--spacing-xs);
        font-size: var(--font-size-xs);
        color: var(--text-tertiary);
        font-family: monospace;
    }

    /* Recommendations Section */
    .recommendations-section {
        margin-bottom: var(--spacing-xl);
    }

    .recommendation-list {
        display: flex;
        flex-direction: column;
        gap: var(--spacing-sm);
    }

    .recommendation-item {
        background: var(--surface);
        border-radius: var(--radius);
        padding: var(--spacing-md);
        box-shadow: var(--shadow-sm);
        display: flex;
        align-items: flex-start;
        gap: var(--spacing-md);
        transition: var(--transition);
    }

    .recommendation-item:hover {
        box-shadow: var(--shadow);
    }

    .recommendation-priority {
        flex-shrink: 0;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .recommendation-priority.high {
        background: #fee2e2;
        color: var(--error);
    }

    .recommendation-priority.medium {
        background: #fef3c7;
        color: var(--warning);
    }

    .recommendation-priority.low {
        background: #dbeafe;
        color: var(--primary);
    }

    .recommendation-content {
        flex: 1;
    }

    .recommendation-field {
        font-weight: 600;
        font-size: var(--font-size-sm);
        color: var(--text-primary);
        margin-bottom: var(--spacing-xs);
        text-transform: capitalize;
    }

    .recommendation-text {
        color: var(--text-secondary);
        font-size: var(--font-size-sm);
        line-height: 1.5;
    }

    .recommendation-impact {
        flex-shrink: 0;
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        display: flex;
        align-items: center;
        gap: var(--spacing-xs);
    }

    /* Educational Info Section */
    .info-section {
        margin-top: var(--spacing-xl);
        margin-bottom: var(--spacing-xl);
        background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
        border: 1px solid #bfdbfe;
        border-radius: var(--radius-lg);
        padding: var(--spacing-xl);
    }

    .info-section-header {
        display: flex;
        align-items: center;
        gap: var(--spacing-sm);
        margin-bottom: var(--spacing-lg);
    }

    .info-section-header svg {
        width: 24px;
        height: 24px;
        color: #2563eb;
        flex-shrink: 0;
    }

    .info-section-header h3 {
        font-size: var(--font-size-lg);
        color: #1e40af;
        margin: 0;
    }

    .info-cards {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: var(--spacing-md);
        margin-bottom: var(--spacing-lg);
    }

    .info-card {
        background: white;
        border-radius: var(--radius);
        padding: var(--spacing-md);
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }

    .info-card-icon {
        width: 40px;
        height: 40px;
        border-radius: var(--radius);
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: var(--spacing-sm);
    }

    .info-card-icon.search {
        background: #fef3c7;
        color: #d97706;
    }

    .info-card-icon.maps {
        background: #dcfce7;
        color: #16a34a;
    }

    .info-card-icon.manage {
        background: #e0e7ff;
        color: #4f46e5;
    }

    .info-card h4 {
        font-size: var(--font-size-md);
        color: var(--text-primary);
        margin-bottom: var(--spacing-xs);
    }

    .info-card p {
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        line-height: 1.5;
        margin: 0;
    }

    .info-card ul {
        margin: var(--spacing-sm) 0 0 0;
        padding-left: var(--spacing-md);
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
    }

    .info-card ul li {
        margin-bottom: var(--spacing-xs);
    }

    .info-summary {
        background: white;
        border-radius: var(--radius);
        padding: var(--spacing-md);
        display: flex;
        align-items: flex-start;
        gap: var(--spacing-md);
    }

    .info-summary svg {
        width: 20px;
        height: 20px;
        color: #2563eb;
        flex-shrink: 0;
        margin-top: 2px;
    }

    .info-summary p {
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        line-height: 1.6;
        margin: 0;
    }

    .info-summary strong {
        color: var(--text-primary);
    }

    .info-summary a {
        color: #2563eb;
        text-decoration: none;
        font-weight: 500;
    }

    .info-summary a:hover {
        text-decoration: underline;
    }

    /* 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);
    }

    /* Loading State */
    .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-header {
        margin-bottom: var(--spacing-lg);
    }

    .loading-header h3 {
        font-size: var(--font-size-lg);
        color: var(--text-primary);
        margin-bottom: var(--spacing-xs);
    }

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

    .loading-steps {
        text-align: left;
        margin-bottom: var(--spacing-lg);
    }

    .loading-step {
        display: flex;
        align-items: center;
        gap: var(--spacing-sm);
        padding: var(--spacing-sm) 0;
        border-bottom: 1px solid var(--border-light);
    }

    .loading-step.step-detail {
        padding-left: var(--spacing-lg);
        font-size: var(--font-size-xs);
    }

    .loading-step:last-child {
        border-bottom: none;
    }

    .step-icon {
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }

    .step-icon.pending {
        color: var(--text-tertiary);
    }

    .step-icon.in_progress {
        color: var(--primary);
    }

    .step-icon.complete {
        color: var(--success);
    }

    .step-icon.error {
        color: var(--error);
    }

    .step-icon.warning {
        color: var(--warning);
    }

    .step-icon.missing {
        color: var(--text-tertiary);
        opacity: 0.6;
    }

    .step-icon.skipped {
        color: var(--text-tertiary);
        opacity: 0.5;
    }

    .step-spinner {
        width: 18px;
        height: 18px;
        border: 2px solid var(--border);
        border-top-color: var(--primary);
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    .step-text {
        flex: 1;
        font-size: var(--font-size-sm);
    }

    .step-text.pending {
        color: var(--text-tertiary);
    }

    .step-text.in_progress {
        color: var(--text-primary);
        font-weight: 500;
    }

    .step-text.complete {
        color: var(--text-secondary);
    }

    .step-text.error {
        color: var(--error);
    }

    .step-text.missing {
        color: var(--text-tertiary);
        font-style: italic;
    }

    .step-text.skipped {
        color: var(--text-tertiary);
        opacity: 0.6;
    }

    .step-text.warning {
        color: var(--warning);
    }

    /* Source tag styling */
    .source-tag {
        display: inline-block;
        font-size: 9px;
        font-weight: 600;
        padding: 1px 5px;
        border-radius: 3px;
        margin-left: 4px;
        text-transform: uppercase;
        vertical-align: middle;
    }

    .source-tag.google {
        background: #4285f4;
        color: white;
    }

    .source-tag.nordabiz {
        background: var(--primary);
        color: white;
    }

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

    .loading-text {
        color: var(--text-secondary);
        font-size: var(--font-size-lg);
    }

    /* Legend */
    .legend {
        display: flex;
        gap: var(--spacing-lg);
        margin-bottom: var(--spacing-md);
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
        flex-wrap: wrap;
    }

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

    .legend-dot {
        width: 12px;
        height: 12px;
        border-radius: 2px;
    }

    .legend-dot.complete { background: #dcfce7; border: 1px solid #166534; }
    .legend-dot.partial { background: #fef3c7; border: 1px solid #92400e; }
    .legend-dot.missing { background: #fee2e2; border: 1px solid #991b1b; }

    /* 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);
    }

    /* Modal styles */
    .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);
        animation: modalSlideIn 0.2s ease-out;
    }

    @keyframes modalSlideIn {
        from {
            opacity: 0;
            transform: translateY(-20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .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;
        flex-shrink: 0;
    }

    .modal-icon.success {
        background: #dcfce7;
        color: #16a34a;
    }

    .modal-icon.info {
        background: #dbeafe;
        color: #2563eb;
    }

    .modal-icon.warning {
        background: #fef3c7;
        color: #d97706;
    }

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

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

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

    /* Field icons */
    .field-icon {
        width: 16px;
        height: 16px;
        color: var(--text-secondary);
    }

    /* Responsive */
    @media (max-width: 768px) {
        .audit-header {
            flex-direction: column;
        }

        .header-actions {
            width: 100%;
            justify-content: center;
        }

        .fields-grid {
            grid-template-columns: 1fr;
        }

        .recommendation-item {
            flex-direction: column;
        }

        .recommendation-impact {
            align-self: flex-start;
        }
    }
</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 GBP</span>
</div>

<div class="audit-header">
    <div class="audit-header-info">
        <h1>Audyt Google Business Profile</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="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            <span>Analiza kompletnosci wizytowki Google dla lokalnego SEO</span>
        </div>
    </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 audit and (audit.google_maps_url or audit.google_place_id) %}
        {% set gbp_url = audit.google_maps_url if audit.google_maps_url else 'https://www.google.com/maps/search/?api=1&query=Google&query_place_id=' ~ audit.google_place_id %}
        <a href="{{ gbp_url }}" target="_blank" rel="noopener" class="btn btn-outline btn-sm" style="color: #4285f4; border-color: #4285f4;">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
            </svg>
            Zobacz wizytowke Google
        </a>
        {% endif %}
        {% if can_audit %}
        <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 audit %}
<!-- Score Section -->
{# Unified 5-level color scale: 0-29 red, 30-49 orange, 50-69 amber, 70-89 lime, 90-100 green #}
{% set score = audit.completeness_score %}
<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 profil GBP
            {% elif score >= 70 %}
            Dobry profil GBP
            {% elif score >= 50 %}
            Przecietny profil GBP
            {% elif score >= 30 %}
            Profil wymaga uzupelnienia
            {% else %}
            Slaby profil GBP
            {% endif %}
        </div>
        <p class="score-description">
            {% if audit.completeness_score >= 90 %}
            Twoja wizytowka Google jest bardzo dobrze zoptymalizowana. Utrzymaj wysoki standard i monitoruj opinie klientow.
            {% elif audit.completeness_score >= 70 %}
            Profil jest w dobrym stanie, ale sa obszary do poprawy. Skupienie sie na rekomendacjach zwiekszy widocznosc.
            {% elif audit.completeness_score >= 50 %}
            Wizytowka wymaga uzupelnienia. Wdrozenie ponizszych rekomendacji znaczaco poprawi lokalne SEO.
            {% else %}
            Wizytowka jest niekompletna i traci potencjalnych klientow. Priorytetowo uzupelnij brakujace informacje.
            {% 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: {{ audit.audit_date.strftime('%d.%m.%Y %H:%M') if audit.audit_date else 'Brak danych' }}</span>
            </div>
            {% if audit.review_count %}
            <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="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"/>
                </svg>
                <span>{{ audit.review_count }} opinii{% if audit.average_rating %} ({{ audit.average_rating }}/5){% endif %}</span>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- Fields Section -->
<div class="fields-section">
    <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 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"/>
        </svg>
        Status pol wizytowki
    </h2>

    <div class="legend">
        <div class="legend-item">
            <div class="legend-dot complete"></div>
            <span>Kompletne</span>
        </div>
        <div class="legend-item">
            <div class="legend-dot partial"></div>
            <span>Czesciowe</span>
        </div>
        <div class="legend-item">
            <div class="legend-dot missing"></div>
            <span>Brakujace</span>
        </div>
    </div>

    <div class="fields-grid">
        {% set field_icons = {
            'name': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/>',
            'address': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/>',
            'phone': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"/>',
            'website': '<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"/>',
            'hours': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>',
            'categories': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/>',
            'photos': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>',
            'description': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h7"/>',
            'services': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>',
            'reviews': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"/>'
        } %}
        {% set field_names_pl = {
            'name': 'Nazwa firmy',
            'address': 'Adres',
            'phone': 'Telefon',
            'website': 'Strona WWW',
            'hours': 'Godziny otwarcia',
            'categories': 'Kategorie',
            'photos': 'Zdjecia',
            'description': 'Opis',
            'services': 'Uslugi',
            'reviews': 'Opinie'
        } %}
        {% set status_names = {
            'complete': 'Kompletne',
            'partial': 'Czesciowe',
            'missing': 'Brakuje'
        } %}

        {% for field_name, field_data in audit.fields_status.items() %}
        <div class="field-card {{ field_data.status }}">
            <div class="field-header">
                <span class="field-name">
                    <svg class="field-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        {{ field_icons.get(field_name, '')|safe }}
                    </svg>
                    {{ field_names_pl.get(field_name, field_name) }}
                </span>
                <span class="field-status-badge {{ field_data.status }}">
                    {{ status_names.get(field_data.status, field_data.status) }}
                </span>
            </div>
            {% if field_data.value %}
            <div class="field-value">
                {% if field_name == 'hours' and field_data.value is mapping and field_data.value.weekday_text %}
                    {# Format opening hours nicely #}
                    {% for day_hours in field_data.value.weekday_text[:5] %}
                        {{ day_hours }}{% if not loop.last %}<br>{% endif %}
                    {% endfor %}
                    {% if field_data.value.weekday_text|length > 5 %}
                        <br>...
                    {% endif %}
                {% elif field_name == 'hours' and field_data.value is string and 'weekday_text' in field_data.value %}
                    {# Handle string representation of dict #}
                    <span class="hours-compact">Godziny ustawione</span>
                {% else %}
                    {{ field_data.value }}
                {% endif %}
            </div>
            {% endif %}
            {% if field_name == 'reviews' %}
            <div class="field-scoring-info reviews-scoring">
                {% if field_data.score == field_data.max_score %}
                    <span class="scoring-message success">🏆 Doskonale! Masz maksymalna punktacje za opinie</span>
                {% elif field_data.score == 0 %}
                    <span class="scoring-message hint">💡 Popros zadowolonych klientow o opinie w Google</span>
                {% else %}
                    <span class="scoring-message progress">👍 Dobry poczatek! Zbierz wiecej opinii - cel to minimum 5</span>
                {% endif %}
                {% if field_data.details and field_data.details.breakdown %}
                <div class="scoring-breakdown-line">{{ field_data.details.breakdown }}</div>
                {% endif %}
            </div>
            {% endif %}
            <div class="field-score">
                <div class="field-score-bar">
                    <div class="field-score-fill {{ field_data.status }}" style="width: {{ (field_data.score / field_data.max_score * 100) if field_data.max_score else 0 }}%;"></div>
                </div>
                <span class="field-score-text">{{ field_data.score|round(1) }}/{{ field_data.max_score }}</span>
            </div>
        </div>
        {% endfor %}
    </div>
</div>

<!-- Recommendations Section -->
{% if audit.recommendations %}
<div class="recommendations-section">
    <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.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/>
        </svg>
        Rekomendacje ({{ audit.recommendations|length }})
    </h2>

    <div class="recommendation-list">
        {% for rec in audit.recommendations %}
        <div class="recommendation-item">
            <div class="recommendation-priority {{ rec.priority }}">
                {% if rec.priority == 'high' %}
                <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="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
                </svg>
                {% elif rec.priority == 'medium' %}
                <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 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                {% else %}
                <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="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/>
                </svg>
                {% endif %}
            </div>
            <div class="recommendation-content">
                <div class="recommendation-field">{{ field_names_pl.get(rec.field, rec.field) }}</div>
                <div class="recommendation-text">{{ rec.recommendation }}</div>
            </div>
            <div class="recommendation-impact">
                <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="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"/>
                </svg>
                +{{ rec.impact }} pkt
            </div>
        </div>
        {% endfor %}
    </div>
</div>
{% endif %}

<!-- Educational Info Section -->
<div class="info-section">
    <div class="info-section-header">
        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
        </svg>
        <h3>Jak dziala wizytowka Google?</h3>
    </div>

    <div class="info-cards">
        <div class="info-card">
            <div class="info-card-icon search">
                <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="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                </svg>
            </div>
            <h4>Wyszukiwarka Google</h4>
            <p>Gdy ktos szuka Twojej firmy w Google, po prawej stronie wynikow pojawia sie <strong>Panel Wiedzy</strong> (Knowledge Panel).</p>
            <ul>
                <li>Nazwa i logo firmy</li>
                <li>Adres i godziny otwarcia</li>
                <li>Ocena i opinie</li>
                <li>Przycisk "Zadzwon" i "Trasa"</li>
            </ul>
        </div>

        <div class="info-card">
            <div class="info-card-icon maps">
                <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="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/>
                </svg>
            </div>
            <h4>Mapy Google</h4>
            <p>W aplikacji Google Maps Twoja firma ma <strong>pelna wizytowke</strong> z dodatkowymi funkcjami.</p>
            <ul>
                <li>Zdjecia i wirtualny spacer</li>
                <li>Wszystkie opinie klientow</li>
                <li>Pytania i odpowiedzi (Q&A)</li>
                <li>Posty i aktualnosci firmy</li>
            </ul>
        </div>

        <div class="info-card">
            <div class="info-card-icon manage">
                <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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                </svg>
            </div>
            <h4>Jak zarzadzac?</h4>
            <p>Wszystkie dane edytujesz w <strong>jednym miejscu</strong> - panelu Google Business Profile.</p>
            <ul>
                <li>Wejdz na <a href="https://business.google.com" target="_blank" rel="noopener">business.google.com</a></li>
                <li>Zaloguj sie kontem Google</li>
                <li>Edytuj dane - zaktualizuja sie wszedzie</li>
                <li>Odpowiadaj na opinie klientow</li>
            </ul>
        </div>
    </div>

    <div class="info-summary">
        <svg 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>
        <p>
            <strong>Jedno zrodlo, wiele widokow.</strong>
            Panel Wiedzy w wyszukiwarce i wizytowka w Mapach Google to <strong>te same dane</strong> wyswietlane w roznych miejscach.
            Wystarczy, ze zarzadzasz profilem w <a href="https://business.google.com" target="_blank" rel="noopener">Google Business Profile</a> -
            zmiany automatycznie pojawia sie wszedzie: w wyszukiwarce, Mapach, Asystencie Google i wynikach lokalnych.
        </p>
    </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="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"/>
    </svg>
    <h2>Brak danych audytu</h2>
    <p>Nie przeprowadzono jeszcze audytu wizytowki Google dla tej firmy. Uruchom audyt, aby sprawdzic kompletnosc profilu.</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 %}
</div>
{% endif %}

<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-content">
        <div class="loading-header">
            <h3>Audyt Google Business Profile</h3>
            <p>Pobieram dane z Google i analizuje wizytowke...</p>
        </div>
        <div class="loading-steps" id="loadingSteps">
            <!-- Phase 1: Find Place -->
            <div class="loading-step" id="step-find">
                <div class="step-icon in_progress">
                    <div class="step-spinner"></div>
                </div>
                <span class="step-text in_progress">Szukam firmy w Google Maps...</span>
            </div>

            <!-- Phase 2: Fetch Details - individual data points from Google -->
            <div class="loading-step step-detail" id="step-rating">
                <div class="step-icon pending">
                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <circle cx="12" cy="12" r="10" stroke-width="2"/>
                    </svg>
                </div>
                <span class="step-text pending">Ocena <span class="source-tag google">Google</span></span>
            </div>
            <div class="loading-step step-detail" id="step-reviews">
                <div class="step-icon pending">
                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <circle cx="12" cy="12" r="10" stroke-width="2"/>
                    </svg>
                </div>
                <span class="step-text pending">Liczba opinii <span class="source-tag google">Google</span></span>
            </div>
            <div class="loading-step step-detail" id="step-photos">
                <div class="step-icon pending">
                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <circle cx="12" cy="12" r="10" stroke-width="2"/>
                    </svg>
                </div>
                <span class="step-text pending">Zdjecia <span class="source-tag google">Google</span></span>
            </div>
            <div class="loading-step step-detail" id="step-hours">
                <div class="step-icon pending">
                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <circle cx="12" cy="12" r="10" stroke-width="2"/>
                    </svg>
                </div>
                <span class="step-text pending">Godziny otwarcia <span class="source-tag google">Google</span></span>
            </div>
            <div class="loading-step step-detail" id="step-phone">
                <div class="step-icon pending">
                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <circle cx="12" cy="12" r="10" stroke-width="2"/>
                    </svg>
                </div>
                <span class="step-text pending">Numer telefonu <span class="source-tag google">Google</span></span>
            </div>
            <div class="loading-step step-detail" id="step-website">
                <div class="step-icon pending">
                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <circle cx="12" cy="12" r="10" stroke-width="2"/>
                    </svg>
                </div>
                <span class="step-text pending">Strona WWW <span class="source-tag google">Google</span></span>
            </div>
            <div class="loading-step step-detail" id="step-status">
                <div class="step-icon pending">
                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <circle cx="12" cy="12" r="10" stroke-width="2"/>
                    </svg>
                </div>
                <span class="step-text pending">Status firmy <span class="source-tag google">Google</span></span>
            </div>

            <!-- Phase 3: Save -->
            <div class="loading-step" id="step-save">
                <div class="step-icon pending">
                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <circle cx="12" cy="12" r="10" stroke-width="2"/>
                    </svg>
                </div>
                <span class="step-text pending">Zapisuje dane w bazie</span>
            </div>

            <!-- Phase 4: Audit -->
            <div class="loading-step" id="step-audit">
                <div class="step-icon pending">
                    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <circle cx="12" cy="12" r="10" stroke-width="2"/>
                    </svg>
                </div>
                <span class="step-text pending">Analizuje kompletnosc profilu</span>
            </div>
        </div>
    </div>
</div>

<!-- Info Modal -->
<div class="modal" id="infoModal">
    <div class="modal-content">
        <div class="modal-header">
            <div class="modal-icon info" 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="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </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 }}';

// All step IDs in order
const allSteps = [
    'step-find',
    'step-rating', 'step-reviews', 'step-photos', 'step-hours',
    'step-phone', 'step-website', 'step-status',
    'step-save', 'step-audit'
];

// Detail step labels (defaults) with source tags
const detailLabels = {
    'step-rating': 'Ocena <span class="source-tag google">Google</span>',
    'step-reviews': 'Liczba opinii <span class="source-tag google">Google</span>',
    'step-photos': 'Zdjecia <span class="source-tag google">Google</span>',
    'step-hours': 'Godziny otwarcia <span class="source-tag google">Google</span>',
    'step-phone': 'Numer telefonu <span class="source-tag google">Google</span>',
    'step-website': 'Strona WWW <span class="source-tag google">Google</span>',
    'step-status': 'Status firmy <span class="source-tag google">Google</span>'
};

// SVG icons for different states
const icons = {
    pending: '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" stroke-width="2"/></svg>',
    in_progress: '<div class="step-spinner"></div>',
    complete: '<svg width="18" height="18" 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>',
    error: '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>',
    warning: '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>',
    skipped: '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 5l7 7-7 7M5 5l7 7-7 7"/></svg>',
    missing: '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"/></svg>'
};

function resetSteps() {
    // Reset all steps to default labels and pending state
    allSteps.forEach((stepId, index) => {
        const stepEl = document.getElementById(stepId);
        if (stepEl) {
            const iconEl = stepEl.querySelector('.step-icon');
            const textEl = stepEl.querySelector('.step-text');

            // Reset label to default (use innerHTML to preserve source tags)
            if (detailLabels[stepId]) {
                textEl.innerHTML = detailLabels[stepId];
            }

            if (index === 0) {
                iconEl.className = 'step-icon in_progress';
                iconEl.innerHTML = icons.in_progress;
                textEl.className = 'step-text in_progress';
            } else {
                iconEl.className = 'step-icon pending';
                iconEl.innerHTML = icons.pending;
                textEl.className = 'step-text pending';
            }
        }
    });
}

function updateStep(stepId, status, message) {
    const stepEl = document.getElementById(stepId);
    if (!stepEl) return;

    const iconEl = stepEl.querySelector('.step-icon');
    const textEl = stepEl.querySelector('.step-text');

    iconEl.className = 'step-icon ' + status;
    iconEl.innerHTML = icons[status] || icons.pending;
    textEl.className = 'step-text ' + status;
    if (message) {
        textEl.textContent = message;
    }
}

function showLoading() {
    resetSteps();
    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();
});

// Update detail steps with fetched data values
async function updateDetailSteps(googleData) {
    const delay = 150; // ms between each step animation

    // Rating
    updateStep('step-rating', 'in_progress', 'Pobieram ocene...');
    await new Promise(r => setTimeout(r, delay));
    if (googleData.google_rating) {
        updateStep('step-rating', 'complete', `Ocena: ${googleData.google_rating}/5`);
    } else {
        updateStep('step-rating', 'missing', 'Brak oceny');
    }

    // Reviews
    updateStep('step-reviews', 'in_progress', 'Pobieram opinie...');
    await new Promise(r => setTimeout(r, delay));
    if (googleData.google_reviews_count) {
        updateStep('step-reviews', 'complete', `Opinie: ${googleData.google_reviews_count}`);
    } else {
        updateStep('step-reviews', 'missing', 'Brak opinii');
    }

    // Photos
    updateStep('step-photos', 'in_progress', 'Pobieram zdjecia...');
    await new Promise(r => setTimeout(r, delay));
    if (googleData.google_photos_count) {
        updateStep('step-photos', 'complete', `Zdjecia: ${googleData.google_photos_count}`);
    } else {
        updateStep('step-photos', 'missing', 'Brak zdjec');
    }

    // Opening hours
    updateStep('step-hours', 'in_progress', 'Pobieram godziny otwarcia...');
    await new Promise(r => setTimeout(r, delay));
    if (googleData.google_opening_hours && googleData.google_opening_hours.weekday_text) {
        updateStep('step-hours', 'complete', 'Godziny otwarcia: ustawione');
    } else {
        updateStep('step-hours', 'missing', 'Brak godzin otwarcia');
    }

    // Phone
    updateStep('step-phone', 'in_progress', 'Pobieram telefon...');
    await new Promise(r => setTimeout(r, delay));
    if (googleData.google_phone) {
        updateStep('step-phone', 'complete', `Telefon: ${googleData.google_phone}`);
    } else {
        updateStep('step-phone', 'missing', 'Brak telefonu');
    }

    // Website
    updateStep('step-website', 'in_progress', 'Pobieram strone WWW...');
    await new Promise(r => setTimeout(r, delay));
    if (googleData.google_website) {
        // Truncate long URLs
        const shortUrl = googleData.google_website.replace(/^https?:\/\//, '').slice(0, 30);
        updateStep('step-website', 'complete', `WWW: ${shortUrl}...`);
    } else {
        updateStep('step-website', 'missing', 'Brak strony WWW');
    }

    // Business status
    updateStep('step-status', 'in_progress', 'Pobieram status...');
    await new Promise(r => setTimeout(r, delay));
    if (googleData.google_business_status) {
        const statusMap = {
            'OPERATIONAL': 'Czynna',
            'CLOSED_TEMPORARILY': 'Tymczasowo zamknieta',
            'CLOSED_PERMANENTLY': 'Zamknieta na stale'
        };
        const statusText = statusMap[googleData.google_business_status] || googleData.google_business_status;
        updateStep('step-status', 'complete', `Status: ${statusText}`);
    } else {
        updateStep('step-status', 'missing', 'Brak statusu');
    }
}

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

    // Simulate step animation start
    await new Promise(r => setTimeout(r, 300));

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

        const data = await response.json();

        // Handle find_place step
        if (data.google_fetch && data.google_fetch.steps) {
            const findStep = data.google_fetch.steps.find(s => s.step === 'find_place');
            if (findStep) {
                updateStep('step-find', findStep.status, findStep.message);
            }
        }

        // If we have Google data, animate the detail steps with actual values
        if (data.google_fetch && data.google_fetch.data && data.google_fetch.success) {
            await updateDetailSteps(data.google_fetch.data);

            // Save step
            const saveStep = data.google_fetch.steps.find(s => s.step === 'save_data');
            if (saveStep) {
                updateStep('step-save', saveStep.status, saveStep.message);
            }
        } else if (data.google_fetch && data.google_fetch.steps) {
            // Mark detail steps as skipped if no Google data
            const detailStepIds = ['step-rating', 'step-reviews', 'step-photos', 'step-hours', 'step-phone', 'step-website', 'step-status'];
            for (const stepId of detailStepIds) {
                updateStep(stepId, 'skipped', detailLabels[stepId] + ' (pominiety)');
            }
        }

        // Update audit step
        if (response.ok && data.success) {
            updateStep('step-save', 'complete', 'Dane zapisane');
            updateStep('step-audit', 'complete', `Analiza zakonczona: ${data.audit?.total_score || 0}/100`);
            // Wait 5 seconds so user can read the progress steps
            await new Promise(r => setTimeout(r, 5000));
            hideLoading();
            showInfoModal('Audyt zakonczony', 'Audyt wizytowki Google zostal zakonczony pomyslnie. Strona zostanie odswiezona.', true);
            setTimeout(() => location.reload(), 1500);
        } else {
            updateStep('step-audit', 'error', 'Blad audytu');
            // Wait 5 seconds so user can see what failed
            await new Promise(r => setTimeout(r, 5000));
            hideLoading();
            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 %}
