// @ts-check
(()=>{
  'use strict';
  const App=window.IUS_TEMPLATE,{utils,state}=App,posts=(App.data.posts||[]).filter(p=>p.status==='published');let activePost=null,archiveOpen=false;
  const q=s=>utils.$(s);
  function card(post,index){const article=document.createElement('article');article.className=`post-card${post.featured?' featured':''}${index>1?' archive-post':''}`;if(index>1&&!archiveOpen)article.hidden=true;const title=utils.local(post.title),section=utils.local(post.section),date=utils.formatDate(post.datePublished),minutes=utils.readingTime(post);article.innerHTML=`${post.featured?`<span class="featured-badge">${utils.escapeHtml(App.modules.i18n.t('posts.featured'))}</span>`:''}<figure><img src="${utils.escapeHtml(post.image)}" alt="${utils.escapeHtml(utils.local(post.imageAlt))}" width="1600" height="1000" loading="lazy" style="object-position:${post.focalPoint.x*100}% ${post.focalPoint.y*100}%"></figure><div class="post-card-body"><div class="post-card-meta"><span>${utils.escapeHtml(section)}</span><time datetime="${post.datePublished}">${utils.escapeHtml(date)}</time></div><h3>${utils.escapeHtml(title)}</h3><p>${utils.escapeHtml(utils.local(post.excerpt))}</p><div class="post-card-actions"><a class="button secondary" href="posts/${post.slug}/" data-post-open="${post.slug}">${utils.escapeHtml(App.modules.i18n.t('posts.read'))}</a><button type="button" aria-label="${utils.escapeHtml(App.modules.i18n.t('posts.share'))}: ${utils.escapeHtml(title)}" data-card-share="${post.slug}"><svg aria-hidden="true"><use href="#icon-share"></use></svg></button></div><small>${minutes} ${utils.escapeHtml(App.modules.i18n.t('posts.min'))}</small></div>`;return article}
  function renderCards(){const grid=q('[data-post-grid]');if(!grid)return;grid.replaceChildren(...posts.map(card));utils.$$('[data-post-open]').forEach(a=>a.addEventListener('click',e=>{e.preventDefault();open(a.dataset.postOpen,a)}));utils.$$('[data-card-share]').forEach(b=>b.addEventListener('click',()=>share(posts.find(p=>p.slug===b.dataset.cardShare),b)))}
  function renderBody(post){const host=q('[data-post-body]');host.replaceChildren();(post.body[state.locale]||post.body.en).forEach(block=>{let el;if(block.type==='heading')el=document.createElement('h2');else if(block.type==='quote')el=document.createElement('blockquote');else el=document.createElement('p');if(block.type==='lead')el.className='lead';el.textContent=block.text;host.append(el)})}
  function related(post){const host=q('[data-related-posts]');host.replaceChildren();posts.filter(p=>p.slug!==post.slug).slice(0,2).forEach(p=>{const a=document.createElement('a');a.className='related-link';a.href=`posts/${p.slug}/`;a.innerHTML=`<span>${utils.escapeHtml(utils.local(p.section))}</span><strong>${utils.escapeHtml(utils.local(p.title))}</strong>`;a.addEventListener('click',e=>{e.preventDefault();open(p.slug,a)});host.append(a)})}
  function populate(post){activePost=post;state.activePost=post.slug;q('[data-post-image]').src=post.image;q('[data-post-image]').alt=utils.local(post.imageAlt);q('[data-post-image]').style.objectPosition=`${post.focalPoint.x*100}% ${post.focalPoint.y*100}%`;q('[data-post-section]').textContent=utils.local(post.section);q('[data-post-date]').dateTime=post.datePublished;q('[data-post-date]').textContent=utils.formatDate(post.datePublished);q('[data-post-title]').textContent=utils.local(post.title);q('[data-post-author]').textContent=utils.local(post.author);q('[data-post-reading]').textContent=`${utils.readingTime(post)} ${App.modules.i18n.t('posts.min')}`;q('[data-post-modified]').textContent=post.dateModified!==post.datePublished?`${App.modules.i18n.t('posts.updated')}: ${utils.formatDate(post.dateModified)}`:'';renderBody(post);related(post);App.modules.comments.setPage(post.slug)}
  function open(slug,trigger,{history=true}={}){const post=posts.find(p=>p.slug===slug),d=q('[data-post-dialog]');if(!post||!d)return;populate(post);utils.openDialog(d,trigger);if(history&&/^https?:$/.test(location.protocol))window.history.pushState({post:slug},'',`#post/${slug}`);requestAnimationFrame(()=>q('.post-reader-scroll')?.scrollTo({top:0}))}
  function close({history=true}={}){utils.closeDialog(q('[data-post-dialog]'));activePost=null;state.activePost=null;if(history&&/^https?:$/.test(location.protocol)&&location.hash.startsWith('#post/'))window.history.pushState({},'',location.pathname+location.search+'#posts')}
  async function share(post,trigger){if(!post)return;const data={title:utils.local(post.title),text:utils.local(post.excerpt),url:utils.canonicalPost(post.slug)};if(navigator.share){try{await navigator.share(data);return}catch(e){if(e?.name==='AbortError')return}}openShare(post,trigger)}
  function openShare(post,trigger){activePost=post;const status=q('[data-share-status]');if(status)status.textContent='';utils.openDialog(q('[data-share-dialog]'),trigger)}
  function shareAction(action){if(!activePost)return;const url=utils.canonicalPost(activePost.slug),title=utils.local(activePost.title),status=q('[data-share-status]');if(action==='copy'){utils.copy(url).then(ok=>{status.textContent=ok?App.modules.i18n.t('share.copied'):url});return}const targets={email:`mailto:?subject=${encodeURIComponent(title)}&body=${encodeURIComponent(url)}`,linkedin:`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`,x:`https://twitter.com/intent/tweet?text=${encodeURIComponent(title)}&url=${encodeURIComponent(url)}`,bluesky:`https://bsky.app/intent/compose?text=${encodeURIComponent(`${title} ${url}`)}`};window.open(targets[action],'_blank','noopener,noreferrer')}
  function printPost(){if(!activePost)return;const print=q('[data-print-document]');print.replaceChildren();const header=document.createElement('header'),h=document.createElement('h1');h.textContent=utils.local(activePost.title);const meta=document.createElement('div');meta.className='print-meta';meta.innerHTML=`<span>${utils.escapeHtml(utils.local(activePost.section))} · ${utils.escapeHtml(utils.formatDate(activePost.datePublished))}</span><span>${utils.escapeHtml(utils.local(activePost.author))}</span>`;header.append(h,meta);const article=document.createElement('article');(activePost.body[state.locale]||activePost.body.en).forEach(block=>{const el=document.createElement(block.type==='heading'?'h2':block.type==='quote'?'blockquote':'p');el.textContent=block.text;article.append(el)});const footer=document.createElement('footer');footer.innerHTML=`<span>${utils.escapeHtml(utils.canonicalPost(activePost.slug))}</span><span>Designed by I/US brand. · iusmusic.com</span>`;print.append(header,article,footer);window.print()}
  function init(){renderCards();q('[data-post-archive]')?.addEventListener('click',()=>{archiveOpen=!archiveOpen;q('[data-post-archive]').setAttribute('aria-expanded',String(archiveOpen));renderCards()});utils.$$('[data-post-close]').forEach(b=>b.addEventListener('click',()=>close()));q('[data-post-share]')?.addEventListener('click',e=>share(activePost,e.currentTarget));q('[data-post-print]')?.addEventListener('click',printPost);utils.$$('[data-share-close]').forEach(b=>b.addEventListener('click',()=>utils.closeDialog(q('[data-share-dialog]'))));utils.$$('[data-share-action]').forEach(b=>b.addEventListener('click',()=>shareAction(b.dataset.shareAction)));window.addEventListener('popstate',()=>{const match=location.hash.match(/^#post\/(.+)$/);if(match)open(match[1],null,{history:false});else if(q('[data-post-dialog]')?.open)close({history:false})});document.addEventListener('ius:localechange',()=>{renderCards();if(activePost)populate(activePost)});const match=location.hash.match(/^#post\/(.+)$/);if(match)setTimeout(()=>open(match[1],null,{history:false}),0)}
  App.modules.posts={init,open,close,share};
})();
