<!-- SideBarExplanation.vue -->
<template>
  <div class="sidebar-explanation">
    <div 
      v-if="isLoading" 
      class="explanation-loading"
    >
      🔄 Translating...
    </div>
    <div 
      v-else
      class="explanation-content"
      v-html="renderedExplanation"
    ></div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { useComponentTranslations } from '../js/services/LanguageProvider.js';

const props = defineProps({
  originalText: {
    type: String,
    default: ''
  },
  currentLanguage: {
    type: String,
    default: 'en'
  },
  apiPrefix: {
    type: String,
    default: ''
  }
});

// Use component translations from provider
const originalTexts = computed(() => ({
  explanation: props.originalText || ''
}));

const { translations, isLoading, error, currentLanguage } = useComponentTranslations(
  'sidebar_explanation', 
  originalTexts.value
);

const translatedText = computed(() => translations.value.explanation || props.originalText);

// Render markdown content
const renderedExplanation = computed(() => {
  if (!translatedText.value) return '';
  
  // Use marked if available, otherwise return plain text
  if (typeof window.marked === 'function') {
    return window.marked(translatedText.value);
  } else if (window.marked && typeof window.marked.parse === 'function') {
    return window.marked.parse(translatedText.value.replace(/\[\[(.*?)\]\]/g, '<strong>$1</strong>'));
  } else {
    return translatedText.value;
  }
});

// Watch for text changes to update the provider
watch(() => props.originalText, () => {
  // Update original texts when prop changes
  originalTexts.value = {
    explanation: props.originalText || ''
  };
});
</script>

<style scoped>
.sidebar-explanation {
  padding: 15px;
  overflow-y: auto;
}

.explanation-loading {
  color: var(--sidebar-color);
  font-style: italic;
  text-align: center;
  padding: 20px;
}

.explanation-content {
  color: var(--sidebar-color);
  font-size: 0.9rem;
  line-height: 1.5;
}

.explanation-content :deep(h1),
.explanation-content :deep(h2),
.explanation-content :deep(h3) {
  color: var(--sidebar-color);
  margin-top: 1rem;
  margin-bottom: 0.5rem;
}

.explanation-content :deep(p) {
  margin-bottom: 1rem;
}

.explanation-content :deep(strong) {
  color: var(--primary-color);
  font-weight: 600;
}
</style>