/**
 * Cloudflare Worker for Dynamic Open Graph Tags
 *
 * Deploy this as a Cloudflare Worker to handle /share routes
 * and inject dynamic OG tags based on URL parameters.
 *
 * URL format: https://portfoliojournal.app/share?goal=My%20Goal&progress=42
 *
 * Setup:
 * 1. Go to Cloudflare Dashboard > Workers
 * 2. Create a new Worker
 * 3. Paste this code
 * 4. Add a route: portfoliojournal.app/share*
 */

export default {
  async fetch(request) {
    const url = new URL(request.url);

    // Only handle /share routes
    if (!url.pathname.startsWith('/share')) {
      return fetch(request);
    }

    // Get parameters
    const goalName = url.searchParams.get('goal') || 'Investment Goal';
    const progress = parseInt(url.searchParams.get('progress')) || 0;

    // Build dynamic OG content
    const ogTitle = `I'm ${progress}% towards my "${goalName}" goal! 🎯`;
    const ogDescription = 'Track your investment goals with Portfolio Journal. Download free on the App Store.';
    const ogImage = 'https://portfoliojournal.app/images/og-share-card.png';
    const appStoreUrl = 'https://apps.apple.com/app/portfolio-journal/id6744983373';

    const html = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${escapeHtml(ogTitle)} - Portfolio Journal</title>

    <!-- Open Graph / Facebook -->
    <meta property="og:type" content="website">
    <meta property="og:url" content="${escapeHtml(url.toString())}">
    <meta property="og:title" content="${escapeHtml(ogTitle)}">
    <meta property="og:description" content="${escapeHtml(ogDescription)}">
    <meta property="og:image" content="${ogImage}">
    <meta property="og:image:width" content="1200">
    <meta property="og:image:height" content="630">
    <meta property="og:site_name" content="Portfolio Journal">

    <!-- Twitter Card -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:url" content="${escapeHtml(url.toString())}">
    <meta name="twitter:title" content="${escapeHtml(ogTitle)}">
    <meta name="twitter:description" content="${escapeHtml(ogDescription)}">
    <meta name="twitter:image" content="${ogImage}">

    <!-- Apple Smart App Banner -->
    <meta name="apple-itunes-app" content="app-id=6744983373">

    <!-- SEO -->
    <meta name="description" content="${escapeHtml(ogDescription)}">
    <link rel="canonical" href="${escapeHtml(url.toString())}">

    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .container { text-align: center; color: white; max-width: 480px; }
        .app-icon {
            width: 100px; height: 100px;
            border-radius: 22px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
            margin-bottom: 20px;
        }
        .goal-card {
            background: rgba(255,255,255,0.15);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 24px;
            margin-bottom: 24px;
            border: 1px solid rgba(255,255,255,0.2);
        }
        .goal-label { font-size: 0.85rem; opacity: 0.8; margin-bottom: 4px; }
        .goal-name { font-size: 1.5rem; font-weight: 700; margin-bottom: 16px; }
        .progress-bar {
            background: rgba(255,255,255,0.2);
            border-radius: 10px;
            height: 12px;
            overflow: hidden;
            margin-bottom: 8px;
        }
        .progress-fill {
            background: white;
            height: 100%;
            width: ${progress}%;
            border-radius: 10px;
        }
        .progress-text { font-size: 1.1rem; font-weight: 600; }
        h1 { font-size: 1.5rem; font-weight: 700; margin-bottom: 8px; }
        .tagline { font-size: 1rem; opacity: 0.9; margin-bottom: 24px; line-height: 1.5; }
        .download-btn {
            display: inline-flex;
            align-items: center;
            gap: 12px;
            background: white;
            color: #667eea;
            padding: 14px 28px;
            border-radius: 14px;
            text-decoration: none;
            font-weight: 600;
            font-size: 1rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.2);
            transition: transform 0.2s;
        }
        .download-btn:hover { transform: translateY(-2px); }
        .footer { margin-top: 32px; font-size: 0.85rem; opacity: 0.7; }
        .footer a { color: white; }
    </style>
</head>
<body>
    <div class="container">
        <img src="/images/app-icon.png" alt="Portfolio Journal" class="app-icon">

        <div class="goal-card">
            <div class="goal-label">Goal Progress</div>
            <div class="goal-name">${escapeHtml(goalName)}</div>
            <div class="progress-bar">
                <div class="progress-fill"></div>
            </div>
            <div class="progress-text">${progress}% complete</div>
        </div>

        <h1>Portfolio Journal</h1>
        <p class="tagline">Track your investment goals and celebrate your financial milestones.</p>

        <a href="${appStoreUrl}" class="download-btn">
            <svg viewBox="0 0 24 24" fill="currentColor" width="22" height="22">
                <path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"/>
            </svg>
            Download Free
        </a>

        <p class="footer">
            <a href="https://portfoliojournal.app">portfoliojournal.app</a>
        </p>
    </div>
</body>
</html>`;

    return new Response(html, {
      headers: {
        'Content-Type': 'text/html;charset=UTF-8',
        'Cache-Control': 'public, max-age=3600', // Cache for 1 hour
      },
    });
  },
};

function escapeHtml(text) {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;',
  };
  return text.replace(/[&<>"']/g, m => map[m]);
}
