---
import JournalList from '../vue/JournalList.vue';

// V1.4-bis FIX 5 : couleurs pills actives attenuees (60% color + 40% papier).
// Active = fill couleur ATTENUEE (muted) + texte encre #0F172A (contraste WCAG ≥4.5:1).
// Inactive = transparent + border + texte couleur 100% (inchange).
// Mix 60/40 : moins agressif que 100% mais reste lisible (vs 30/70 pastels V1.3 trop dilues).
const categories = [
  {
    id: 'politique',
    label: 'Politique',
    color: '#B5443A',
    muted: '#C8867E',
    pastel: '#E5C3BE',
    hashtags: ['#politique', '#aep-politique'],
    plateformes: [
      { id: 'instagram', label: 'Court', url: 'https://www.instagram.com/aep.politique/' },
      { id: 'castopod', label: 'Podcast', url: 'https://podcast.trans-former.fr' },
      { id: 'substack', label: 'Article', url: 'https://julesneny.substack.com' },
    ],
    hasSelector: true,
  },
  {
    id: 'art',
    label: 'Art',
    color: '#5B6B3A',
    muted: '#8F9A78',
    pastel: '#CACFBE',
    hashtags: ['#peinture', '#art'],
    plateformes: [
      { id: 'instagram', label: '@julesneny', url: 'https://www.instagram.com/julesneny/' },
    ],
    hasSelector: false,
  },
  {
    id: 'outils',
    label: 'Outils',
    color: '#475569',
    muted: '#7B848E',
    pastel: '#C4C8CC',
    hashtags: ['#stack', '#building-public'],
    plateformes: [
      { id: 'gitea', label: 'Gitea', url: 'https://git.trans-former.fr/jules' },
    ],
    hasSelector: false,
  },
  {
    id: 'pro',
    label: 'Pro',
    color: '#0F172A',
    muted: '#566375',
    pastel: '#C4C8CC',
    hashtags: ['#building-public', '#pro'],
    plateformes: [
      { id: 'linkedin', label: 'LinkedIn', url: 'https://www.linkedin.com/in/jules-neny/' },
    ],
    hasSelector: false,
  },
];
---
<div class="h-full flex flex-col p-4 pt-20 md:pt-6 gap-5">

  <!-- Hashtags accordeon -->
  <details id="hashtags-accordion" class="border-t border-neutral-200 pt-4">
    <summary class="font-semibold cursor-pointer select-none flex items-center justify-between">
      <span>Hashtags</span>
      <span class="text-xs text-neutral-400 font-normal">4 categories</span>
    </summary>

    <div class="mt-3 flex flex-wrap gap-2" id="category-badges">
      {categories.map((cat) => (
        <button
          type="button"
          data-category-id={cat.id}
          data-hashtags={cat.hashtags.join(',')}
          data-color={cat.color}
          data-muted={cat.muted}
          data-pastel={cat.pastel}
          data-has-selector={cat.hasSelector ? 'true' : 'false'}
          class="category-badge"
          style={`background:${cat.muted};color:#0F172A;font-family:'Courier New',Courier,monospace;font-size:13px;padding:3px 10px;border-radius:4px;cursor:pointer;border:1px solid ${cat.muted};`}
        >
          {cat.label}
        </button>
      ))}
    </div>

    <!-- Selecteur plateforme Politique (V1.4-B : transparent en fill inactive) -->
    <div id="politique-selector" class="mt-2 hidden flex gap-2">
      {categories[0].plateformes.map((p) => (
        <button
          type="button"
          data-platform-id={p.id}
          class="platform-pill"
          style="font-family:'Courier New',Courier,monospace;font-size:12px;padding:2px 8px;border-radius:12px;cursor:pointer;border:1px solid #B5443A;background:transparent;color:#B5443A;"
        >
          {p.label}
        </button>
      ))}
    </div>

    <!-- Bouton Replier -->
    <div class="mt-3 flex justify-end">
      <button
        type="button"
        id="accordion-close"
        class="text-xs text-neutral-400 underline cursor-pointer bg-transparent border-0 p-0"
      >
        replier
      </button>
    </div>

    <!-- Bouton Manifeste (V1.3-E : sur "/" -> preview centrale, ailleurs -> page complete) -->
    <a
      href="/manifeste"
      data-manifeste-link
      class="block mt-3 px-4 py-2 bg-neutral-900 text-white font-bold text-sm text-center rounded-lg hover:bg-neutral-700 transition-colors"
      style="font-family:'Courier New',Courier,monospace;"
    >
      Manifeste - Lire
    </a>
  </details>

  <!-- Journal chrono -->
  <section class="border-t border-neutral-200 pt-4 flex-1 overflow-y-auto">
    <h2 class="font-semibold mb-3 flex items-center justify-between">
      <span>Journal</span>
      <span class="text-xs text-neutral-400 font-normal">chrono</span>
    </h2>
    <div id="journal-list" class="space-y-3 text-sm">
      <JournalList client:visible />
    </div>
  </section>
</div>

<script>
  const accordion = document.getElementById('hashtags-accordion') as HTMLDetailsElement | null;
  if (accordion) {
    const mql = window.matchMedia('(min-width: 768px)');
    const apply = () => { accordion.open = mql.matches; };
    apply();
    mql.addEventListener('change', apply);
  }

  const closeBtn = document.getElementById('accordion-close');
  if (closeBtn && accordion) {
    closeBtn.addEventListener('click', () => { accordion.open = false; });
  }

  const STORAGE_KEY = 'tf-hashtag-filters';
  const PLATFORM_KEY = 'tf-platform-filter';

  // Active state : map categoryId -> boolean
  const activeCategories: Record<string, boolean> = { politique: true, art: true, outils: true, pro: true };

  // Platform filter : map categoryId -> platformId | null
  const platformFilters: Record<string, string | null> = { politique: null };

  // Load persisted state
  try {
    const storedHashtags = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}') as Record<string, boolean>;
    // Derive category active state from hashtag values
    const politiqueHashtags = ['#politique', '#aep-politique'];
    const artHashtags = ['#peinture', '#art'];
    const outilsHashtags = ['#stack', '#building-public'];
    const proHashtags = ['#building-public', '#pro'];

    const allPolitique = politiqueHashtags.every(h => storedHashtags[h] !== false);
    const allArt = artHashtags.every(h => storedHashtags[h] !== false);
    const allOutils = outilsHashtags.every(h => storedHashtags[h] !== false);
    const allPro = proHashtags.every(h => storedHashtags[h] !== false);

    if (Object.keys(storedHashtags).length > 0) {
      activeCategories['politique'] = allPolitique;
      activeCategories['art'] = allArt;
      activeCategories['outils'] = allOutils;
      activeCategories['pro'] = allPro;
    }
  } catch { /* mode prive */ }

  try {
    const storedPlatform = JSON.parse(localStorage.getItem(PLATFORM_KEY) || '{}') as Record<string, string | null>;
    if (storedPlatform.politique !== undefined) {
      platformFilters['politique'] = storedPlatform.politique;
    }
  } catch { /* mode prive */ }

  const buildHashtagPayload = () => {
    const hashtags: Record<string, boolean> = {};
    const catHashtags: Record<string, string[]> = {
      politique: ['#politique', '#aep-politique'],
      art: ['#peinture', '#art'],
      outils: ['#stack', '#building-public'],
      pro: ['#building-public', '#pro'],
    };
    for (const [catId, tags] of Object.entries(catHashtags)) {
      const active = activeCategories[catId] ?? true;
      for (const tag of tags) {
        hashtags[tag] = active;
      }
    }
    return hashtags;
  };

  const persist = () => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(buildHashtagPayload()));
      localStorage.setItem(PLATFORM_KEY, JSON.stringify(platformFilters));
    } catch { /* mode prive */ }
  };

  const dispatchHashtag = () => {
    window.dispatchEvent(new CustomEvent('hashtag-filter-change', { detail: buildHashtagPayload() }));
  };

  const dispatchPlatform = (platform: string | null) => {
    window.dispatchEvent(new CustomEvent('platform-filter-change', { detail: { platform } }));
  };

  // V1.4-bis FIX 5 : pill active en couleur ATTENUEE (data-muted) + texte encre #0F172A.
  // Inactive : transparent + texte couleur 100% + border couleur 100% (inchange).
  // Pourquoi encre #0F172A au lieu de blanc : sur fond attenue (#C8867E etc.), le ratio
  // contraste blanc tombe ~3.5:1 (limite). Encre #0F172A donne ratio ≥6:1 sur tous les muted.
  const updateBadgeStyle = (btn: HTMLElement, active: boolean) => {
    const color = btn.dataset.color || '#000';
    const muted = btn.dataset.muted || color;
    if (active) {
      btn.style.background = muted;
      btn.style.color = '#0F172A';
      btn.style.border = `1px solid ${muted}`;
    } else {
      btn.style.background = 'transparent';
      btn.style.color = color;
      btn.style.border = `1px solid ${color}`;
    }
  };

  const updatePolitiqueSelector = () => {
    const selector = document.getElementById('politique-selector');
    if (!selector) return;
    if (activeCategories['politique']) {
      selector.classList.remove('hidden');
      selector.style.display = 'flex';
    } else {
      selector.classList.add('hidden');
      selector.style.display = 'none';
    }
  };

  // V1.4-bis FIX 5 : sub-pills Politique, active en brique ATTENUEE #C8867E + encre.
  // Active (ou aucun filtre) = fill #C8867E + texte encre #0F172A.
  // Inactive = transparent + texte brique 100% + border brique 100%.
  const updatePillStyles = () => {
    const pills = document.querySelectorAll<HTMLElement>('.platform-pill');
    const active = platformFilters['politique'];
    pills.forEach((pill) => {
      const pid = pill.dataset.platformId;
      if (!active || pid === active) {
        pill.style.background = '#C8867E';
        pill.style.color = '#0F172A';
      } else {
        pill.style.background = 'transparent';
        pill.style.color = '#B5443A';
      }
    });
  };

  // Init badge styles
  const badges = document.querySelectorAll<HTMLElement>('.category-badge');
  badges.forEach((btn) => {
    const catId = btn.dataset.categoryId || '';
    updateBadgeStyle(btn, activeCategories[catId] ?? true);

    btn.addEventListener('click', () => {
      activeCategories[catId] = !(activeCategories[catId] ?? true);
      updateBadgeStyle(btn, activeCategories[catId]);
      updatePolitiqueSelector();
      if (!activeCategories['politique']) {
        platformFilters['politique'] = null;
        updatePillStyles();
        dispatchPlatform(null);
      }
      persist();
      dispatchHashtag();
    });
  });

  // Init selector
  updatePolitiqueSelector();
  updatePillStyles();

  // Platform pills
  const pills = document.querySelectorAll<HTMLElement>('.platform-pill');
  pills.forEach((pill) => {
    pill.addEventListener('click', () => {
      const pid = pill.dataset.platformId || null;
      // Toggle : click on active pill deselects it
      if (platformFilters['politique'] === pid) {
        platformFilters['politique'] = null;
      } else {
        platformFilters['politique'] = pid;
      }
      updatePillStyles();
      persist();
      dispatchPlatform(platformFilters['politique']);
    });
  });

  // Apply persisted filters on init
  persist();
  dispatchHashtag();
  if (platformFilters['politique']) {
    dispatchPlatform(platformFilters['politique']);
  }

  // V1.3-E : intercept clics liens Manifeste -> preview centrale (uniquement sur racine /)
  // Tagger les liens [data-manifeste-link] et router vers event 'preview-open' si on est sur /.
  // Sinon : laisser la navigation native vers /manifeste.
  document.querySelectorAll<HTMLAnchorElement>('a[data-manifeste-link]').forEach((el) => {
    el.addEventListener('click', (e) => {
      if (window.location.pathname === '/') {
        e.preventDefault();
        window.dispatchEvent(new CustomEvent('preview-open', { detail: { type: 'manifeste' } }));
      }
      // sinon : navigation normale vers /manifeste (fallback SEO + no-JS)
    });
  });
</script>
