{% extends "base.html" %}

{% block title %}Market - AISBF Dashboard{% endblock %}

{% block content %}
<h2 style="margin-bottom: 20px;"><i class="fas fa-store" style="color: var(--color-link);"></i> Market</h2>
<p style="color: var(--color-muted); margin-bottom: 20px;">Browse shared providers and models, review pricing and reputation, and import market resources into your account.</p>

<div style="background: var(--bg-panel); border: 1px solid var(--color-border); border-radius: 10px; padding: 16px; margin-bottom: 18px; display:grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px;">
    <input id="market-search" placeholder="Search name, type, capability" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
    <select id="market-source-type" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
        <option value="">All resource types</option>
        <option value="provider">Provider</option>
        <option value="model">Model</option>
        <option value="rotation">Rotation</option>
        <option value="autoselect">Autoselect</option>
    </select>
    <input id="market-capabilities" placeholder="Capabilities comma-separated" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
    <input id="market-model-type" placeholder="Model type / family" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
    <input id="market-model-name" placeholder="Model name" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
    <input id="market-size" placeholder="Size / params" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
    <label style="display:flex; align-items:center; gap:8px; color:var(--color-text);"><input type="checkbox" id="market-online-only"> Online only</label>
    <select id="market-sort" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
        <option value="newest">Newest</option>
        <option value="price_asc">Price low to high</option>
        <option value="price_desc">Price high to low</option>
        <option value="upvotes">Best rated</option>
        <option value="performance">Best performance</option>
        <option value="requests">Most used</option>
        <option value="revenue">Top grossing</option>
    </select>
    <button class="btn btn-secondary" onclick="reloadMarket()">Apply Filters</button>
</div>

<div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 16px;" id="market-grid"></div>

<div style="margin-top: 30px; background: var(--bg-panel); border: 1px solid var(--color-border); border-radius: 10px; padding: 18px;">
    <h3 style="margin-top:0;">Publish one of your resources</h3>
    <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 12px;">
        <select id="publish-source-type" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
            <option value="provider">Provider</option>
            <option value="model">Model</option>
            <option value="rotation">Rotation</option>
            <option value="autoselect">Autoselect</option>
        </select>
        <input id="publish-source-id" placeholder="Provider / model / rotation / autoselect id" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
        <input id="publish-title" placeholder="Listing title" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
        <input id="publish-provider-id" placeholder="Provider id for model listings" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
        <input id="publish-price-tokens" type="number" step="0.0001" min="0" placeholder="Price / 1M tokens" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
        <input id="publish-price-requests" type="number" step="0.0001" min="0" placeholder="Price / 1000 requests" style="padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);">
    </div>
    <textarea id="publish-description" placeholder="Description" style="margin-top:12px; width:100%; min-height:84px; padding:10px; border:1px solid var(--color-border); border-radius:6px; background:var(--bg-page); color:var(--color-text);"></textarea>
    <button class="btn" style="margin-top:12px;" onclick="publishListing()">Publish Listing</button>
</div>
{% endblock %}

{% block extra_js %}
<script>
const listings = {{ market_listings_json | safe }};
const currencySymbol = {{ currency_symbol | tojson }};
const marketSettings = {{ market_settings_json | safe }};

function voteSummary(votes, target) {
    const item = (votes || {})[target] || {upvotes:0, downvotes:0, score:0};
    return `+${item.upvotes} / -${item.downvotes} (score ${item.score})`;
}

function renderMarket() {
    const root = document.getElementById('market-grid');
    root.innerHTML = '';
    listings.forEach(listing => {
        const el = document.createElement('div');
        el.style.cssText = 'background: var(--bg-panel); border: 1px solid var(--color-border); border-radius: 12px; padding: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.08);';
        el.innerHTML = `
            <div style="display:flex; justify-content:space-between; gap:10px; align-items:flex-start;">
                <div>
                    <h3 style="margin:0 0 6px 0;">${listing.title}</h3>
                    <div style="color: var(--color-muted); font-size: 13px;">by ${listing.owner_display_name || listing.owner_username}</div>
                </div>
                <div style="text-align:right; font-size:13px; color: var(--color-link);">
                    <div>${currencySymbol}${Number(listing.price_per_million_tokens || 0).toFixed(4)} / 1M tok</div>
                    <div>${currencySymbol}${Number(listing.price_per_1000_requests || 0).toFixed(4)} / 1k req</div>
                </div>
            </div>
            <p style="color: var(--color-text); margin: 12px 0;">${listing.description || ''}</p>
            <div style="font-size:12px; color: var(--color-muted); margin-bottom: 10px;">Provider: ${listing.provider_id || '-'} ${listing.model_id ? ` | Model: ${listing.model_id}` : ''} ${listing.model_type_label ? ` | Type: ${listing.model_type_label}` : ''} ${listing.size_label ? ` | Size: ${listing.size_label}` : ''}</div>
            <div style="font-size:12px; color: var(--color-muted); margin-bottom: 10px;">Status: ${listing.online ? 'online' : 'offline'}${(listing.capabilities || []).length ? ` | Capabilities: ${(listing.capabilities || []).join(', ')}` : ''}</div>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:6px; font-size:12px; margin-bottom:12px;">
                <div>Listing votes: ${voteSummary(listing.votes, 'listing')}</div>
                <div>User votes: ${voteSummary(listing.votes, 'user')}</div>
                <div>Provider votes: ${voteSummary(listing.votes, 'provider')}</div>
                <div>Model votes: ${voteSummary(listing.votes, 'model')}</div>
            </div>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:6px; font-size:12px; margin-bottom:12px; color: var(--color-muted);">
                <div>Usage events: ${(listing.stats || {}).usage_events || 0}</div>
                <div>Total requests: ${(listing.stats || {}).total_requests || 0}</div>
                <div>Total tokens: ${(listing.stats || {}).total_tokens || 0}</div>
                <div>Avg tokens/req: ${Number((listing.stats || {}).avg_tokens_per_request || 0).toFixed(1)}</div>
                <div>Gross: ${currencySymbol}${Number((listing.stats || {}).gross_revenue || 0).toFixed(2)}</div>
                <div>Seller rev: ${currencySymbol}${Number((listing.stats || {}).provider_revenue || 0).toFixed(2)}</div>
                <div>Analytics req: ${(listing.analytics || {}).request_count || 0}</div>
                <div>Avg latency: ${Number((listing.analytics || {}).avg_latency_ms || 0).toFixed(1)} ms</div>
                <div>Error rate: ${(Number((listing.analytics || {}).error_rate || 0) * 100).toFixed(1)}%</div>
                <div>Analytics tokens: ${(listing.analytics || {}).total_tokens || 0}</div>
            </div>
            <div style="display:flex; flex-wrap:wrap; gap:8px;">
                <button class="btn btn-secondary" onclick="importListing(${listing.id})">Import</button>
                <button class="btn btn-secondary" onclick="voteListing(${listing.id}, 'listing', 1)">Upvote</button>
                <button class="btn btn-secondary" onclick="voteListing(${listing.id}, 'listing', -1)">Downvote</button>
            </div>
        `;
        root.appendChild(el);
    });
}

async function importListing(id) {
    const response = await fetch(`/api/market/listings/${id}/import`, {method:'POST', headers:{'Content-Type':'application/json'}});
    const result = await response.json();
    if (!response.ok) {
        alert(result.error || 'Import failed');
        return;
    }
    alert(`Imported as ${result.imported_config_type}: ${result.imported_config_id}`);
}

async function voteListing(id, targetType, vote) {
    const response = await fetch(`/api/market/listings/${id}/vote`, {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({target_type: targetType, vote})
    });
    const result = await response.json();
    if (!response.ok) {
        alert(result.error || 'Vote failed');
        return;
    }
    const listing = listings.find(item => item.id === id);
    if (listing) listing.votes = result.votes;
    renderMarket();
}

async function publishListing() {
    const body = {
        source_type: document.getElementById('publish-source-type').value,
        provider_id: document.getElementById('publish-provider-id').value.trim(),
        source_id: document.getElementById('publish-source-id').value.trim(),
        model_id: document.getElementById('publish-source-type').value === 'model' ? document.getElementById('publish-source-id').value.trim() : undefined,
        title: document.getElementById('publish-title').value.trim(),
        description: document.getElementById('publish-description').value.trim(),
        price_per_million_tokens: parseFloat(document.getElementById('publish-price-tokens').value || '0'),
        price_per_1000_requests: parseFloat(document.getElementById('publish-price-requests').value || '0')
    };
    const response = await fetch('/api/market/listings', {
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify(body)
    });
    const result = await response.json();
    if (!response.ok) {
        alert(result.error || 'Publish failed');
        return;
    }
    window.location.reload();
}

renderMarket();

async function reloadMarket() {
    const params = new URLSearchParams();
    const q = document.getElementById('market-search').value.trim();
    const sourceType = document.getElementById('market-source-type').value;
    const capabilities = document.getElementById('market-capabilities').value.trim();
    const modelType = document.getElementById('market-model-type').value.trim();
    const modelName = document.getElementById('market-model-name').value.trim();
    const size = document.getElementById('market-size').value.trim();
    const onlineOnly = document.getElementById('market-online-only').checked;
    const sortBy = document.getElementById('market-sort').value;
    if (q) params.set('q', q);
    if (sourceType) params.set('source_type', sourceType);
    if (capabilities) params.set('capabilities', capabilities);
    if (modelType) params.set('model_type', modelType);
    if (modelName) params.set('model_name', modelName);
    if (size) params.set('size', size);
    if (onlineOnly) params.set('online_only', '1');
    if (sortBy) params.set('sort_by', sortBy);
    const response = await fetch(`/api/market/listings?${params.toString()}`);
    const result = await response.json();
    if (!response.ok) {
        alert(result.error || 'Failed to load market');
        return;
    }
    listings.length = 0;
    for (const listing of result.listings || []) listings.push(listing);
    renderMarket();
}
</script>
{% endblock %}
