import {objects,lessons,sources,lessonFigures,filterObjects,calculateRolling,sanitizeProgress,gradeAnswer} from './content.mjs'; import {initLogoMotion} from './logo-motion.mjs'; import {initTensileLab} from './tensile-lab.mjs'; import {initMaterialLabs} from './material-labs.mjs'; import {initTestingLabs} from './testing-labs.mjs'; import {selectCorrosionType} from './corrosion-lesson.mjs'; import {selectFoundationCase} from './foundations.mjs'; const $=(selector,root=document)=>root.querySelector(selector); const $$=(selector,root=document)=>[...root.querySelectorAll(selector)]; const storeKey='metalurgia-viva-percurso-v1'; let completed=[],storageAvailable=true,filter='todos',activeLesson=null,activeStep=0,answered=false,lastOpener=null,postCloseFocus=null,rollTimer,toastTimer; try{completed=sanitizeProgress(localStorage.getItem(storeKey));localStorage.setItem(storeKey,JSON.stringify(completed));}catch{storageAvailable=false;} const fmt=(n,digits=1)=>n.toLocaleString('pt-BR',{minimumFractionDigits:digits,maximumFractionDigits:digits}); const dialog=$('#content-dialog'); const sourceMarkup=keys=>keys.length?``:''; const graphic=id=>``; const clock=''; function renderObjects(){ const found=filterObjects(filter,$('#object-search').value); $('#object-grid').innerHTML=found.map(o=>`
${o.material}

${o.title}

${o.intro}

${o.topic}
`).join(''); $('#empty-state').hidden=found.length!==0; $('#result-count').textContent=`${found.length} ${found.length===1?'objeto encontrado':'objetos encontrados'}`; } function renderLessons(){ $('#lesson-grid').innerHTML=lessons.map((l,i)=>`
${clock} 5 min · no seu ritmo${completed.includes(l.id)?'✓ Concluída':`${String(i+1).padStart(2,'0')}`}

${l.title}

${l.summary}

`).join(''); const grid=$('#lesson-grid'),focusGrid=$('#lesson-grid-aplicacoes'); focusGrid.replaceChildren(); [...grid.children].forEach((card,index)=>{if(lessons[index].track==='focus')focusGrid.append(card);}); } function renderProgress(){ $('#nav-count').textContent=`${completed.length}/${lessons.length}`; $('#completed-count').innerHTML=`${completed.length}/${lessons.length}`; $('#journey-bar').setAttribute('aria-valuenow',completed.length); $('#journey-bar').setAttribute('aria-valuemax',lessons.length); $('#journey-bar > span').style.width=`${completed.length/lessons.length*100}%`; $('#journey-list').innerHTML=lessons.map(l=>`
  • ${completed.includes(l.id)?'✓':''}
  • `).join(''); if(!storageAvailable)$('#storage-note').textContent='O armazenamento está indisponível. O progresso fica nesta sessão.'; renderLessons(); } function persistProgress(){ try{localStorage.setItem(storeKey,JSON.stringify(completed));}catch{storageAvailable=false;} renderProgress(); } function toast(text){ clearTimeout(toastTimer);$('#toast').textContent=text;$('#toast').hidden=false; toastTimer=setTimeout(()=>{$('#toast').hidden=true;},4000); } function openDialog(){ if(!dialog.open){lastOpener=document.activeElement;dialog.showModal();document.body.style.overflow='hidden';} dialog.scrollTop=0; const title=$('#dialog-title');title.setAttribute('tabindex','-1');title.focus({preventScroll:true}); } function openObject(id){ const o=objects.find(o=>o.id===id);if(!o)return; activeLesson=null; $('#dialog-content').innerHTML=`

    METALURGIA NO COTIDIANO · ${o.topic.toUpperCase()}

    ${o.title}

    ${o.intro}

    ${graphic(o.symbol)}${o.element}
    ${o.facts.map(f=>`
    ${f[0]}
    ${f[1]}
    `).join('')}

    Olhe mais de perto

    ${o.insight}

    ${o.question}

    ${o.id==='latinha'?'Ler a ficha “Da chapa à lata” ':''}${sourceMarkup(o.sources)}
    `; openDialog(); } function openLesson(id){ const lesson=lessons.find(l=>l.id===id);if(!lesson)return; activeLesson=lesson;activeStep=0;answered=false;renderLesson(); } function renderLesson(){ const l=activeLesson;if(!l)return; const isQuiz=activeStep===2,page=l.pages[activeStep]; const nav=['A ideia','Na prática','Seu desafio'].map((s,i)=>``).join(''); const body=isQuiz?`

    Hora de testar sua ideia

    ${l.question}

    ${l.options.map((o,i)=>``).join('')}
    `:`

    ${page.title}

    ${page.html}${activeStep===0&&page.figure!==false?`
    ${lessonFigures[l.figure]}
    ${page.caption}
    `:''}

    ${page.fact}

    Um passo além · nível graduação

    ${page.advanced}

    `; $('#dialog-content').innerHTML=`

    EM CINCO MINUTOS · ${l.tag}

    ${l.title}

    ${l.summary}

    ${nav}
    ${body}${sourceMarkup(l.sources)}
    `; answered=false;openDialog(); } function answerQuiz(index){ if(!activeLesson||activeStep!==2||answered)return; if(!Number.isInteger(index)||index<0||index>3)return; answered=true; const l=activeLesson,correct=gradeAnswer(l.id,index); $$('.quiz-option',dialog).forEach((b,i)=>{b.disabled=true;b.classList.add(i===l.correct?'correct':i===index?'incorrect':'dimmed');if(i===index)b.setAttribute('aria-label',`${l.options[i]}. Sua resposta. ${correct?'Correta':'Incorreta'}`);}); if(correct&&!completed.includes(l.id)){completed.push(l.id);persistProgress();} const next=lessons[lessons.indexOf(l)+1]; $('#quiz-feedback').className=`quiz-feedback ${correct?'':'incorrect'}`; $('#quiz-feedback').innerHTML=`

    ${correct?'Boa! Você conectou as ideias.':'Vamos olhar por outro ângulo?'}

    ${l.explanation}

    ${correct?`

    ✓ Microaula concluída. ${completed.length===lessons.length?'Você concluiu todas as microaulas!':'Seu percurso foi atualizado.'}

    `:''}`; } function updateRolling(){ const state=calculateRolling($('#thickness').value),h=state.output*3; $('#thickness-label').textContent=`${fmt(state.output)} mm`; $('#thickness').setAttribute('aria-valuetext',`${fmt(state.output)} milímetros`); $('#reduction-value').textContent=`${fmt(state.reduction,0)}%`; $('#length-value').textContent=`${fmt(state.length,2)} m`; $('#svg-thickness').textContent=`${fmt(state.output,state.output%1?1:0)} mm`; const top=170-h,bottom=170+h; const d=`M40 140H240L320 ${top}H650V${bottom}H320L240 200H40Z`; $('#plate-shape').setAttribute('d',d);$('#plate-texture').setAttribute('d',d); $('#top-roll').setAttribute('transform',`translate(0 ${top-165})`); $('#bottom-roll').setAttribute('transform',`translate(0 ${bottom-175})`); $('#lab-observation').innerHTML=state.reduction===0?'

    Sem redução de espessura: o comprimento continua em 1 m. Feche a abertura para explorar a mudança.

    ':`

    A espessura caiu ${fmt(state.reduction,0)}%. A chapa ficou mais longa, sem perder material neste modelo.

    `; $('#rolling-desc').textContent=`Uma chapa de 10 milímetros entra entre os cilindros. Na saída tem ${fmt(state.output)} milímetros. A redução é de ${fmt(state.reduction,0)} por cento e o comprimento final é ${fmt(state.length,2)} metros, com volume e largura constantes.`; } function stopRolling(){ clearTimeout(rollTimer);$('#rolling-diagram').classList.remove('is-rolling'); $('#animate-roll').innerHTML=' Ver em movimento'; $('#animate-roll').disabled=false;$('#lab-status').textContent='Pronto para laminar'; } $('#object-search').addEventListener('input',renderObjects); $$('[data-filter]').forEach(b=>b.addEventListener('click',()=>{filter=b.dataset.filter;$$('[data-filter]').forEach(f=>{f.classList.toggle('active',f===b);f.setAttribute('aria-pressed',f===b);});renderObjects();})); $('#clear-search').addEventListener('click',()=>{$('#object-search').value='';$('[data-filter="todos"]').click();$('#object-search').focus();}); $('#close-dialog').addEventListener('click',()=>dialog.close()); dialog.addEventListener('click',e=>{if(e.target===dialog)dialog.close();}); dialog.addEventListener('close',()=>{document.body.style.overflow='';const lessonId=activeLesson?.id;activeLesson=null;const focusTarget=postCloseFocus||(lastOpener?.isConnected?lastOpener:lessonId?$(`[data-lesson="${lessonId}"]`):null);postCloseFocus=null;focusTarget?.focus({preventScroll:true});}); document.addEventListener('click',e=>{ const target=e.target.closest('button,a');if(!target)return; if(target.dataset.object){e.preventDefault();openObject(target.dataset.object);} else if(target.dataset.lesson){e.preventDefault();openLesson(target.dataset.lesson);} else if(target.dataset.corrosionType){selectCorrosionType(dialog,target.dataset.corrosionType);} else if(target.dataset.foundationCase){selectFoundationCase(dialog,target.closest('[data-foundation-activity]').dataset.foundationActivity,target.dataset.foundationCase);} else if(target.hasAttribute('data-handout')){e.preventDefault();$('#handout-reading').open=true;postCloseFocus=$('#handout-title');if(dialog.open)dialog.close();location.hash='da-chapa-a-lata';} else if(target.matches('.reveal-answer')){const expanded=target.getAttribute('aria-expanded')==='true';target.setAttribute('aria-expanded',!expanded);$('#object-answer').hidden=expanded;target.innerHTML=expanded?'Revelar explicação ':'Ocultar explicação ';} else if(target.hasAttribute('data-next')){activeStep=Math.min(2,activeStep+1);renderLesson();} else if(target.hasAttribute('data-step')&&!target.disabled){activeStep=Number(target.dataset.step);renderLesson();} else if(target.hasAttribute('data-answer'))answerQuiz(Number(target.dataset.answer)); else if(target.hasAttribute('data-retry'))renderLesson(); else if(target.hasAttribute('data-go-lab')){postCloseFocus=$('#thickness');dialog.close();location.hash='laboratorio';} else if(target.hasAttribute('data-finish')){postCloseFocus=$('#percurso h2');postCloseFocus.setAttribute('tabindex','-1');dialog.close();location.hash='percurso';} }); $('#thickness').addEventListener('input',updateRolling); $('#animate-roll').addEventListener('click',()=>{ const reduced=matchMedia('(prefers-reduced-motion: reduce)').matches; $('#lab-status').textContent=reduced?'Fluxo: entrada → cilindros → saída':'Laminação em movimento'; $('#rolling-diagram').classList.add('is-rolling'); $('#animate-roll').textContent=reduced?'Fluxo demonstrado ✓':'Laminando…';$('#animate-roll').disabled=true; rollTimer=setTimeout(()=>{stopRolling();$('#lab-status').textContent='Experimento concluído · ajuste e compare';},reduced?1200:4200); }); $('#reset-roll').addEventListener('click',()=>{stopRolling();$('#thickness').value='6';updateRolling();toast('Experimento restaurado: saída com 6 mm.');}); $('#reset-progress').addEventListener('click',()=>{$('#reset-confirm').hidden=false;$('#confirm-reset').focus();}); $('#cancel-reset').addEventListener('click',()=>{$('#reset-confirm').hidden=true;$('#reset-progress').focus();}); $('#confirm-reset').addEventListener('click',()=>{completed=[];persistProgress();$('#reset-confirm').hidden=true;$('#reset-progress').focus();toast('Seu percurso foi reiniciado. Vamos descobrir de novo?');}); $('#menu-toggle').addEventListener('click',()=>{const open=$('#main-nav').classList.toggle('open');$('#menu-toggle').setAttribute('aria-expanded',open);$('#menu-toggle').setAttribute('aria-label',open?'Fechar menu':'Abrir menu');}); $$('#main-nav a').forEach(a=>a.addEventListener('click',()=>{$('#main-nav').classList.remove('open');$('#menu-toggle').setAttribute('aria-expanded','false');$('#menu-toggle').setAttribute('aria-label','Abrir menu');})); document.addEventListener('keydown',e=>{if(e.key==='Escape'){$('#main-nav').classList.remove('open');$('#menu-toggle').setAttribute('aria-expanded','false');$('#menu-toggle').setAttribute('aria-label','Abrir menu');}}); if('IntersectionObserver' in window){const observer=new IntersectionObserver(entries=>{for(const entry of entries){if(entry.isIntersecting){$$('#main-nav a').forEach(a=>{const active=a.hash===`#${entry.target.id}`;a.classList.toggle('current',active);if(active)a.setAttribute('aria-current','location');else a.removeAttribute('aria-current');});}}},{rootMargin:'-15% 0px -70% 0px'});$$('section[id]').forEach(s=>observer.observe(s));} renderObjects();renderProgress();updateRolling(); initLogoMotion(); initTensileLab(); initMaterialLabs(); initTestingLabs();