<script setup lang="ts">
import FixedLayout from '~/components/layouts/FixedLayout.vue';
import TableHeader from '~/components/parts/TableHeader.vue';
import ServerStatus from '~/components/parts/ServerStatus.vue';

import ContactLinks from '~/components/parts/ContactLinks.vue';

import { useSeo } from '~/composables/seo'

import Place from '~/components/widgets/Place.vue';

const { get, post } = useApi();
const { locale } = useI18n();
const { t } = useI18n();

useSeo({
  title: 'Home',
  description: 'Aran Roig — Developer, Artist & Designer. Exploring projects in software engineering, digital art, and interactive design.',
  canonicalUrl: '/',
  structuredData: {
    '@context': 'https://schema.org',
    '@type': 'WebPage',
    '@id': 'https://aranroig.com/#webpage',
    url: 'https://aranroig.com',
    name: 'Aran Roig — Developer, Artist & Designer',
    description: 'Personal website of Aran Roig — developer, artist, and designer.',
    inLanguage: ['en', 'es', 'ca'],
    publisher: {
      '@type': 'Person',
      name: 'Aran Roig'
    }
  }
});

useHead({
  script: [
    {
      type: 'application/ld+json',
      innerHTML: JSON.stringify({
        '@context': 'https://schema.org',
        '@type': 'Person',
        name: 'Aran Roig',
        url: 'https://aranroig.com',
        sameAs: [],
        jobTitle: 'Developer, Artist & Designer'
      })
    }
  ]
});

const currentPath = computed(() => route.path);
const route = useRoute();

const { data: markdown } = await useAsyncData(`fixed-root`, async () =>
 await queryCollection(`fixed`).path(`/fixed/${locale.value}/root`).first()
 ,{watch: [locale]})

const { data: projects } = await useAsyncData(`projects`, async () =>
 (await queryCollection(`projects`).where('path', 'LIKE', `/projects/${locale.value}/%`).all())
 .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()),
{ watch: [locale] })

const { data: posts } = await useAsyncData('blog-posts', 
 () => queryCollection(`blog`).where('path', 'LIKE', `/blog/${locale.value}/%`).order('date', 'DESC').all(),
 { watch: [locale] });

const { data: contactMarkdown } = await useAsyncData(`fixed-contact`, async () =>
 await queryCollection(`fixed`).path(`/fixed/${locale.value}/contact`).first()
 ,{watch: [locale]})

const localePath = useLocalePath();

function resolveProjectLink(project) {
  if (project.link) return project.link;
  const slugToProjectMap = {
    'dragonroll': 'https://dragonroll.aranroig.com',
  };
  return slugToProjectMap[project.slug] || null;
}

function navigateToProject(project) {
  const link = resolveProjectLink(project);
  if (link) window.open(link, '_blank', 'noopener,noreferrer');
}

const artPosts = useState<any[]>('art-posts', () => null as any);
if (!artPosts.value?.length) {
  const currentLocale = locale.value;
  (async () => {
    try {
      if (currentLocale === 'en') {
        artPosts.value = await queryCollection('art')
          .where('path', 'LIKE', `/art/en/%`)
          .order('date', 'DESC')
          .all();
      } else {
        const enPosts = await queryCollection('art')
          .where('path', 'LIKE', `/art/en/%`)
          .order('date', 'DESC')
          .all();
        const localePosts = await queryCollection('art')
          .where('path', 'LIKE', `/art/${currentLocale}/%`)
          .order('date', 'DESC')
          .all();
        const translatedSlugs = new Set(
          localePosts.map((p) => p.path.replace(`/art/${currentLocale}/`, ''))
        );
        const enFallbacks = enPosts.filter(
          (p) => !translatedSlugs.has(p.path.replace('/art/en/', ''))
        );
        artPosts.value = [...localePosts, ...enFallbacks].sort(
          (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
        );
      }
    } catch (e) {
      console.error('Error loading art posts:', e);
    }
  })();
}

const isArtFallback = (art) => art.path.startsWith('/art/en/') && locale.value !== 'en';

const HOME_BLOG_LIMIT = 3;
const HOME_ART_LIMIT = 6;

const displayedBlogPosts = computed(() => {
  const all = posts.value || [];
  return all.slice(0, HOME_BLOG_LIMIT);
});

const displayedArtPosts = computed(() => {
  const all = artPosts.value || [];
  return all.slice(0, HOME_ART_LIMIT);
});

onMounted(async () => {
  try {
    const response = await get('/test');
  } catch (error) {
    console.error('API Error:', error);
  }
});

function scrollToTop() {
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

function scrollToSection(e: Event, targetId: string) {
  e.preventDefault();
  const el = document.querySelector(targetId);
  if (el) {
    el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  } else {
    window.location.hash = targetId.substring(1);
  }
}

const sectionTargets = {
  index: '#top',
  blog: '#scroll-blog',
  contact: '#scroll-contact',
  art: '#scroll-art'
}

</script>

<template>
  <TableHeader></TableHeader>
  
   <h1 style="position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;">Aran Roig — Developer, Artist & Designer</h1>
   <div id="top" style="scroll-margin-top: 60px;">&nbsp;</div>

  <FixedLayout>
    <section class="intro-section">
      <div class="intro-layout">
        <div class="intro-content">
          <Container>
            <ContentRenderer v-if="markdown" :value="markdown"></ContentRenderer>
          </Container>
        </div>
        <div class="intro-sidebar">
          <ServerStatus />
        </div>
      </div>
    </section>

    <section class="normal-section" id="place">
      <Container>
        <h2 class="section-title">{{ t('pages.place_heading') }}</h2>
        <Place></Place>
      </Container>
    </section>

    <section class="normal-section projects-section" id="scroll-projects" v-if="projects && projects.length > 0">
      <Container>
        <h2 class="section-title">{{ t('pages.projects_heading') }}</h2>
        
        <div class="projects-grid">
          <div 
             v-for="project in projects" 

            :key="project.slug"
            class="project-card-wrapper"
          >
            <div 
              class="project-card" 
              @click="navigateToProject(project)" 
            >
              <div class="project-layout">
                <img 
                  v-if="project.preview" 
                  :src="project.preview" 
                  :alt="`Preview of ${project.title}`" 
                  class="project-preview"
                />
                <div class="project-info">
                  <p class="project-title">{{ project.title }}</p>
                  <p class="project-description">{{ project.description }}</p>
                  <div class="project-tech">
                    <span v-for="tech in project.tech" :key="tech" class="tech-tag">{{ tech }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

      </Container>
    </section>

    <section class="normal-section" id="scroll-blog">
      <Container>
        <h2 class="section-title">{{ t('pages.blog_heading') }}</h2>
        <ul class="tui-list">
          <li v-for="post in displayedBlogPosts" :key="post.slug" class="blog-entry">
            <NuxtLink :to="localePath({ name: 'blog-slug', params: { slug: post.slug } })" class="entry-link">
              <span class="entry-title">{{ post.title }}</span>
            </NuxtLink>
            <span class="entry-meta">[{{ post.date }}] {{ post.description }}</span>
          </li>
        </ul>
        <p v-if="posts && posts.length > 0" class="show-more-link">
          <NuxtLink :to="localePath('/blog')" class="tui-link">{{ t('pages.show_more') }}</NuxtLink>
        </p>
      </Container>
    </section>

    <section class="normal-section" id="scroll-art">
      <Container>
        <h2 class="section-title">{{ t('pages.art_heading') }}</h2>
        <div class="grid">
          <NuxtLink v-for="art in displayedArtPosts" :key="art.slug"
            class="selector"
            :to="localePath(`/art/${art.slug}`)">
              <span class="selector-border-top" aria-hidden="true">────────</span>
              <img
                :src="art.thumb"
                :alt="art.title"
                class="selector-img"
              />
              <span class="selector-border-bottom" aria-hidden="true">────────</span>
              <div class="overlay-label">{{ art.title }}</div>
          </NuxtLink>
        </div>
        <p v-if="artPosts && artPosts.length > 0" class="show-more-link">
          <NuxtLink :to="localePath('/art')" class="tui-link">{{ t('pages.show_more') }}</NuxtLink>
        </p>
      </Container>
    </section>

    <section class="normal-section" id="scroll-contact">
      <Container>
        <h2 class="section-title">{{ t('pages.contact_heading') }}</h2>
        <ContentRenderer v-if="contactMarkdown" :value="contactMarkdown"></ContentRenderer>
        <ContactLinks /> 
      </Container>
    </section>
  </FixedLayout>
  <Footer></Footer>
</template>

<style lang="scss" scoped>
.tui-frame:first-child {
  margin-top: 0;
  margin-right: 0;
}

.intro-section {

  .intro-layout {
    display: flex;
    gap: 16px;
    align-items: stretch;

    @media screen and (max-width: 1200px) {
      flex-direction: column;
    }
  }

  .intro-content {
    flex: 1;
    min-width: 0;
    margin: 0px;
  }

  .intro-sidebar {
    width: 220px;
    flex-shrink: 0;

    @media screen and (max-width: 1200px) {
      width: 100%;
    }
  }

  > div:first-child {
    margin-top: 0;
  }

  .tui-frame:last-child {
    margin-bottom: 0;
  }

  .tui-frame:last-child {
    margin-bottom: 0;
  }

  @media screen and (min-width: 1200px) {
    margin-top: 290px;
  }

  @media screen and (max-width: 1200px) and (min-width: 900px) {
    margin-top: 380px;
  }

  @media screen and (max-width: 900px) {
    margin-top: 100px;
  }

  @media screen and (max-width: 600px) {
      margin-top: 140px;
  }

  @media screen and (max-width: 480px) {
      margin-top: 180px;
  }
}

.normal-section {
  margin-top: 24px;
  
  .tui-frame:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-family: 'Hurmit', monospace;
  color: var(--color-text);
  font-size: 1.2rem;
  letter-spacing: 0.5px;
  margin: 28px 0 16px 0;
  padding-left: 12px;
  line-height: 1.3;

  &::before {
    content: "├";
    color: var(--color-link);
    margin-right: 8px;
    font-weight: normal;
  }

  &::after {
    content: '';
    display: inline-block;
    width: 6px;
    height: 6px;
    background-color: var(--color-link);
    margin-left: 10px;
    vertical-align: middle;
    box-shadow: 0 0 4px var(--color-link);
    animation: blink-cursor 1s steps(1) infinite;
  }
}

.section-title:first-child {
  margin-top: 20px;
}

@keyframes blink-cursor {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.projects-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.project-card {
  position: relative;
  background: var(--color-background-fore);
  border: 1px solid var(--color-border-color);
  box-shadow: 4px -4px 0px 0px var(--color-container-shadow);
  padding: 12px 16px;
  transition: all 0.1s steps(2, end);

  &::before {
    content: "[ PROJECT ]";
    position: absolute;
    top: -9px;
    left: 12px;
    background-color: var(--color-background-fore);
    padding: 0 6px;
    font-size: 0.65rem;
    color: var(--color-link);
    letter-spacing: 2px;
  }

  .project-layout {
    display: flex;
    gap: 16px;
  }

  .project-preview {
    width: 140px;
    min-width: 140px;
    height: 85px;
    object-fit: cover;
    border: 1px solid var(--color-border-color);
    image-rendering: auto;
    transition: border-color 0.1s steps(2, end);
  }

  .project-info {
    display: flex;
    flex-direction: column;
    gap: 6px;
    min-width: 0;
  }
}

.project-card-corner {
  position: absolute;
  width: 14px;
  height: 14px;
  border-color: #cfcfcf;

  &.tl { top: -1px; left: -1px; border-top: 2px solid; border-left: 2px solid; }
  &.tr { top: -1px; right: -1px; border-top: 2px solid; border-right: 2px solid; }
  &.bl { bottom: -1px; left: -1px; border-bottom: 2px solid; border-left: 2px solid; }
  &.br { bottom: -1px; right: -1px; border-bottom: 2px solid; border-right: 2px solid; }
}

.project-title {
  font-family: 'Hurmit', monospace;
  color: inherit;
  text-decoration: none;
  font-size: 1.05rem;
  text-shadow: inherit;

  &:hover {
    color: var(--color-link);
  }
}

.project-card {
  cursor: pointer;
}

.project-card-wrapper:hover .project-card {
  border-color: var(--color-link);
  box-shadow: 4px -4px 0px 0px var(--color-link);
}

.project-info {
  cursor: pointer;
}

.project-description {
  font-family: 'Hurmit', monospace;
  color: var(--color-text);
  margin: 8px 0 12px 0;
  line-height: 1.5;
  font-size: 0.9rem;
}

.project-tech {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tech-tag {
  font-family: 'Hurmit', monospace;
  font-size: 0.7rem;
  color: var(--color-background-fore);
  background-color: var(--color-link);
  padding: 1px 6px;
  box-shadow: 2px -2px 0px 0px rgba(0, 0, 0, 0.3);
  letter-spacing: 0.5px;
}

.stats-section {
  margin-top: 32px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.stat-card {
  position: relative;
  background: var(--color-background-fore);
  border: 2px solid var(--color-border-color);
  box-shadow: 
    inset 1px -1px 0px 0px rgba(0,0,0,0.3),
    4px -4px 0px 0px var(--color-container-shadow);
  padding: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  gap: 0;
  overflow: hidden;
  transition: all 0.1s steps(2, end);

  &:hover {
    border-color: var(--color-link);
    box-shadow: 
      inset 1px -1px 0px 0px rgba(0,0,0,0.3),
      4px -4px 0px 0px var(--color-link);
  }

  .stat-card-corner {
    position: absolute;
    width: 12px;
    height: 12px;
    border-color: #cfcfcf;

    &.tl { top: -1px; left: -1px; border-top: 2px solid; border-left: 2px solid; }
    &.tr { top: -1px; right: -1px; border-top: 2px solid; border-right: 2px solid; }
    &.bl { bottom: -1px; left: -1px; border-bottom: 2px solid; border-left: 2px solid; }
    &.br { bottom: -1px; right: -1px; border-bottom: 2px solid; border-right: 2px solid; }
  }
}

.stat-card-frame-top {
  position: absolute;
  top: -2px;
  left: 14px;
  right: 14px;
  height: 0;
  color: var(--color-border-color);
  font-family: 'Hurmit', monospace;
  font-size: 0;
  line-height: 0;
  white-space: nowrap;

  &::before {
    content: "═════";
  }
}

.stat-card-frame-bottom {
  position: absolute;
  bottom: -2px;
  left: 14px;
  right: 14px;
  height: 0;
  color: var(--color-border-color);
  font-family: 'Hurmit', monospace;
  font-size: 0;
  line-height: 0;
  white-space: nowrap;

  &::before {
    content: "═════";
  }
}

.stat-card-header {
  background-color: var(--color-link);
  color: var(--color-background-fore);
  padding: 3px 12px;
  font-family: 'Hurmit', monospace;
  font-size: 0.55rem;
  letter-spacing: 2px;
  text-transform: uppercase;
  width: 100%;
  text-align: center;
  box-shadow: inset 0 -2px 0px 0px rgba(0,0,0,0.3);
}

.stat-card-content {
  padding: 16px 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  gap: 8px;
  width: 100%;
}

.stat-pixel-art {
  width: 36px;
  height: 36px;
  margin-bottom: 2px;
  fill: var(--color-link);
  filter: drop-shadow(0 0 4px var(--color-link));
  image-rendering: pixelated;
}

.stat-number {
  font-family: 'Hurmit', monospace;
  font-size: 1.6rem;
  color: var(--color-link);
  text-shadow: 0 0 8px var(--color-link), 0 0 4px var(--color-link);
  font-weight: bold;
  letter-spacing: 2px;
}

.stat-label {
  font-family: 'Hurmit', monospace;
  color: var(--color-text);
  font-size: 0.65rem;
  line-height: 1.35;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  opacity: 0.8;
}

.tui-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.blog-entry {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 8px 16px;
  border-left: 2px solid var(--color-border-color);
  margin-bottom: 4px;
  transition: all 0.1s steps(2, end);

  &:hover {
    border-left-color: var(--color-link);
    background-color: var(--color-hover);
  }
}

.entry-link {
  text-decoration: none;
  color: var(--color-text);

  &:hover {
    color: var(--color-link);
    text-shadow: 0 0 6px var(--color-link);
  }
}

.entry-title {
  font-family: 'Hurmit', monospace;
  font-size: 1rem;
  transition: all 0.1s steps(2, end);
}

.entry-meta {
  font-family: 'Hurmit', monospace;
  color: var(--color-text);
  font-size: 0.8rem;
  opacity: 0.6;
}

.show-more-link {
  margin-top: 12px;
  padding-left: 14px;

  a {
    color: var(--color-link);
    font-family: 'Hurmit', monospace;
    font-size: 0.85rem;
    text-shadow: 0 0 4px var(--color-link);
    transition: all 0.1s steps(2, end);

    &:hover {
      text-shadow: 0 0 10px var(--color-link), 0 0 3px var(--color-link);
    }
  }
}

.grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(250px, 1fr));
    gap: 16px;
    padding: 24px 0;
}

.selector {
    width: 100%;
    height: 250px;
    overflow: hidden;
    position: relative;
    cursor: pointer;
    transition: all 0.1s steps(3, end);
    display: block;
    border: 2px solid var(--color-border-color);
    background-color: var(--color-background-fore);

    &:hover {
        border-color: var(--color-link);
        transform: translateY(-2px);
        box-shadow: 4px -4px 0px 0px var(--color-link);
    }
    
    .selector-border-top,
    .selector-border-bottom {
        position: absolute;
        left: 30px;
        right: 30px;
        height: 0;
        color: var(--color-border-color);
        font-family: 'Hurmit', monospace;
        font-size: 0;
        line-height: 0;
        white-space: nowrap;
        z-index: 10;
        transition: color 0.1s steps(2, end);
    }
    
    .selector-border-top {
        top: -2px;
        &::before { content: "═══════════════════"; }
    }
    
    .selector-border-bottom {
        bottom: -2px;
        &::before { content: "═══════════════════"; }
    }
}

.selector-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

.overlay-label {
    position: absolute;
    bottom: -2px;
    left: 30px;
    background-color: var(--color-link);
    color: var(--color-background-fore);
    padding: 2px 8px;
    font-family: 'Hurmit', monospace;
    font-size: 0.7rem;
    letter-spacing: 1px;
    text-transform: uppercase;
    box-shadow: inset 0 -2px 0px 0px rgba(0,0,0,0.3);
    pointer-events: none;
}

@keyframes blink-cursor {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

@media (max-width: 900px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .grid {
      grid-template-columns: repeat(2, minmax(200px, 1fr));
  }
  
  .selector {
      height: 200px;
  }
}

@media (max-width: 600px) {
  .section-title {
    font-size: 1.1rem;
  }

  .project-card {
    padding: 8px 12px;
  }

  .project-layout {
    flex-direction: column !important;
  }

  .project-preview {
    width: 100% !important;
    min-width: auto !important;
    height: 160px !important;
  }

  .project-title {
    font-size: 0.95rem;
  }

  .project-description {
    font-size: 0.82rem;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }

  .stat-card-header {
      padding: 2px 8px;
      font-size: 0.5rem;
  }

  .stat-card-content {
      padding: 12px 6px;
  }

  .stat-number {
    font-size: 1.4rem;
  }

  .stat-label {
    font-size: 0.6rem;
  }

  .stat-pixel-art {
    width: 28px;
    height: 28px;
  }

  .grid {
      grid-template-columns: 1fr;
      padding: 16px 0;
  }

  .selector {
      height: 180px;
  }
}

@media (max-width: 400px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .section-title {
    font-size: 1rem;
    padding-left: 0;
  }

  .grid {
      grid-template-columns: 1fr;
  }

  .selector {
      height: 200px;
  }
}
</style>
