// Real catalog route matching for the landing page.
// Keep this small and explicit so the prototype remains easy to reason about.
window.REAL_USE_CASE_ROUTES = [
  {
    slug: 'help-me-code',
    label: 'help me code',
    keywords: ['code', 'coding', 'developer', 'program', 'ide', 'pull request', 'debug', 'software']
  },
  {
    slug: 'automate-meeting-notes',
    label: 'automate meeting notes',
    keywords: ['meeting', 'meetings', 'transcribe', 'transcription', 'notes', 'note taker', 'summary', 'summarise', 'zoom', 'call']
  },
  {
    slug: 'run-a-local-llm',
    label: 'run a local LLM',
    keywords: ['local', 'llm', 'offline', 'private', 'privacy', 'self hosted', 'self-hosted', 'laptop', 'ollama']
  },
  {
    slug: 'generate-marketing-videos',
    label: 'generate marketing videos',
    keywords: ['video', 'videos', 'marketing', 'reel', 'reels', 'avatar', 'shorts', 'tiktok', 'youtube']
  },
  {
    slug: 'review-legal-documents',
    label: 'review legal documents',
    keywords: ['legal', 'contract', 'contracts', 'document review', 'clause', 'lawyer', 'agreement']
  },
  {
    slug: 'general-ai-assistant',
    label: 'general AI assistant',
    keywords: ['assistant', 'chat', 'brainstorm', 'write', 'analyse', 'analyze', 'general']
  },
  {
    slug: 'answer-current-questions',
    label: 'answer current questions',
    keywords: ['search', 'current', 'sources', 'research web', 'answer', 'news']
  },
  {
    slug: 'create-images',
    label: 'create images',
    keywords: ['image', 'images', 'picture', 'design', 'logo', 'visual', 'art']
  },
  {
    slug: 'create-voice-audio',
    label: 'create voice and audio',
    keywords: ['voice', 'audio', 'voiceover', 'speech', 'podcast', 'dub', 'dubbing']
  },
  {
    slug: 'write-marketing-copy',
    label: 'write marketing copy',
    keywords: ['copy', 'marketing copy', 'writing', 'grammar', 'rewrite', 'content', 'campaign']
  },
  {
    slug: 'research-papers',
    label: 'research papers',
    keywords: ['paper', 'papers', 'study', 'studies', 'academic', 'literature', 'evidence']
  }
];

window.findRealUseCaseRoute = function findRealUseCaseRoute(query) {
  const normalized = String(query || '').trim().toLowerCase();

  if (!normalized) {
    return null;
  }

  const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const hasKeyword = (keyword) => {
    const normalizedKeyword = keyword.toLowerCase();

    if (normalizedKeyword.includes(' ') || normalizedKeyword.includes('-')) {
      return normalized.includes(normalizedKeyword);
    }

    return new RegExp(`\\b${escapeRegExp(normalizedKeyword)}\\b`).test(normalized);
  };

  const scoredRoutes = window.REAL_USE_CASE_ROUTES.map((route) => {
    let score = 0;

    if (normalized === route.label) {
      score += 100;
    } else if (normalized.includes(route.label)) {
      score += 60;
    }

    score += route.keywords.filter(hasKeyword).length * 10;

    return { route, score };
  }).filter((result) => result.score > 0);

  scoredRoutes.sort((a, b) => b.score - a.score);

  return scoredRoutes[0]?.route || null;
};

window.findRecommendedUseCaseRoute = async function findRecommendedUseCaseRoute(query) {
  const normalized = String(query || '').trim();

  if (!normalized) {
    return null;
  }

  try {
    const response = await fetch(`/api/recommendations?q=${encodeURIComponent(normalized)}`, {
      headers: {
        Accept: 'application/json'
      }
    });
    const payload = await response.json();

    if (response.ok && payload.ok && payload.recommendation?.useCase?.slug) {
      return {
        slug: payload.recommendation.useCase.slug,
        label: payload.recommendation.useCase.title,
        score: payload.recommendation.useCaseScore,
        tools: payload.recommendation.tools
      };
    }
  } catch {
    // Fall back to the static router if the dynamic recommendation API is unavailable.
  }

  return window.findRealUseCaseRoute(query);
};

window.goToRealUseCaseRoute = async function goToRealUseCaseRoute(query) {
  const route = await window.findRecommendedUseCaseRoute(query);

  if (!route) {
    return false;
  }

  window.parent.location.href = `/use-case/${route.slug}/refine?q=${encodeURIComponent(String(query || '').trim())}`;
  return true;
};
