<template>
  <div class="container-fluid px-0">
    <header class="navbar navbar-dark bg-dark shadow-sm sticky-top" style="z-index: 1040;">
      <div class="container-fluid position-relative d-flex justify-content-center align-items-center p-2">
        
        <div class="position-absolute start-0 ps-3 d-flex align-items-center">
          <button 
            class="btn btn-outline-light d-lg-none border-0 me-2" 
            @click="isMobileMenuOpen = true"
            aria-label="Toggle navigation">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-list" viewBox="0 0 16 16">
              <path fill-rule="evenodd" d="M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5z"/>
            </svg>
          </button>
          <RouterLink to="/" class="d-flex align-items-center text-decoration-none text-white">
            <img src="@/assets/logo.png" alt="Logo" width="40" height="40" class="d-block" />
          </RouterLink>
        </div>

        <h1 class="navbar-brand mb-0 h1 d-none d-sm-block">AccessiVue - {{ componentData?.name || 'Loading...' }}</h1>
        <h1 class="navbar-brand mb-0 h1 d-block d-sm-none">AccessiVue</h1>

        <div class="position-absolute end-0 pe-3">
          <RouterLink to="/about" class="btn btn-sm btn-outline-light">Sobre el projecte</RouterLink>
        </div>
      </div>
    </header>

    <div 
      class="offcanvas offcanvas-start text-bg-dark" 
      tabindex="-1" 
      :class="{ 'show': isMobileMenuOpen }" 
      style="visibility: visible;" 
      v-if="isMobileMenuOpen">
      
      <div class="offcanvas-header border-bottom border-secondary">
        <h5 class="offcanvas-title">En aquesta pàgina</h5>
        <button type="button" class="btn-close btn-close-white" @click="isMobileMenuOpen = false"></button>
      </div>
      
      <div class="offcanvas-body">
        <h6 class="text-uppercase text-muted fw-bold mb-3 small">Components</h6>
        <div class="list-group list-group-flush mb-4 rounded repo-nav">
            <RouterLink v-for="c in allComponents" :key="c.slug" :to="`/component/${c.slug}`"
              class="list-group-item list-group-item-action bg-dark text-white border-secondary repo-nav-item"
              :class="{ 'active': c.slug === currentSlug }"
              @click.prevent="navigateAndReload(`/component/${c.slug}`)">
              {{ c.name }}
            </RouterLink>
        </div>
      </div>
    </div>
    
    <div v-if="isMobileMenuOpen" class="offcanvas-backdrop fade show" @click="isMobileMenuOpen = false"></div>

    <main id="main" class="container-fluid" role="main" tabindex="-1">
      <div v-if="componentData" class="row g-4 justify-content-center">
        
        <div class="col-lg-2 d-none d-lg-block border-end border-secondary-subtle pt-5">
          <div class="position-sticky" style="top: 80px; max-height: 90vh; overflow-y: auto;">
            <h2 class="mb-3 ps-2 text-secondary">Components</h2>
            <div class="list-group list-group-flush repo-nav">
              <RouterLink v-for="c in allComponents" :key="c.slug" :to="`/component/${c.slug}`"
                class="list-group-item list-group-item-action border-top border-bottom border-secondary repo-nav-item"
                :class="{ 'active': c.slug === currentSlug }"
                @click.prevent="navigateAndReload(`/component/${c.slug}`)">
                {{ c.name }}
              </RouterLink>
            </div>
          </div>
        </div>

        <div class="col-12 col-lg-8 pt-5 ps-4">

          <h1 class="mb-4 text-center">{{ componentData.name }}</h1>

          <section class="mb-5" id="overview">
            <h2 class="mb-3">Visió General</h2>
            <p class="lead">{{ componentData.description }}</p>
            <div class="d-flex flex-wrap gap-2 mb-4">
              <span v-for="tag in componentData.functionality" :key="tag" class="badge bg-primary fs-6">{{ tag }}</span>
              <span class="badge bg-secondary fs-6">{{ componentData.complexity }}</span>
            </div>
            <div class="card bg-light">
              <div class="card-body">
                <h3 class="card-title">Característiques</h3>
                <ul class="mb-0 list-unstyled">
                  <li v-for="(feature, index) in componentData.features" :key="index" class="mb-2">
                    
                    <template v-if="typeof feature === 'object'">
                      <span :class="{ 'text-success fw-bold': feature.isA11y }">
                        <span v-if="feature.isA11y" class="me-1">*</span>
                        {{ feature.text }}
                      </span>
                      
                      <a v-if="feature.wcag" 
                        :href="feature.wcag" 
                        target="_blank" 
                        class="badge bg-secondary text-decoration-none ms-2"
                        title="Veure norma WCAG"
                        aria-label="Norma WCAG relacionada (obre en nova pestanya)">
                        WCAG <i class="bi bi-box-arrow-up-right" style="font-size: 0.7em;"></i>
                      </a>
                    </template>

                    <span v-else>{{ feature }}</span>

                  </li>
                </ul>
                <p class="small text-muted mt-3 mb-0">
                  <span class="text-success fw-bold">*</span> Característiques específiques d'accessibilitat.
                </p>
              </div>
            </div>
          </section>

          <section id="demo" class="mb-5">
            <h2 class="mb-3">Demostració en Viu</h2>
            <div class="card shadow-sm">
              <div class="card-body p-4">
                <div class="demo-container text-center">
                  <iframe v-if="iframeSrc" :src="iframeSrc" :title="`Demostració - ${componentData?.name || 'Demo'}`" style="width:100%; height:500px; border:none;"></iframe>
                </div>
              </div>
            </div>
          </section>

          <section id="props" class="mb-5">
            <h2 class="mb-3">Opcions (Props)</h2>

            <div class="card bg-light border-0 mb-4">
              <div class="card-body">
                <h3 class="h6 fw-bold text-primary mb-3 d-flex align-items-center">
                  <span class="info-icon me-2">i</span>
                  Què són les Props?
                </h3>
                <p class="small text-muted mb-2">
                  Imagina que aquest component és una màquina o un electrodomèstic. Les <strong>Props</strong>
                  (propietats) són els botons i la configuració que tu li poses abans d'engegar-lo.
                </p>
                <p class="small text-muted mb-3">
                  Serveixen per <strong>enviar informació cap a dins</strong> del component perquè sàpiga què ha de
                  mostrar (per exemple: la llista d'usuaris, el títol, o el color de fons).
                </p>

                <div class="p-3 bg-white rounded border border-secondary-subtle overflow-auto">
                  <p class="mb-1 fw-bold text-dark small">Exemple visual:</p>
                  <code class="d-block text-dark small" style="line-height: 1.6; white-space: pre;">
                    &lt;{{ componentData.component }}<br>
                    &nbsp;&nbsp;<span class="text-primary">:llista-items</span>="<span class="text-success">lesMevesDades</span>" <span class="text-muted fst-italic">// 1. Li passem les dades (variable)</span><br>
                    &nbsp;&nbsp;<span class="text-secondary">títol</span>="<span class="text-success">El meu Títol</span>" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="text-muted fst-italic">// 2. Li configurem el text (fix)</span><br>
                    /&gt;
                  </code>
                </div>
                <p class="small text-muted mt-2 mb-0 fst-italic">
                  * Nota: Posem dos punts <code>:</code> davant del nom quan li passem variables (dades que canvien), i
                  sense dos punts quan és text fix.
                </p>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table table-bordered table-hover align-middle">
                <thead class="table-light">
                  <tr>
                    <th style="min-width: 150px;">Nom de l'Opció (Prop)</th>
                    <th>Tipus</th>
                    <th>Valor Inicial</th>
                    <th>Per a què serveix?</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="prop in componentData.props" :key="prop.name">
                    <td>
                      <code class="fw-bold text-primary">{{ prop.name }}</code>
                      <span v-if="prop.required" class="badge bg-danger ms-2" style="font-size: 0.7em;">Obligatori</span>
                    </td>
                    <td><span class="badge bg-secondary text-light font-monospace">{{ prop.type }}</span></td>
                    <td><code class="text-muted">{{ prop.default }}</code></td>
                    <td class="text-secondary small">{{ prop.description }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </section>

          <section id="events" class="mb-5">
            <h2 class="mb-3">Esdeveniments</h2>

            <div class="card bg-light border-0 mb-4">
              <div class="card-body">
                <h3 class="h6 fw-bold text-primary mb-3 d-flex align-items-center">
                  <span class="info-icon me-2">i</span>
                  Què són els Esdeveniments?
                </h3>
                <p class="small text-muted mb-2">
                  Si les Props entren dades, els <strong>Esdeveniments</strong> (Events) treuen avisos <strong>cap a
                    fora</strong>. Són com les notificacions del teu mòbil.
                </p>
                <p class="small text-muted mb-3">
                  El component utilitza els esdeveniments per avisar-te quan l'usuari fa alguna acció important (com fer
                  clic a un botó, seleccionar una opció o enviar un formulari). Tu pots "escoltar" aquests avisos per
                  guardar les dades o mostrar missatges.
                </p>

                <div class="p-3 bg-white rounded border border-secondary-subtle overflow-auto">
                  <p class="mb-1 fw-bold text-dark small">Exemple visual:</p>
                  <code class="d-block text-dark small" style="line-height: 1.6; white-space: pre;">
                    &lt;{{ componentData.component }}<br>
                    &nbsp;&nbsp;<span class="text-danger">@guardar</span>="<span class="text-primary">gestionarLesDades</span>" <span class="text-muted fst-italic">// Quan el component avisi de 'guardar', executem la funció</span><br>
                    /&gt;
                  </code>
                </div>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table table-bordered table-hover align-middle">
                <thead class="table-light">
                  <tr>
                    <th style="min-width: 150px;">Nom de l'Avís (Event)</th>
                    <th>Dades que envia</th>
                    <th>Quan passa?</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="event in componentData.events" :key="event.name">
                    <td><code class="text-danger fw-bold">@{{ event.name }}</code></td>
                    <td><code>{{ event.params }}</code></td>
                    <td class="text-secondary small">{{ event.description }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </section>

          <section id="code" class="mb-5">
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-3 gap-3">
              <h2 class="m-0">Codi Font</h2>

              <div class="btn-group" role="group" aria-label="Mode de visualització del codi">
                <button type="button" class="btn btn-outline-primary" :class="{ active: codeViewMode === 'explained' }"
                  @click="codeViewMode = 'explained'">
                  Separat per parts
                </button>
                <button type="button" class="btn btn-outline-primary" :class="{ active: codeViewMode === 'full' }"
                  @click="codeViewMode = 'full'">
                  Fitxer Complet
                </button>
              </div>
            </div>

            <div v-if="codeViewMode === 'explained'" class="d-flex flex-column gap-4">

              <div class="card border-primary shadow-sm" v-if="parsedCode.template">
                <div class="card-header bg-primary text-white">
                  <h3 class="mb-0">{{ componentData.codeExplanation?.template?.title || 'Estructura (Template)' }}</h3>
                </div>
                <div class="card-body bg-light border-bottom">
                  <p class="mb-0">{{ componentData.codeExplanation?.template?.description || 'Definició de l\'estructura HTML.' }}</p>
                </div>
                <div class="card-body p-0">
                  <pre
                    class="m-0 rounded-0"><code class="language-html" ref="templateBlock">{{ parsedCode.template }}</code></pre>
                </div>
              </div>

              <div class="card border-success shadow-sm" v-if="parsedCode.script">
                <div class="card-header bg-success text-white">
                  <h3 class="mb-0">{{ componentData.codeExplanation?.script?.title || 'Lògica (Script)' }}</h3>
                </div>
                <div class="card-body bg-light border-bottom">
                  <p class="mb-0">{{ componentData.codeExplanation?.script?.description || 'Definició de la lògica i estat.' }}</p>
                </div>
                <div class="card-body p-0">
                  <pre
                    class="m-0 rounded-0"><code class="language-javascript" ref="scriptBlock">{{ parsedCode.script }}</code></pre>
                </div>
              </div>

              <div class="card border-info shadow-sm" v-if="parsedCode.style">
                <div class="card-header bg-info text-white">
                  <h3 class="mb-0">{{ componentData.codeExplanation?.style?.title || 'Estils (CSS)' }}</h3>
                </div>
                <div class="card-body bg-light border-bottom">
                  <p class="mb-0">{{ componentData.codeExplanation?.style?.description || 'Definició de l\'aparença.' }}
                  </p>
                </div>
                <div class="card-body p-0">
                  <pre
                    class="m-0 rounded-0"><code class="language-css" ref="styleBlock">{{ parsedCode.style }}</code></pre>
                </div>
              </div>

            </div>

            <div v-show="codeViewMode === 'full'" class="card bg-dark text-light">
              <div class="card-header d-flex justify-content-between align-items-center">
                <span class="text-truncate me-2">{{ componentData.name }} - Fitxer complet</span>
                <button class="btn btn-sm btn-outline-light text-nowrap" @click="copyCode">
                  {{ copied ? '✓ Copiat!' : 'Copiar Tot' }}
                </button>
              </div>
              <div class="card-body p-0">
                <pre class="m-0"><code class="language-html" ref="fullCodeBlock" v-text="codeContent"></code></pre>
              </div>
            </div>
          </section>

          <section id="exemples" class="mb-5">
            <h2 class="mb-4 border-bottom pb-2">Exemples d'ús</h2>
            <div class="card bg-light border-0 mb-4">
              <div class="card-body">
                <h3 class="h6 fw-bold text-primary mb-2">
                  <span class="info-icon" style="font-size: 1.2em; margin-right: 0.5rem;">i</span>
                  Com utilitzar els components?
                </h3>
                <p class="small text-muted mb-2">
                  A continuació trobaràs diversos exemples pràctics de com utilitzar aquest component en diferents
                  escenaris.
                  Cada exemple inclou una vista prèvia interactiva i el codi font corresponent dividit en HTML,
                  JavaScript i CSS.
                  Per utilitzar el component, ves a l'apartat "Codi Font", elegeix "Fitxer complet" i copia el codi complet del component. 
                  Després, enganxa'l al teu projecte Vue.
                  Llavors, adapta els codis segons les teves necessitats específiques, seguint els exemples.
                  En el codi trobaràs comentaris indicant què has de modificar o adaptar.
                </p>
                <p class="small text-muted mt-2 mb-0">
                  <strong>Consell:</strong> Ves al principi del codi per modificar el CSS i al final per modificar les dades.
                </p>
              </div>
            </div>
            <div v-for="(example, index) in componentData.examples" :key="index" class="card mb-5 shadow-sm border-0">
              <div class="card-header bg-light d-flex justify-content-between align-items-center py-3">
                <h4 class="m-0 h6">{{ example.title }}</h4>
                <span class="badge bg-primary">Exemple {{ index + 1 }}</span>
              </div>
              <div class="card-body">
                <p>{{ example.description }}</p>
                <div class="row g-0 border rounded overflow-hidden">
                  <div class="col-lg-6 bg-white border-end position-relative preview-area">
                    <div class="d-flex justify-content-between bg-light px-3 py-2 border-bottom">
                      <small class="text-uppercase fw-bold text-muted">Vista Prèvia</small>
                      <button class="btn btn-sm btn-link p-0" @click="reloadIframe(index)">Refrescar</button>
                    </div>
                    <div class="iframe-wrapper">
                      <iframe :ref="el => iframeRefs[index] = el" :title="`Exemple ${index + 1} - ${example.title}`" class="w-100 h-100 border-0"
                        style="min-height: 400px;"></iframe>
                    </div>
                  </div>
                  <div class="col-lg-6 bg-dark text-white code-area">
                    <div class="d-flex border-bottom border-secondary">
                      <button class="btn btn-sm btn-dark rounded-0 px-3 py-2"
                        :class="{ 'active-tab': activeTabs[index] === 'html' }"
                        @click="activeTabs[index] = 'html'">HTML</button>
                      <button class="btn btn-sm btn-dark rounded-0 px-3 py-2"
                        :class="{ 'active-tab': activeTabs[index] === 'js' }"
                        @click="activeTabs[index] = 'js'">JS</button>
                      <button class="btn btn-sm btn-dark rounded-0 px-3 py-2"
                        :class="{ 'active-tab': activeTabs[index] === 'css' }"
                        @click="activeTabs[index] = 'css'">CSS</button>
                    </div>
                    <div class="position-relative">
                      <pre v-show="activeTabs[index] === 'html'"
                        class="m-0 p-3 language-html"><code>{{ example.template }}</code></pre>
                      <pre v-show="activeTabs[index] === 'js'"
                        class="m-0 p-3 language-javascript"><code>{{ example.script }}</code></pre>
                      <pre v-show="activeTabs[index] === 'css'"
                        class="m-0 p-3 language-css"><code>{{ example.css || '/* Cap estil personalitzat */' }}</code></pre>
                      <button class="btn btn-sm btn-light position-absolute top-0 end-0 m-2 opacity-75"
                        @click="copyToClipboard(example, activeTabs[index])">Copiar</button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>

        </div>

        <div class="col-lg-2 d-none d-lg-block mx-auto pt-5">
          <div class="position-sticky" style="top: 80px;">
            <nav class="nav flex-column small component-nav" style="padding-left: 10%; padding-top: 5%;">
              <h3 class="text-muted mb-3 fs-5">En aquesta pàgina</h3>
              <a class="nav-link py-1" href="#overview">Visió General</a>
              <a class="nav-link py-1" href="#demo">Demostració</a>
              <a class="nav-link py-1" href="#props">Opcions</a>
              <a class="nav-link py-1" href="#events">Esdeveniments</a>
              <a class="nav-link py-1" href="#code">Codi Font</a>
              <a class="nav-link py-1" href="#exemples">Exemples</a>
            </nav>
          </div>
        </div>
      </div>

      <div v-else class="text-center py-5">
        <div class="spinner-border text-primary" role="status"></div>
        <p class="mt-3 text-muted">Carregant component...</p>
      </div>
    </main>
  </div>

  <footer class="bg-dark text-white text-center py-4 mt-auto">
    <div class="container">
      <p class="mb-1 small">Universitat de Barcelona - Enginyeria Informàtica</p>
      <p class="mb-0 text-white-50 small">&copy; 2026 Gemma Vallès. AccessiVue.</p>
    </div>
  </footer>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { useRoute, RouterLink } from 'vue-router'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'
import componentsData from '@/assets/componentsData.json'

const route = useRoute()
const allComponents = ref(componentsData)

// Estat del menú mòbil
const isMobileMenuOpen = ref(false)

const iframeSrc = ref('');
const fullCodeBlock = ref(null);
const templateBlock = ref(null);
const scriptBlock = ref(null);
const styleBlock = ref(null);

const codeContent = ref('');
const copied = ref(false);
const componentData = ref(null)
const iframeRefs = ref([])
const activeTabs = ref({})
const baseComponentCode = ref('');
const componentStyles = ref('');
const currentSlug = ref('');

const codeViewMode = ref('explained'); // 'explained' o 'full'
const parsedCode = ref({ template: '', script: '', style: '' });

// Tancar el menú mòbil en canviar de pàgina
watch(() => route.path, () => {
  isMobileMenuOpen.value = false
})

const loadComponentDetails = async () => {
  // Scroll to top quan es carrega un nou component
  try { window.scrollTo({ top: 0, left: 0, behavior: 'instant' }); } catch(e) { window.scrollTo(0,0); }
  const slug = route.params.componentName
  currentSlug.value = slug;

  // Reset
  iframeSrc.value = '';
  codeContent.value = '';
  activeTabs.value = {};
  iframeRefs.value = [];
  parsedCode.value = { template: '', script: '', style: '' };
  codeViewMode.value = 'explained'; // Default

  componentData.value = componentsData.find(c => c.slug === slug)
  document.title = componentData.value ? "AccessiVue - " + componentData.value.name : "AccessiVue";

  if (!componentData.value) return;

  await nextTick()

  // Default tab per a cada exemple
  if (componentData.value.examples) {
    componentData.value.examples.forEach((_, idx) => {
      activeTabs.value[idx] = 'html'
    })
  }

  try {
    const path = componentData.value.code.replace('@/', '/');
    const response = await fetch(path);
    codeContent.value = await response.text();

    // Extraure CSS
    const styleMatch = codeContent.value.match(/<style>([\s\S]*?)<\/style>/);
    parsedCode.value.style = styleMatch ? styleMatch[1].trim() : '';

    // Extraure Script
    // La lògica real està en el <script> que NO és el de Vue CDN.
    const scriptMatches = [...codeContent.value.matchAll(/<script>([\s\S]*?)<\/script>/g)];
    let fullScript = '';
    if (scriptMatches.length > 0) {
      // Obtenir l'última etiqueta script (normalment la definició del component)
      fullScript = scriptMatches[scriptMatches.length - 1][1];

      // Netejar les línies específiques de Vue per mostrar només l'objecte del component
      let cleanScript = fullScript
        .replace(/const\s*{\s*createApp.*?}\s*=\s*Vue;?/, '')
        .replace(/createApp\([\s\S]*?\)\.mount\(['"].*?['"]\);?/, '')
        .trim();

      parsedCode.value.script = cleanScript;
    }

    // Extraure Template
    const templateInJsMatch = fullScript.match(/template:\s*`([\s\S]*?)`/);
    if (templateInJsMatch) {
      parsedCode.value.template = templateInJsMatch[1].trim();
      // Si hem trobat la plantilla en JS, la retirem del JS mostrat per evitar duplicació
      parsedCode.value.script = parsedCode.value.script.replace(/template:\s*`[\s\S]*?`/, '// (Veure secció Template dalt)').trim();
    } else {
      // Fallback: buscar etiquetes <template> en el fitxer HTML
      const templateTagMatch = codeContent.value.match(/<template>([\s\S]*?)<\/template>/);
      parsedCode.value.template = templateTagMatch ? templateTagMatch[1].trim() : '';
    }

    // Emmagatzemar estils per a l'iframe demo
    if (styleMatch && styleMatch[1]) {
      componentStyles.value = styleMatch[1];
    }

    // Emmagatzemar la lògica per a l'iframe demo
    if (scriptMatches.length > 0) {
      let fs = scriptMatches[scriptMatches.length - 1][1];
      fs = fs.replace(/const\s*{\s*createApp\s*}\s*=\s*Vue;?/, '');
      fs = fs.replace(/createApp\([\s\S]*?\)\.mount\(['"].*?['"]\);?/, '');
      baseComponentCode.value = fs;
    }

    // Generar blob per a la demo principal
    const blob = new Blob([codeContent.value], { type: 'text/html' });
    iframeSrc.value = URL.createObjectURL(blob);

  } catch (err) {
    console.error(err);
    codeContent.value = `Error loading file: ${componentData.value.code}`;
  }

  await nextTick()
  highlightCode()
  renderPlaygrounds()
}

onMounted(loadComponentDetails);

watch(() => route.params.componentName, (newSlug) => {
  if (newSlug) loadComponentDetails();
});

// Re-highlight al canviar entre pestanyes
watch(codeViewMode, async () => {
  await nextTick();
  highlightCode();
});

function copyCode() {
  if (!codeContent.value) return
  navigator.clipboard.writeText(codeContent.value)
  copied.value = true
  setTimeout(() => (copied.value = false), 2000)
}

function highlightCode() {
  // Highlight els blocs principals si existeixen
  if (fullCodeBlock.value) hljs.highlightElement(fullCodeBlock.value);
  if (templateBlock.value) hljs.highlightElement(templateBlock.value);
  if (scriptBlock.value) hljs.highlightElement(scriptBlock.value);
  if (styleBlock.value) hljs.highlightElement(styleBlock.value);

  // Highlight els blocs d'exemple
  document.querySelectorAll('.code-area pre code').forEach(block => {
    hljs.highlightElement(block);
  });
}

function renderPlaygrounds() {
  if (!componentData.value.examples) return;
  componentData.value.examples.forEach((example, index) => {
    generateIframeContent(index, example)
  })
}

function reloadIframe(index) {
  const example = componentData.value.examples[index];
  generateIframeContent(index, example);
}

function generateIframeContent(index, example) {
  const iframe = iframeRefs.value[index]
  if (!iframe) return

  const baseCode = baseComponentCode.value.trim();
  const match = baseCode.match(/const\s+(\w+)\s*=\s*\{/);
  const componentName = match ? match[1] : null;

  const htmlContent = `
    <!DOCTYPE html>
    <html>
    <head>
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
      <style>
        ${componentStyles.value}
        body { padding: 1rem; background-color: #f8f9fa; }
        ${example.css || ''}
      </style>
      <script src="https://unpkg.com/vue@3/dist/vue.global.js"><\/script>
    </head>
    <body>
      <div id="app">
        ${example.template}
      </div>
      <script>
        const { createApp } = Vue;
        try {
            ${baseCode}
            function getExampleData() {
               ${example.script}
            }
            const app = createApp({
              components: {
                'accessible-form': ${componentName},
                'search-box': ${componentName},
                'crud-component': ${componentName},
                'resource-library': ${componentName},
                'draggable-board': ${componentName},
                '${componentName}': ${componentName}
              },
              data() {
                const d = getExampleData();
                if (d && typeof d.data === 'function') {
                  try { return d.data(); } catch (err) { return {}; }
                }
                if (d && typeof d === 'object') return d;
                return {};
              },
              methods: {
                handleSubmit(data) { console.log(data); alert('Comprova la consola.'); },
                handleSelect(item) { console.log(item); alert('Selected: ' + (item.title || item.name || item.login)); },
                onSelect(item) { console.log(item); alert('Selected: ' + (item.title || item.name)); },
                handleFilterChange(filters) { console.log(filters); }
              }
            });
            app.mount('#app');
        } catch (err) {
          document.body.innerHTML = '<div class="alert alert-danger">Error: ' + err.message + '</div>';
        }
      <\/script>
    </body>
    </html>
  `
  const blob = new Blob([htmlContent], { type: 'text/html' })
  iframe.src = URL.createObjectURL(blob)
}

function copyToClipboard(example, type) {
  let text = '';
  if (type === 'html') text = example.template;
  if (type === 'js') text = example.script;
  if (type === 'css') text = example.css;
  navigator.clipboard.writeText(text);
}

// Navegar a un nou component i recarregar la pàgina
function navigateAndReload(path) {
  window.location.assign(path);
}
</script>

<style scoped>
@import "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css";

[v-cloak] {
  display: none;
}

.info-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background-color: #003e9b;
  color: white;
  border-radius: 50%;
  font-family: serif;
  font-weight: bold;
  font-style: italic;
  font-size: 14px;
  line-height: 1;
}

.demo-container {
  border: 2px dashed #ccc;
  border-radius: 10px;
  padding: 2rem;
}

.active-tab {
  border-bottom: 2px solid #4299e1;
  background-color: #343a40;
  color: white;
}

pre {
  max-height: 500px;
  overflow: auto;
  white-space: pre-wrap;
}

.card-header h5 {
  font-weight: 600;
  font-size: 1rem;
}

.offcanvas {
  transition: transform 0.3s ease-in-out;
}

/* Nav esquerra */
.repo-nav .repo-nav-item {
  border: 0 !important;
  padding: 0.45rem 0.75rem;
  color: #24292f !important;
  background: transparent !important;
  border-left: 3px solid transparent;
  border-radius: 0;
  font-weight: 500;
}
.repo-nav .repo-nav-item:hover {
  background: #f6f8fa !important;
  color: #0366d6 !important;
}
.repo-nav .repo-nav-item.active {
  background: transparent !important;
  color: #0366d6 !important;
  border-left-color: #0366d6 !important;
  font-weight: 600;
}

/* Nav dreta */
.component-nav {
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  padding: 6px;
  background: #fafbfc;
}
.component-nav .nav-link {
  color: #57606a;
  padding: 0.45rem 0.75rem;
  border-left: 3px solid transparent;
  border-radius: 3px;
  margin: 2px 0;
}
.component-nav .nav-link:hover {
  background: #f6f8fa;
  color: #0366d6;
}
.component-nav .nav-link.active {
  background: transparent;
  color: #0366d6;
  border-left-color: #0366d6;
  font-weight: 600;
}

.navbar-brand {
    margin-right: 0 !important;
}

/* Marge al utilitzar la navegació */
section[id] {
  scroll-margin-top: 80px;
}

@media (max-width: 576px) {
  section[id] {
    scroll-margin-top: 64px;
  }
}

/* Accessibilitat */
.card.bg-light .badge.bg-secondary.text-light {
  background-color: #6c757d !important;
  color: #ffffff !important;
}

.card.bg-light code.hljs,
.card.bg-light pre code.hljs {
  background: transparent !important;
  color: #0b2433 !important;
}

.card.bg-light code .hljs-name,
.card.bg-light code .hljs-keyword,
.card.bg-light code .hljs-title,
.card.bg-light code .hljs-string {
  color: #0b3a66 !important;
}

.card.bg-light .small.text-muted,
.card.bg-light .text-secondary.small {
  color: #495057 !important;
}

.badge.bg-secondary.text-light {
  background-color: #545b62 !important;
  color: #ffffff !important;
  border: 1px solid rgba(0,0,0,0.08);
}
.code-area pre, .card.bg-light pre, pre.m-0 {
  background: #f1f5f9 !important;
  color: white !important;
}
.code-area pre code.hljs, .card.bg-light code.hljs, code.language-html.hljs {
  color: white !important;
}
.code-area pre code.hljs .hljs-name,
.card.bg-light code.hljs .hljs-name,
code.hljs .hljs-name {
  color: #0b3a66 !important;
}
.code-area pre code.hljs .hljs-keyword,
.card.bg-light code.hljs .hljs-keyword {
  color: #b83280 !important;
}

.card.bg-light .badge.bg-primary {
  color: #ffffff !important;
}
.repo-nav .repo-nav-item,
.component-nav .nav-link {
  color: #212529 !important;
}
.repo-nav .repo-nav-item:hover,
.component-nav .nav-link:hover {
  color: #0b3a66 !important;
}

code.hljs, pre code.hljs, code.language-html.hljs, code.language-xml.hljs, code.language-javascript.hljs {
  background: black !important;
  color: white !important;
}

code.hljs span.hljs-tag,
code.hljs span.hljs-name,
code.hljs span.hljs-attr,
code.hljs span.hljs-string,
code.hljs span.hljs-keyword,
code.hljs span.hljs-built_in,
code.hljs span.hljs-literal,
code.hljs span.hljs-title,
code.hljs span.hljs-function,
code.hljs span.hljs-class {
  color: #0b3a66 !important;
}

code.hljs span.hljs-number,
code.hljs span.hljs-params,
code.hljs span.hljs-doctag {
  color: #b83280 !important;
}

.code-area pre, .code-area pre code.hljs {
  background: #0b1220 !important;
  color: #e6eef3 !important;
}
.code-area pre code.hljs span.hljs-name,
.code-area pre code.hljs span.hljs-tag,
.code-area pre code.hljs span.hljs-title,
.code-area pre code.hljs span.hljs-string {
  color: #8ab4ff !important;
}
.code-area pre code.hljs span.hljs-keyword {
  color: #ff9aa2 !important;
}

code.hljs .hljs-comment,
.card.bg-light code.hljs .hljs-comment,
.code-area pre code.hljs .hljs-comment,
code.language-html.hljs .hljs-comment {
color: #ffffff !important;
opacity: 1 !important;
}
</style>