---
import Footer from '@layouts/Footer.astro';
import VerticalSideBarLayout from '@layouts/VerticalSideBarLayout.astro';
import { getUbiquitousLanguageWithSubdomains } from '@utils/collections/domains';
import { buildUrl } from '@utils/url-builder';
import { ClientRouter } from 'astro:transitions';
import * as LucideIcons from 'lucide-react';
import { RectangleGroupIcon } from '@heroicons/react/24/outline';

import { Page } from './_index.data';

export const prerender = Page.prerender;
export const getStaticPaths = Page.getStaticPaths;

// Get data
const props = await Page.getData(Astro);

const pageTitle = `${props.collection} | ${props.data.name}`.replace(/^\w/, (c) => c.toUpperCase());
const ubiquitousLanguageData = await getUbiquitousLanguageWithSubdomains(props);
const ubiquitousLanguage = ubiquitousLanguageData.domain;
const { subdomains, duplicateTerms } = ubiquitousLanguageData;
---

<VerticalSideBarLayout title={pageTitle} description={props.data.summary}>
  <main
    class="flex sm:px-6 docs-layout h-full bg-[rgb(var(--ec-page-bg))]"
    data-pagefind-body
    data-pagefind-meta={`title:${pageTitle}`}
  >
    <div class="flex docs-layout w-full">
      <div class="w-full lg:mr-2 pr-8 overflow-y-auto pt-6 pb-8 min-h-[50em]">
        {/* Title Section */}
        <div class="relative border-b border-[rgb(var(--ec-page-border))] mb-6 pb-6">
          <div class="xl:flex xl:items-start xl:justify-between">
            <div class="min-w-0 flex-1">
              <h1 class="text-xl font-bold leading-7 text-[rgb(var(--ec-page-text))] sm:text-2xl xl:text-3xl">
                Ubiquitous Language
              </h1>
              <p class="mt-2 text-sm text-[rgb(var(--ec-page-text-muted))]">
                Browse and discover ubiquitous language terms in the {props.data.name} domain{
                  subdomains.length > 0 ? ' and its subdomains' : ''
                }
              </p>
            </div>

            <div class="mt-4 xl:mt-0 xl:ml-4 xl:flex-shrink-0">
              <div class="relative w-full xl:w-80">
                <input
                  type="text"
                  id="searchInput"
                  placeholder="Search terms..."
                  class="w-full px-4 py-2.5 pl-10 border border-[rgb(var(--ec-input-border))] rounded-lg focus:ring-2 focus:ring-[rgb(var(--ec-accent))] focus:border-[rgb(var(--ec-accent))] text-sm bg-[rgb(var(--ec-input-bg))] text-[rgb(var(--ec-input-text))] placeholder:text-[rgb(var(--ec-input-placeholder))] transition-colors"
                />
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <svg class="h-4 w-4 text-[rgb(var(--ec-icon-color))]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                  </svg>
                </div>
              </div>
              <div class="mt-2 text-right">
                <span
                  class="inline-flex items-center px-2 py-1 text-xs font-medium text-[rgb(var(--ec-page-text-muted))] bg-[rgb(var(--ec-card-bg,var(--ec-page-bg)))] border border-[rgb(var(--ec-page-border))] rounded-md"
                  id="resultsCount"
                >
                  {/* This will be updated by JavaScript */}
                </span>
              </div>
            </div>
          </div>
        </div>

        {
          !ubiquitousLanguage && subdomains.length === 0 && (
            <div class="flex flex-col items-center justify-center py-16 px-4">
              <div class="flex items-center justify-center w-16 h-16 rounded-full bg-[rgb(var(--ec-card-bg,var(--ec-page-bg)))] border border-[rgb(var(--ec-page-border))] mb-4">
                {(() => {
                  const BookOpen = LucideIcons.BookOpen;
                  //@ts-ignore
                  return <BookOpen className="w-8 h-8 text-[rgb(var(--ec-icon-color))]" />;
                })()}
              </div>
              <h3 class="text-lg font-medium text-[rgb(var(--ec-page-text))] mb-2">No ubiquitous language defined</h3>
              <p class="text-sm text-[rgb(var(--ec-page-text-muted))] text-center max-w-md">
                This domain does not have any defined ubiquitous language terms yet. Consider adding some terms to help establish
                a common vocabulary for your domain.
              </p>
            </div>
          )
        }

        <div class="py-4 w-full min-h-[calc(100vh-10em)]">
          {
            (ubiquitousLanguage || subdomains.some((s) => s.ubiquitousLanguage)) && (
              <div>
                {/* Domain Language Section */}
                {ubiquitousLanguage && (
                  <div class="mb-10" data-domain-section="main">
                    <div class="flex items-center justify-between mb-5">
                      <div class="flex items-center gap-3">
                        {/* <div class="flex items-center justify-center w-8 h-8 rounded-lg bg-gray-900">
                          <RectangleGroupIcon className="w-4 h-4 text-white" />
                        </div> */}
                        <h3 class="text-xl font-semibold text-[rgb(var(--ec-page-text))]">
                          {props.data.name} Domain Language
                          <span class="ml-1 text-sm font-normal text-[rgb(var(--ec-page-text-muted))]">
                            ({ubiquitousLanguage?.data?.dictionary?.length || 0} terms)
                          </span>
                        </h3>
                      </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4" data-terms-grid="main">
                      {ubiquitousLanguage?.data?.dictionary?.map((term) => (
                        <a
                          href={buildUrl(`/docs/${props.collection}/${props.data.id}/language/${term.id}`)}
                          class={`term-card group block bg-[rgb(var(--ec-card-bg,var(--ec-page-bg)))] border rounded-lg p-5 transition-all duration-200 hover:shadow-md hover:border-[rgb(var(--ec-accent)/0.5)] hover:-translate-y-0.5 ${duplicateTerms.has(term.name.toLowerCase()) ? 'border-orange-500/50 dark:border-orange-500/30' : 'border-[rgb(var(--ec-page-border))]'}`}
                          data-domain="main"
                        >
                          <div class="flex flex-col h-full">
                            <div class="flex items-start justify-between gap-3 mb-3">
                              <div class="flex items-center gap-2.5">
                                {term.icon ? (
                                  <div class="flex items-center justify-center w-8 h-8 rounded-md bg-[rgb(var(--ec-accent-subtle))] transition-colors">
                                    {(() => {
                                      const Icon = LucideIcons[term.icon as keyof typeof LucideIcons];
                                      //@ts-ignore
                                      return Icon ? <Icon className="w-4 h-4 text-[rgb(var(--ec-accent))]" /> : null;
                                    })()}
                                  </div>
                                ) : (
                                  <div class="flex items-center justify-center w-8 h-8 rounded-md bg-[rgb(var(--ec-accent-subtle))] transition-colors">
                                    {(() => {
                                      const BookText = LucideIcons.BookText;
                                      //@ts-ignore
                                      return <BookText className="w-4 h-4 text-[rgb(var(--ec-accent))]" />;
                                    })()}
                                  </div>
                                )}
                                <h4
                                  class={`text-base font-semibold group-hover:text-[rgb(var(--ec-icon-hover))] transition-colors ${duplicateTerms.has(term.name.toLowerCase()) ? 'text-orange-500 dark:text-orange-400' : 'text-[rgb(var(--ec-page-text))]'}`}
                                >
                                  {term.name}
                                </h4>
                              </div>
                              {duplicateTerms.has(term.name.toLowerCase()) && (
                                <span class="flex-shrink-0 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-orange-500/10 text-orange-500 dark:text-orange-400 border border-orange-500/20">
                                  Duplicate
                                </span>
                              )}
                            </div>
                            <p class="summary-text text-[rgb(var(--ec-page-text-muted))] text-sm leading-relaxed line-clamp-3 flex-grow mb-3">
                              {term.summary}
                            </p>
                            <div class="pt-3 border-t border-[rgb(var(--ec-page-border))]">
                              <span class="inline-flex items-center text-sm text-[rgb(var(--ec-page-text-muted))] font-medium group-hover:text-[rgb(var(--ec-page-text))]">
                                View details
                                <svg
                                  class="ml-1 w-4 h-4 transition-transform group-hover:translate-x-0.5"
                                  fill="none"
                                  stroke="currentColor"
                                  viewBox="0 0 24 24"
                                >
                                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                                </svg>
                              </span>
                            </div>
                          </div>
                        </a>
                      ))}
                    </div>
                    <div
                      class="hidden domain-no-results text-center py-12 bg-[rgb(var(--ec-card-bg,var(--ec-page-bg)))] rounded-lg border border-[rgb(var(--ec-page-border))] border-dashed"
                      data-domain-no-results="main"
                    >
                      <div class="flex items-center justify-center w-12 h-12 mx-auto mb-4 rounded-full bg-[rgb(var(--ec-content-hover))]">
                        <svg
                          class="w-6 h-6 text-[rgb(var(--ec-icon-color))]"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                          />
                        </svg>
                      </div>
                      <h4 class="text-base font-medium text-[rgb(var(--ec-page-text))]">
                        No matching terms in {props.data.name}
                      </h4>
                      <p class="mt-1 text-sm text-[rgb(var(--ec-page-text-muted))]">Try adjusting your search terms.</p>
                    </div>
                  </div>
                )}

                {/* Subdomain Language Sections */}
                {subdomains
                  .filter((s) => s.ubiquitousLanguage)
                  .map(({ subdomain, ubiquitousLanguage: subdomainUL }) => (
                    <div class="mb-10" data-domain-section={subdomain.data.id}>
                      <div class="flex items-center justify-between mb-5">
                        <div class="flex items-center gap-3">
                          {/* <div class="flex items-center justify-center w-8 h-8 rounded-lg bg-gray-200">
                            <RectangleGroupIcon className="w-4 h-4 text-gray-700" />
                          </div> */}
                          <h3 class="text-xl font-semibold text-[rgb(var(--ec-page-text))]">
                            {subdomain.data.name} Domain Language
                            <span class="ml-1 text-sm font-normal text-[rgb(var(--ec-page-text-muted))]">
                              ({subdomainUL?.data?.dictionary?.length || 0} terms)
                            </span>
                          </h3>
                        </div>
                        <a
                          href={buildUrl(`/docs/domains/${subdomain.data.id}/${subdomain.data.version}`)}
                          class="inline-flex items-center text-sm text-[rgb(var(--ec-page-text-muted))] hover:text-[rgb(var(--ec-page-text))] font-medium transition-colors"
                        >
                          View Domain
                          <svg class="ml-1 w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                          </svg>
                        </a>
                      </div>
                      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4" data-terms-grid={subdomain.data.id}>
                        {subdomainUL?.data?.dictionary?.map((term) => (
                          <a
                            href={buildUrl(`/docs/${props.collection}/${subdomain.data.id}/language/${term.id}`)}
                            class={`term-card group block bg-[rgb(var(--ec-card-bg,var(--ec-page-bg)))] border rounded-lg p-5 transition-all duration-200 hover:shadow-md hover:border-[rgb(var(--ec-accent)/0.5)] hover:-translate-y-0.5 ${duplicateTerms.has(term.name.toLowerCase()) ? 'border-orange-500/50 dark:border-orange-500/30' : 'border-[rgb(var(--ec-page-border))]'}`}
                            data-domain={subdomain.data.id}
                          >
                            <div class="flex flex-col h-full">
                              <div class="flex items-start justify-between gap-3 mb-3">
                                <div class="flex items-center gap-2.5">
                                  {term.icon ? (
                                    <div class="flex items-center justify-center w-8 h-8 rounded-md bg-[rgb(var(--ec-accent-subtle))] transition-colors">
                                      {(() => {
                                        const Icon = LucideIcons[term.icon as keyof typeof LucideIcons];
                                        //@ts-ignore
                                        return Icon ? <Icon className="w-4 h-4 text-[rgb(var(--ec-accent))]" /> : null;
                                      })()}
                                    </div>
                                  ) : (
                                    <div class="flex items-center justify-center w-8 h-8 rounded-md bg-[rgb(var(--ec-accent-subtle))] transition-colors">
                                      {(() => {
                                        const BookText = LucideIcons.BookText;
                                        //@ts-ignore
                                        return <BookText className="w-4 h-4 text-[rgb(var(--ec-accent))]" />;
                                      })()}
                                    </div>
                                  )}
                                  <h4
                                    class={`text-base font-semibold group-hover:text-[rgb(var(--ec-icon-hover))] transition-colors ${duplicateTerms.has(term.name.toLowerCase()) ? 'text-orange-500 dark:text-orange-400' : 'text-[rgb(var(--ec-page-text))]'}`}
                                  >
                                    {term.name}
                                  </h4>
                                </div>
                                {duplicateTerms.has(term.name.toLowerCase()) && (
                                  <span class="flex-shrink-0 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-orange-500/10 text-orange-500 dark:text-orange-400 border border-orange-500/20">
                                    Duplicate
                                  </span>
                                )}
                              </div>
                              <p class="summary-text text-[rgb(var(--ec-page-text-muted))] text-sm leading-relaxed line-clamp-3 flex-grow mb-3">
                                {term.summary}
                              </p>
                              <div class="pt-3 border-t border-[rgb(var(--ec-page-border))]">
                                <span class="inline-flex items-center text-sm text-[rgb(var(--ec-page-text-muted))] font-medium group-hover:text-[rgb(var(--ec-page-text))]">
                                  View details
                                  <svg
                                    class="ml-1 w-4 h-4 transition-transform group-hover:translate-x-0.5"
                                    fill="none"
                                    stroke="currentColor"
                                    viewBox="0 0 24 24"
                                  >
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                                  </svg>
                                </span>
                              </div>
                            </div>
                          </a>
                        ))}
                      </div>
                      <div
                        class="hidden domain-no-results text-center py-12 bg-[rgb(var(--ec-card-bg,var(--ec-page-bg)))] rounded-lg border border-[rgb(var(--ec-page-border))] border-dashed"
                        data-domain-no-results={subdomain.data.id}
                      >
                        <div class="flex items-center justify-center w-12 h-12 mx-auto mb-4 rounded-full bg-[rgb(var(--ec-content-hover))]">
                          <svg
                            class="w-6 h-6 text-[rgb(var(--ec-icon-color))]"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path
                              stroke-linecap="round"
                              stroke-linejoin="round"
                              stroke-width="2"
                              d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                            />
                          </svg>
                        </div>
                        <h4 class="text-base font-medium text-[rgb(var(--ec-page-text))]">
                          No matching terms in {subdomain.data.name}
                        </h4>
                        <p class="mt-1 text-sm text-[rgb(var(--ec-page-text-muted))]">Try adjusting your search terms.</p>
                      </div>
                    </div>
                  ))}
              </div>
            )
          }
        </div>

        <Footer />
      </div>
    </div>
    <ClientRouter />
  </main>

  <script>
    function initializeSearch() {
      const searchInput = document.getElementById('searchInput');
      const domainSections = document.querySelectorAll('[data-domain-section]');
      const resultsCount = document.getElementById('resultsCount');

      function updateResults() {
        //@ts-ignore
        const searchTerm = searchInput?.value.toLowerCase() || '';
        let totalVisibleTerms = 0;
        let totalTerms = 0;

        // Handle search for each domain section
        domainSections.forEach((section) => {
          const domainId = section.getAttribute('data-domain-section');
          const domainCards = section.querySelectorAll('.term-card');
          const domainNoResults = section.querySelector(`[data-domain-no-results="${domainId}"]`);
          let domainVisibleCount = 0;

          domainCards.forEach((card) => {
            totalTerms++;
            const title = card.querySelector('h4')?.textContent?.toLowerCase() || '';
            const description = card.querySelector('p')?.textContent?.toLowerCase() || '';
            const matches = searchTerm === '' || title.includes(searchTerm) || description.includes(searchTerm);

            card.classList.toggle('hidden', !matches);
            if (matches) {
              domainVisibleCount++;
              totalVisibleTerms++;
            }
          });

          // Show/hide domain-specific no results message
          if (domainNoResults) {
            if (searchTerm.trim() === '') {
              domainNoResults.classList.add('hidden');
            } else {
              domainNoResults.classList.toggle('hidden', domainVisibleCount > 0);
            }
          }
        });

        // Update results count
        if (resultsCount) {
          resultsCount.textContent = `Showing ${totalVisibleTerms} terms`;
        }
      }

      searchInput?.addEventListener('input', updateResults);

      // Initialize results count
      updateResults();
    }

    function initializeShowMore() {
      const cards = document.querySelectorAll('.term-card');
      cards.forEach((card) => {
        const summary = card.querySelector('.summary-text');
        if (summary) {
          summary.classList.add('visible');
        }
      });
    }

    function highlightMatchingTerm() {
      const urlParams = new URLSearchParams(window.location.search);
      const termId = urlParams.get('id');

      if (termId) {
        const cards = document.querySelectorAll('.term-card');
        cards.forEach((card) => {
          const termName = card.querySelector('h3')?.textContent?.trim();
          if (termName?.toLowerCase() === termId.toLowerCase()) {
            // Add highlight class
            card.classList.add('highlighted');
            (card as HTMLElement).click();

            setTimeout(() => {
              // Scroll into view
              card.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }, 300);
          }
        });
      }
    }

    document.addEventListener('astro:page-load', () => {
      initializeShowMore();
      initializeSearch();
      highlightMatchingTerm();
    });

    initializeShowMore();
    initializeSearch();
    highlightMatchingTerm();
  </script>

  <style is:global>
    .term-card.highlighted {
      border-color: #111827;
      box-shadow: 0 0 0 2px #111827;
      animation: pulse 1s;
    }

    @keyframes pulse {
      0%,
      100% {
        transform: scale(1);
        box-shadow: 0 0 0 2px #111827;
      }
      50% {
        transform: scale(1.01);
        box-shadow: 0 0 0 4px #111827;
      }
    }

    .line-clamp-3 {
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
  </style>
</VerticalSideBarLayout>
