import json
import logging
from datetime import datetime

logger = logging.getLogger(__name__)


def collect_storefront_data(db_session, min_score=30):
    from app.models import Package, Augment
    from app.services.quality_scorer import calculate_quality_score, quality_badge_tier

    packages = db_session.query(Package).filter(Package.site_copy.isnot(None)).order_by(Package.created_at.desc()).all()
    pkg_list = []
    seen_domains = set()

    for pkg in packages:
        if pkg.domain_name in seen_domains:
            continue
        seen_domains.add(pkg.domain_name)

        brand = pkg.brand or {}
        site_copy = pkg.site_copy or {}
        options = brand.get("options", [])
        rec = brand.get("recommended", 0)
        chosen = options[rec] if options and rec < len(options) else {"name": pkg.domain_name, "tagline": ""}

        augment_count = db_session.query(Augment).filter(Augment.domain_name == pkg.domain_name).count()
        score = calculate_quality_score(site_copy, brand, pkg.hero_image_url, augment_count)

        if score < min_score:
            continue

        tier = quality_badge_tier(score)
        features = site_copy.get("features", [])
        pricing = site_copy.get("pricing_tiers", site_copy.get("pricing_plans", []))
        faq = site_copy.get("faq_items", site_copy.get("faq", []))
        testimonials = site_copy.get("testimonials", [])
        listing_price = 497 if score >= 90 else 397 if score >= 65 else 297

        hero_image = None
        if pkg.hero_image_url and pkg.hero_image_url.startswith("/"):
            hero_image = pkg.hero_image_url

        palette = chosen.get("palette", {})
        color_primary = palette.get("primary", brand.get("color_primary", "#6366f1"))

        headline = site_copy.get("headline", "")
        subheadline = site_copy.get("subheadline", "")

        section_count = 0
        for key in ["features", "pricing_tiers", "faq_items", "testimonials", "how_it_works_steps", "comparison_table", "stats"]:
            val = site_copy.get(key)
            if val and ((isinstance(val, list) and len(val) > 0) or (isinstance(val, dict) and val)):
                section_count += 1

        pkg_list.append({
            "domain": pkg.domain_name,
            "brand_name": chosen.get("name", pkg.domain_name),
            "tagline": chosen.get("tagline", ""),
            "niche": pkg.chosen_niche or "",
            "hero_image": hero_image,
            "quality_score": round(score),
            "quality_tier": tier,
            "listing_price": listing_price,
            "color_primary": color_primary,
            "has_features": isinstance(features, list) and len(features) > 0,
            "has_pricing": isinstance(pricing, list) and len(pricing) > 0,
            "has_faq": isinstance(faq, list) and len(faq) > 0,
            "has_testimonials": isinstance(testimonials, list) and len(testimonials) > 0,
            "augment_count": augment_count,
            "feature_count": len(features) if isinstance(features, list) else 0,
            "section_count": section_count,
            "headline": headline[:120] if headline else "",
            "subheadline": subheadline[:200] if subheadline else "",
        })

    pkg_list.sort(key=lambda x: x["quality_score"], reverse=True)
    return pkg_list


def generate_static_storefront(db_session, base_url="", contact_email="", min_score=30, embed_images=False):
    packages = collect_storefront_data(db_session, min_score=min_score)

    if embed_images:
        import base64, os, mimetypes
        for pkg in packages:
            if pkg.get("hero_image") and pkg["hero_image"].startswith("/"):
                local_path = pkg["hero_image"].lstrip("/")
                if os.path.exists(local_path):
                    try:
                        mime = mimetypes.guess_type(local_path)[0] or "image/png"
                        with open(local_path, "rb") as f:
                            b64 = base64.b64encode(f.read()).decode()
                        pkg["hero_image"] = f"data:{mime};base64,{b64}"
                    except Exception:
                        pass

    legendary = [p for p in packages if p["quality_tier"] == "legendary"]
    premium = [p for p in packages if p["quality_tier"] == "premium"]
    standard = [p for p in packages if p["quality_tier"] == "standard"]

    total_value = sum(p["listing_price"] for p in packages)
    avg_score = round(sum(p["quality_score"] for p in packages) / max(len(packages), 1))

    stats = {
        "total": len(packages),
        "legendary_count": len(legendary),
        "premium_count": len(premium),
        "standard_count": len(standard),
        "total_value": total_value,
        "avg_score": avg_score,
    }

    preview_base = base_url.rstrip("/") if base_url else ""

    generated_date = datetime.utcnow().strftime("%B %d, %Y")

    html = _render_static_html(packages, legendary, stats, preview_base, contact_email, generated_date)
    return html


def _render_static_html(packages, legendary, stats, preview_base, contact_email, generated_date):
    packages_json = json.dumps(packages)

    featured_cards_html = ""
    for pkg in legendary[:3]:
        featured_cards_html += _render_featured_card(pkg, preview_base)

    grid_cards_html = ""
    for pkg in packages:
        grid_cards_html += _render_grid_card(pkg, preview_base)

    niche_set = sorted(set(p["niche"] for p in packages if p["niche"]))
    niche_buttons = ''.join(f'<button onclick="filterNiche(\'{n}\')" class="filter-pill" data-niche="{n}">{n}</button>' for n in niche_set[:12])

    return f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Premium Website Packages | Ready-to-Deploy Business Sites</title>
<meta name="description" content="{stats['total']} premium, AI-generated website packages ready for immediate deployment. Complete with brand identity, content, hero images, and interactive tools.">
<meta property="og:title" content="Premium Website Packages | {stats['total']} Sites Available">
<meta property="og:description" content="Agency-quality website packages starting at $297. Each includes full source code, brand identity, and marketing assets.">
<meta property="og:type" content="website">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Premium Website Packages">
<meta name="twitter:description" content="{stats['total']} ready-to-deploy business websites with AI-generated content and brand identity.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=Playfair+Display:wght@700;800;900&display=swap" rel="stylesheet">
<script type="application/ld+json">
{{
  "@context": "https://schema.org",
  "@type": "ItemList",
  "name": "Premium Website Packages",
  "numberOfItems": {stats['total']},
  "itemListElement": [''' + ','.join(f'''{{
    "@type": "ListItem",
    "position": {i+1},
    "item": {{
      "@type": "Product",
      "name": "{p['brand_name']}",
      "description": "Premium website package for {p['domain']}",
      "offers": {{
        "@type": "Offer",
        "price": "{p['listing_price']}",
        "priceCurrency": "USD"
      }}
    }}
  }}''' for i, p in enumerate(packages[:10])) + f''']
}}
</script>
<style>
*,*::before,*::after{{box-sizing:border-box;margin:0;padding:0}}
:root{{
  --bg-void:#08080f;--bg-surface:#0d0d1a;--bg-card:#12122a;--bg-card-hover:#181838;
  --border-subtle:rgba(255,255,255,0.04);--border-hover:rgba(99,102,241,0.25);
  --text-primary:#f0f0f8;--text-secondary:#9898b0;--text-muted:#606078;
  --accent-indigo:#6366f1;--accent-violet:#8b5cf6;--accent-cyan:#06b6d4;
  --accent-amber:#f59e0b;--accent-rose:#f43f5e;
  --gold-start:#f59e0b;--gold-end:#ef4444;
  --radius-sm:8px;--radius-md:16px;--radius-lg:24px;--radius-xl:32px;
}}
html{{scroll-behavior:smooth}}
body{{font-family:'Inter',system-ui,-apple-system,sans-serif;background:var(--bg-void);color:var(--text-primary);line-height:1.6;-webkit-font-smoothing:antialiased;overflow-x:hidden}}
.serif{{font-family:'Playfair Display',Georgia,serif}}

.glow-orb{{position:fixed;border-radius:50%;filter:blur(120px);pointer-events:none;z-index:0;opacity:0.12}}
.glow-orb-1{{width:600px;height:600px;background:var(--accent-indigo);top:-200px;left:-100px}}
.glow-orb-2{{width:500px;height:500px;background:var(--accent-violet);bottom:-150px;right:-100px}}
.glow-orb-3{{width:400px;height:400px;background:var(--accent-cyan);top:40%;left:60%;opacity:0.06}}

.container{{max-width:1280px;margin:0 auto;padding:0 24px;position:relative;z-index:1}}

nav{{position:sticky;top:0;z-index:50;background:rgba(8,8,15,0.85);backdrop-filter:blur(20px) saturate(180%);border-bottom:1px solid var(--border-subtle)}}
.nav-inner{{display:flex;align-items:center;justify-content:space-between;padding:16px 0}}
.logo{{font-size:1.75rem;font-weight:900;background:linear-gradient(135deg,var(--accent-indigo),var(--accent-violet));-webkit-background-clip:text;-webkit-text-fill-color:transparent}}
.logo-sub{{font-size:0.8rem;color:var(--text-muted);font-weight:500;margin-left:10px}}
.nav-stats{{display:flex;gap:24px;align-items:center}}
.nav-stat{{text-align:center}}
.nav-stat-val{{font-size:1.1rem;font-weight:800;color:var(--text-primary)}}
.nav-stat-label{{font-size:0.65rem;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em}}

.hero{{padding:100px 0 80px;text-align:center;position:relative}}
.hero-eyebrow{{display:inline-flex;align-items:center;gap:8px;padding:6px 16px;border-radius:100px;background:rgba(99,102,241,0.08);border:1px solid rgba(99,102,241,0.15);font-size:0.8rem;color:var(--accent-indigo);font-weight:600;margin-bottom:24px}}
.hero-eyebrow .pulse{{width:6px;height:6px;border-radius:50%;background:var(--accent-cyan);animation:pulse 2s infinite}}
@keyframes pulse{{0%,100%{{opacity:1;transform:scale(1)}}50%{{opacity:0.5;transform:scale(1.5)}}}}
.hero h1{{font-size:clamp(2.5rem,6vw,4.5rem);font-weight:900;line-height:1.05;margin-bottom:20px;letter-spacing:-0.03em}}
.hero h1 .gradient{{background:linear-gradient(135deg,var(--accent-indigo),var(--accent-violet),var(--accent-cyan));-webkit-background-clip:text;-webkit-text-fill-color:transparent}}
.hero-sub{{font-size:1.15rem;color:var(--text-secondary);max-width:640px;margin:0 auto 40px;line-height:1.7}}
.hero-actions{{display:flex;gap:16px;justify-content:center;flex-wrap:wrap}}
.btn-primary{{padding:14px 32px;border-radius:12px;font-weight:700;font-size:0.95rem;border:none;cursor:pointer;background:linear-gradient(135deg,var(--accent-indigo),var(--accent-violet));color:#fff;transition:all 0.3s;box-shadow:0 4px 24px -4px rgba(99,102,241,0.4)}}
.btn-primary:hover{{transform:translateY(-2px);box-shadow:0 8px 32px -4px rgba(99,102,241,0.5)}}
.btn-secondary{{padding:14px 32px;border-radius:12px;font-weight:600;font-size:0.95rem;border:1px solid var(--border-hover);cursor:pointer;background:transparent;color:var(--text-primary);transition:all 0.3s}}
.btn-secondary:hover{{background:rgba(99,102,241,0.08);border-color:var(--accent-indigo)}}

.trust-bar{{padding:40px 0;border-top:1px solid var(--border-subtle);border-bottom:1px solid var(--border-subtle)}}
.trust-row{{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:24px;text-align:center}}
.trust-item .val{{font-size:1.8rem;font-weight:900;background:linear-gradient(135deg,var(--accent-indigo),var(--accent-cyan));-webkit-background-clip:text;-webkit-text-fill-color:transparent}}
.trust-item .label{{font-size:0.75rem;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;margin-top:4px}}

.section-title{{font-size:2rem;font-weight:800;text-align:center;margin-bottom:8px;letter-spacing:-0.02em}}
.section-sub{{text-align:center;color:var(--text-secondary);margin-bottom:48px;font-size:1rem}}

.featured-section{{padding:80px 0}}
.featured-grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(380px,1fr));gap:24px}}
.featured-card{{background:var(--bg-card);border:1px solid var(--border-subtle);border-radius:var(--radius-lg);overflow:hidden;transition:all 0.4s cubic-bezier(0.16,1,0.3,1);position:relative}}
.featured-card::before{{content:'';position:absolute;inset:0;border-radius:var(--radius-lg);padding:1px;background:linear-gradient(135deg,rgba(99,102,241,0.3),rgba(139,92,246,0.1),transparent);mask:linear-gradient(#fff 0 0) content-box,linear-gradient(#fff 0 0);mask-composite:exclude;-webkit-mask-composite:xor;pointer-events:none;opacity:0;transition:opacity 0.4s}}
.featured-card:hover{{transform:translateY(-8px);box-shadow:0 32px 64px -16px rgba(0,0,0,0.6),0 0 48px -8px rgba(99,102,241,0.12)}}
.featured-card:hover::before{{opacity:1}}
.featured-img{{width:100%;aspect-ratio:16/9;object-fit:cover;display:block}}
.featured-img-placeholder{{width:100%;aspect-ratio:16/9;display:flex;align-items:center;justify-content:center;font-size:3rem;font-weight:900;color:rgba(255,255,255,0.08)}}
.featured-body{{padding:28px}}
.badge{{display:inline-flex;align-items:center;gap:4px;padding:4px 12px;border-radius:100px;font-size:0.7rem;font-weight:800;text-transform:uppercase;letter-spacing:0.1em}}
.badge-legendary{{background:linear-gradient(135deg,var(--gold-start),var(--gold-end));color:#fff;box-shadow:0 2px 12px -2px rgba(245,158,11,0.4)}}
.badge-premium{{background:linear-gradient(135deg,var(--accent-indigo),var(--accent-violet));color:#fff}}
.badge-standard{{background:rgba(6,182,212,0.12);color:var(--accent-cyan);border:1px solid rgba(6,182,212,0.2)}}
.badge-basic{{background:rgba(255,255,255,0.06);color:var(--text-muted)}}
.featured-name{{font-size:1.4rem;font-weight:800;margin:12px 0 4px;letter-spacing:-0.01em}}
.featured-domain{{font-size:0.85rem;color:var(--text-muted)}}
.featured-tagline{{font-size:0.9rem;color:var(--text-secondary);margin:12px 0 16px;line-height:1.5}}
.featured-meta{{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:20px}}
.meta-chip{{font-size:0.65rem;padding:3px 10px;border-radius:6px;background:rgba(255,255,255,0.04);color:var(--text-muted);font-weight:500}}
.featured-footer{{display:flex;align-items:center;justify-content:space-between;padding-top:20px;border-top:1px solid var(--border-subtle)}}
.price{{font-size:1.8rem;font-weight:900;color:var(--text-primary)}}
.price-was{{font-size:0.85rem;color:var(--text-muted);text-decoration:line-through;margin-right:8px}}
.score-ring{{width:44px;height:44px;border-radius:50%;display:flex;align-items:center;justify-content:center;position:relative}}
.score-ring::before{{content:'';position:absolute;inset:0;border-radius:50%;background:conic-gradient(var(--accent-indigo) var(--pct),rgba(255,255,255,0.06) 0);mask:radial-gradient(farthest-side,transparent calc(100% - 3px),#fff calc(100% - 3px))}}
.score-val{{font-size:0.75rem;font-weight:800;position:relative;z-index:1}}
.btn-preview{{padding:10px 20px;border-radius:10px;font-weight:600;font-size:0.8rem;border:1px solid var(--border-subtle);cursor:pointer;background:transparent;color:var(--text-secondary);transition:all 0.3s;text-decoration:none}}
.btn-preview:hover{{background:rgba(255,255,255,0.04);border-color:var(--border-hover);color:var(--text-primary)}}
.btn-buy{{padding:10px 24px;border-radius:10px;font-weight:700;font-size:0.8rem;border:none;cursor:pointer;background:var(--accent-indigo);color:#fff;transition:all 0.3s;text-decoration:none}}
.btn-buy:hover{{background:var(--accent-violet);transform:translateY(-1px)}}

.filters{{padding:20px 0 60px;display:flex;gap:8px;flex-wrap:wrap;justify-content:center}}
.filter-pill{{padding:8px 18px;border-radius:100px;font-size:0.8rem;font-weight:600;border:1px solid var(--border-subtle);background:transparent;color:var(--text-muted);cursor:pointer;transition:all 0.25s}}
.filter-pill:hover,.filter-pill.active{{background:rgba(99,102,241,0.1);border-color:var(--accent-indigo);color:var(--accent-indigo)}}

.grid-section{{padding:0 0 80px}}
.pkg-grid{{display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:20px}}
.grid-card{{background:var(--bg-card);border:1px solid var(--border-subtle);border-radius:var(--radius-md);overflow:hidden;transition:all 0.3s cubic-bezier(0.16,1,0.3,1)}}
.grid-card:hover{{transform:translateY(-4px);border-color:var(--border-hover);box-shadow:0 20px 40px -12px rgba(0,0,0,0.5)}}
.grid-img{{width:100%;aspect-ratio:16/9;object-fit:cover;display:block}}
.grid-img-placeholder{{width:100%;aspect-ratio:16/9;display:flex;align-items:center;justify-content:center;font-size:2rem;font-weight:900;color:rgba(255,255,255,0.06)}}
.grid-body{{padding:20px}}
.grid-header{{display:flex;align-items:start;justify-content:space-between;margin-bottom:8px}}
.grid-name{{font-size:1.05rem;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:200px}}
.grid-domain{{font-size:0.75rem;color:var(--text-muted);margin-bottom:6px}}
.grid-niche{{display:inline-block;font-size:0.65rem;padding:3px 10px;border-radius:6px;background:rgba(99,102,241,0.08);color:rgba(99,102,241,0.8);font-weight:600;margin-bottom:10px}}
.grid-tagline{{font-size:0.82rem;color:var(--text-secondary);margin-bottom:14px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;line-height:1.5}}
.grid-chips{{display:flex;gap:4px;flex-wrap:wrap;margin-bottom:16px}}
.grid-footer{{display:flex;align-items:center;justify-content:space-between;padding-top:16px;border-top:1px solid var(--border-subtle)}}
.grid-price{{font-size:1.4rem;font-weight:900}}
.grid-actions{{display:flex;gap:8px}}

.guarantee-section{{padding:60px 0;text-align:center}}
.guarantee-box{{max-width:700px;margin:0 auto;padding:40px;border-radius:var(--radius-lg);border:1px solid rgba(6,182,212,0.15);background:rgba(6,182,212,0.03)}}
.guarantee-icon{{font-size:3rem;margin-bottom:16px}}
.guarantee-title{{font-size:1.5rem;font-weight:800;margin-bottom:12px}}
.guarantee-text{{color:var(--text-secondary);line-height:1.7}}

.how-section{{padding:80px 0}}
.how-grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:32px;max-width:1000px;margin:0 auto}}
.how-step{{text-align:center;padding:24px}}
.how-num{{width:48px;height:48px;border-radius:50%;background:linear-gradient(135deg,var(--accent-indigo),var(--accent-violet));display:inline-flex;align-items:center;justify-content:center;font-size:1.2rem;font-weight:900;margin-bottom:16px}}
.how-step-title{{font-size:1.05rem;font-weight:700;margin-bottom:8px}}
.how-step-desc{{font-size:0.85rem;color:var(--text-secondary);line-height:1.6}}

.bundle-section{{padding:80px 0}}
.bundle-grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:24px;max-width:1000px;margin:0 auto}}
.bundle-card{{background:var(--bg-card);border:1px solid var(--border-subtle);border-radius:var(--radius-lg);padding:36px;text-align:center;transition:all 0.3s;position:relative}}
.bundle-card.featured{{border-color:var(--accent-indigo);box-shadow:0 0 32px -8px rgba(99,102,241,0.2)}}
.bundle-card.featured::after{{content:'BEST VALUE';position:absolute;top:-12px;left:50%;transform:translateX(-50%);padding:4px 16px;border-radius:100px;font-size:0.65rem;font-weight:800;background:linear-gradient(135deg,var(--accent-indigo),var(--accent-violet));color:#fff;letter-spacing:0.08em}}
.bundle-card:hover{{transform:translateY(-4px)}}
.bundle-name{{font-size:1.3rem;font-weight:800;margin-bottom:8px}}
.bundle-count{{font-size:0.85rem;color:var(--text-muted);margin-bottom:20px}}
.bundle-price{{font-size:2.5rem;font-weight:900;margin-bottom:4px}}
.bundle-per{{font-size:0.85rem;color:var(--text-secondary);margin-bottom:20px}}
.bundle-features{{list-style:none;text-align:left;margin-bottom:28px}}
.bundle-features li{{padding:8px 0;font-size:0.85rem;color:var(--text-secondary);border-bottom:1px solid var(--border-subtle);display:flex;align-items:center;gap:8px}}
.bundle-features li::before{{content:'\\2713';color:var(--accent-cyan);font-weight:700;font-size:0.9rem}}
.btn-bundle{{width:100%;padding:14px;border-radius:12px;font-weight:700;font-size:0.9rem;border:none;cursor:pointer;transition:all 0.3s}}
.btn-bundle-primary{{background:linear-gradient(135deg,var(--accent-indigo),var(--accent-violet));color:#fff}}
.btn-bundle-secondary{{background:rgba(255,255,255,0.04);border:1px solid var(--border-subtle);color:var(--text-primary)}}
.btn-bundle:hover{{transform:translateY(-2px)}}

.cta-section{{padding:80px 0;text-align:center}}
.cta-box{{max-width:600px;margin:0 auto;padding:48px;border-radius:var(--radius-xl);background:linear-gradient(135deg,rgba(99,102,241,0.08),rgba(139,92,246,0.04));border:1px solid rgba(99,102,241,0.12)}}
.cta-title{{font-size:1.8rem;font-weight:900;margin-bottom:12px}}
.cta-sub{{color:var(--text-secondary);margin-bottom:28px}}
.cta-form{{display:flex;gap:8px;max-width:420px;margin:0 auto}}
.cta-input{{flex:1;padding:12px 18px;border-radius:10px;border:1px solid var(--border-subtle);background:var(--bg-surface);color:var(--text-primary);font-size:0.9rem;outline:none}}
.cta-input:focus{{border-color:var(--accent-indigo)}}
.cta-input::placeholder{{color:var(--text-muted)}}

footer{{padding:40px 0;text-align:center;border-top:1px solid var(--border-subtle);color:var(--text-muted);font-size:0.8rem}}
footer a{{color:var(--accent-indigo);text-decoration:none}}

@media(max-width:768px){{
  .hero h1{{font-size:2.2rem}}
  .featured-grid,.pkg-grid{{grid-template-columns:1fr}}
  .bundle-grid{{grid-template-columns:1fr}}
  .nav-stats{{display:none}}
  .cta-form{{flex-direction:column}}
  .hero-actions{{flex-direction:column;align-items:center}}
}}

@media(prefers-reduced-motion:reduce){{
  *{{animation:none!important;transition:none!important}}
}}
</style>
</head>
<body>

<div class="glow-orb glow-orb-1"></div>
<div class="glow-orb glow-orb-2"></div>
<div class="glow-orb glow-orb-3"></div>

<nav>
<div class="container nav-inner">
  <div style="display:flex;align-items:baseline">
    <span class="logo">Aura</span>
    <span class="logo-sub">Marketplace</span>
  </div>
  <div class="nav-stats">
    <div class="nav-stat"><div class="nav-stat-val">{stats['total']}</div><div class="nav-stat-label">Packages</div></div>
    <div class="nav-stat"><div class="nav-stat-val">{stats['legendary_count']}</div><div class="nav-stat-label">Legendary</div></div>
    <div class="nav-stat"><div class="nav-stat-val">{stats['avg_score']}</div><div class="nav-stat-label">Avg Score</div></div>
    <a href="#packages" class="btn-primary" style="padding:10px 24px;font-size:0.85rem">Browse All</a>
  </div>
</div>
</nav>

<section class="hero">
<div class="container">
  <div class="hero-eyebrow"><span class="pulse"></span> {stats['total']} packages available now</div>
  <h1 class="serif">Premium <span class="gradient">Website Packages</span><br>Ready to Deploy</h1>
  <p class="hero-sub">Agency-quality business websites with AI-generated content, brand identity, hero images, and interactive tools. Each package includes full source code and is ready for immediate deployment.</p>
  <div class="hero-actions">
    <a href="#featured" class="btn-primary">View Featured Packages</a>
    <a href="#bundles" class="btn-secondary">Portfolio Bundles</a>
  </div>
</div>
</section>

<section class="trust-bar">
<div class="container">
  <div class="trust-row">
    <div class="trust-item"><div class="val">{stats['total']}</div><div class="label">Ready Sites</div></div>
    <div class="trust-item"><div class="val">${stats['total_value']:,}</div><div class="label">Total Catalog Value</div></div>
    <div class="trust-item"><div class="val">{stats['legendary_count']}</div><div class="label">Legendary Tier</div></div>
    <div class="trust-item"><div class="val">100%</div><div class="label">Source Code Included</div></div>
    <div class="trust-item"><div class="val">$297+</div><div class="label">Starting Price</div></div>
  </div>
</div>
</section>

<section class="featured-section" id="featured">
<div class="container">
  <h2 class="section-title serif">Featured <span style="background:linear-gradient(135deg,var(--gold-start),var(--gold-end));-webkit-background-clip:text;-webkit-text-fill-color:transparent">Legendary</span> Packages</h2>
  <p class="section-sub">Our highest-rated website packages — scored 90+ out of 100 by our quality engine</p>
  <div class="featured-grid">
    {featured_cards_html}
  </div>
</div>
</section>

<section class="how-section">
<div class="container">
  <h2 class="section-title">How It Works</h2>
  <p class="section-sub">From purchase to live website in minutes</p>
  <div class="how-grid">
    <div class="how-step"><div class="how-num">1</div><div class="how-step-title">Choose Your Package</div><div class="how-step-desc">Browse our collection and find the perfect domain + website for your niche.</div></div>
    <div class="how-step"><div class="how-num">2</div><div class="how-step-title">Instant Download</div><div class="how-step-desc">Get the complete source code, assets, brand kit, and all interactive tools.</div></div>
    <div class="how-step"><div class="how-num">3</div><div class="how-step-title">Deploy & Customize</div><div class="how-step-desc">Upload to any hosting provider. The site is production-ready out of the box.</div></div>
    <div class="how-step"><div class="how-num">4</div><div class="how-step-title">Start Earning</div><div class="how-step-desc">Your professional online presence is live. Attract clients from day one.</div></div>
  </div>
</div>
</section>

<section class="guarantee-section">
<div class="container">
  <div class="guarantee-box">
    <div class="guarantee-icon">&#x1F6E1;</div>
    <div class="guarantee-title">Quality Guaranteed</div>
    <p class="guarantee-text">Every package is scored by our 12-point quality engine. You see the exact score before you buy. Each site includes complete source code, brand identity, hero imagery, content sections, and interactive tools. What you preview is exactly what you get.</p>
  </div>
</div>
</section>

<section class="grid-section" id="packages">
<div class="container">
  <h2 class="section-title">All Packages</h2>
  <p class="section-sub">Browse our complete collection — filter by tier or niche</p>
  <div class="filters">
    <button onclick="filterTier('all')" class="filter-pill active" data-tier="all">All ({stats['total']})</button>
    <button onclick="filterTier('legendary')" class="filter-pill" data-tier="legendary">Legendary ({stats['legendary_count']})</button>
    <button onclick="filterTier('premium')" class="filter-pill" data-tier="premium">Premium ({stats['premium_count']})</button>
    {niche_buttons}
  </div>
  <div class="pkg-grid" id="pkg-grid">
    {grid_cards_html}
  </div>
</div>
</section>

<section class="bundle-section" id="bundles">
<div class="container">
  <h2 class="section-title serif">Portfolio <span class="gradient">Bundles</span></h2>
  <p class="section-sub">Volume discounts for serious buyers — save up to 50%</p>
  <div class="bundle-grid">
    <div class="bundle-card">
      <div class="bundle-name">Starter Bundle</div>
      <div class="bundle-count">5 Website Packages</div>
      <div class="bundle-price">$997</div>
      <div class="bundle-per">$199 per site (save 33%)</div>
      <ul class="bundle-features">
        <li>5 hand-picked premium sites</li>
        <li>All source code included</li>
        <li>Brand identities & hero images</li>
        <li>Email support</li>
      </ul>
      <button class="btn-bundle btn-bundle-secondary" onclick="contactBundle('starter')">Get This Bundle</button>
    </div>
    <div class="bundle-card featured">
      <div class="bundle-name">Professional Bundle</div>
      <div class="bundle-count">10 Website Packages</div>
      <div class="bundle-price">$1,497</div>
      <div class="bundle-per">$149 per site (save 50%)</div>
      <ul class="bundle-features">
        <li>10 curated sites (mix of tiers)</li>
        <li>Complete source code & assets</li>
        <li>All interactive tools & augments</li>
        <li>Priority customization support</li>
        <li>Bulk hosting setup guide</li>
      </ul>
      <button class="btn-bundle btn-bundle-primary" onclick="contactBundle('professional')">Get This Bundle</button>
    </div>
    <div class="bundle-card">
      <div class="bundle-name">Full Portfolio</div>
      <div class="bundle-count">All {stats['total']} Packages</div>
      <div class="bundle-price">Contact</div>
      <div class="bundle-per">Maximum value, minimum per-site cost</div>
      <ul class="bundle-features">
        <li>Every package in the catalog</li>
        <li>All domains + websites + tools</li>
        <li>White-label rights</li>
        <li>Dedicated onboarding</li>
        <li>Custom modifications included</li>
      </ul>
      <button class="btn-bundle btn-bundle-secondary" onclick="contactBundle('portfolio')">Let's Talk</button>
    </div>
  </div>
</div>
</section>

<section class="cta-section">
<div class="container">
  <div class="cta-box">
    <div class="cta-title">Stay Updated</div>
    <p class="cta-sub">Get notified when new legendary packages drop. No spam, ever.</p>
    <form class="cta-form" onsubmit="handleSubscribe(event)">
      <input type="email" class="cta-input" placeholder="you@example.com" required>
      <button type="submit" class="btn-primary" style="white-space:nowrap">Notify Me</button>
    </form>
    <p id="subscribe-msg" style="margin-top:12px;font-size:0.8rem;color:var(--accent-cyan);display:none"></p>
  </div>
</div>
</section>

<footer>
<div class="container">
  <p>Powered by <a href="#">Aura</a> &middot; AI-Generated Business Packages &middot; Generated {generated_date}</p>
</div>
</footer>

<script>
const packages = {packages_json};

function filterTier(tier) {{
  document.querySelectorAll('.filter-pill[data-tier]').forEach(b => b.classList.toggle('active', b.dataset.tier === tier));
  document.querySelectorAll('.filter-pill[data-niche]').forEach(b => b.classList.remove('active'));
  document.querySelectorAll('#pkg-grid .grid-card').forEach(c => {{
    c.style.display = (tier === 'all' || c.dataset.tier === tier) ? '' : 'none';
  }});
}}

function filterNiche(niche) {{
  document.querySelectorAll('.filter-pill[data-tier]').forEach(b => b.classList.remove('active'));
  document.querySelectorAll('.filter-pill[data-niche]').forEach(b => b.classList.toggle('active', b.dataset.niche === niche));
  document.querySelectorAll('#pkg-grid .grid-card').forEach(c => {{
    c.style.display = (!niche || c.dataset.niche === niche) ? '' : 'none';
  }});
}}

function contactBundle(tier) {{
  const email = '{contact_email}' || '';
  if (email) {{
    window.location.href = 'mailto:' + email + '?subject=Bundle Inquiry: ' + tier + ' package';
  }} else {{
    alert('Bundle inquiry: ' + tier + '. Contact us to purchase!');
  }}
}}

function handleSubscribe(e) {{
  e.preventDefault();
  const msg = document.getElementById('subscribe-msg');
  msg.textContent = 'Thanks! You\\'ll be notified when new packages drop.';
  msg.style.display = 'block';
  e.target.reset();
}}
</script>
</body>
</html>'''


def _render_featured_card(pkg, preview_base):
    img_html = f'<img src="{preview_base}{pkg["hero_image"]}" alt="{pkg["brand_name"]}" class="featured-img" loading="lazy">' if pkg.get("hero_image") else f'<div class="featured-img-placeholder" style="background:linear-gradient(135deg,{pkg["color_primary"]},#8b5cf6)">{pkg["brand_name"][:2].upper()}</div>'

    chips = []
    if pkg["has_features"]: chips.append(f'{pkg["feature_count"]} Features')
    if pkg["has_pricing"]: chips.append('Pricing')
    if pkg["has_faq"]: chips.append('FAQ')
    if pkg["has_testimonials"]: chips.append('Testimonials')
    if pkg["augment_count"] > 0: chips.append(f'{pkg["augment_count"]} Tools')
    chips_html = ''.join(f'<span class="meta-chip">{c}</span>' for c in chips)

    preview_url = f'{preview_base}/_dev_preview/N5G4K8fWLY9MrapEkZnw_g/{pkg["domain"]}/standalone' if preview_base else '#'
    agency_value = pkg["listing_price"] * 8

    return f'''<div class="featured-card" data-tier="{pkg['quality_tier']}" data-domain="{pkg['domain']}">
  {img_html}
  <div class="featured-body">
    <span class="badge badge-{pkg['quality_tier']}">{pkg['quality_tier']}</span>
    <div class="featured-name">{pkg['brand_name']}</div>
    <div class="featured-domain">{pkg['domain']}</div>
    <p class="featured-tagline">{pkg['tagline']}</p>
    <div class="featured-meta">{chips_html}</div>
    <div class="featured-footer">
      <div><span class="price-was">${agency_value:,}</span><span class="price">${pkg['listing_price']}</span></div>
      <div class="score-ring" style="--pct:{pkg['quality_score']}%"><span class="score-val">{pkg['quality_score']}</span></div>
      <div style="display:flex;gap:8px">
        <a href="{preview_url}" target="_blank" class="btn-preview">Preview</a>
        <button class="btn-buy" onclick="contactBundle('{pkg['domain']}')">Buy Now</button>
      </div>
    </div>
  </div>
</div>'''


def _render_grid_card(pkg, preview_base):
    img_html = f'<img src="{preview_base}{pkg["hero_image"]}" alt="{pkg["brand_name"]}" class="grid-img" loading="lazy">' if pkg.get("hero_image") else f'<div class="grid-img-placeholder" style="background:linear-gradient(135deg,{pkg["color_primary"]},#8b5cf6)">{pkg["brand_name"][:2].upper()}</div>'

    chips = []
    if pkg["has_features"]: chips.append('Features')
    if pkg["has_pricing"]: chips.append('Pricing')
    if pkg["has_faq"]: chips.append('FAQ')
    if pkg["augment_count"] > 0: chips.append(f'{pkg["augment_count"]} Tools')
    chips_html = ''.join(f'<span class="meta-chip">{c}</span>' for c in chips)

    preview_url = f'{preview_base}/_dev_preview/N5G4K8fWLY9MrapEkZnw_g/{pkg["domain"]}/standalone' if preview_base else '#'

    return f'''<div class="grid-card" data-tier="{pkg['quality_tier']}" data-domain="{pkg['domain']}" data-niche="{pkg['niche']}">
  {img_html}
  <div class="grid-body">
    <div class="grid-header">
      <div><div class="grid-name" title="{pkg['brand_name']}">{pkg['brand_name']}</div><div class="grid-domain">{pkg['domain']}</div></div>
      <div class="score-ring" style="--pct:{pkg['quality_score']}%;width:36px;height:36px"><span class="score-val" style="font-size:0.65rem">{pkg['quality_score']}</span></div>
    </div>
    <span class="badge badge-{pkg['quality_tier']}" style="margin-bottom:8px">{pkg['quality_tier']}</span>
    {f'<span class="grid-niche">{pkg["niche"]}</span>' if pkg['niche'] else ''}
    <p class="grid-tagline">{pkg['tagline']}</p>
    <div class="grid-chips">{chips_html}</div>
    <div class="grid-footer">
      <span class="grid-price">${pkg['listing_price']}</span>
      <div class="grid-actions">
        <a href="{preview_url}" target="_blank" class="btn-preview">Preview</a>
        <button class="btn-buy" onclick="contactBundle('{pkg['domain']}')">Buy</button>
      </div>
    </div>
  </div>
</div>'''
