(function(){
'use strict';
function slugify(value){return (value||'').toLowerCase().trim().normalize('NFKD').replace(/[\u0300-\u036f]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'');}
function sourceInput(form){return form.querySelector('[name="name"], [name="title"], [name="shop_name"], [name="subject"], [name="rule_name"], [name="method_name"]');}
function codeValue(field,source){const clean=(source||'ITEM').toUpperCase().replace(/[^A-Z0-9]/g,'').slice(0,8)||'ITEM';const now=new Date();const d=String(now.getFullYear()).slice(-2)+String(now.getMonth()+1).padStart(2,'0')+String(now.getDate()).padStart(2,'0');const rnd=Math.random().toString(36).slice(2,8).toUpperCase();if(field==='barcode'){let base='2';for(let i=0;i<11;i++)base+=Math.floor(Math.random()*10);let sum=0;for(let i=0;i<12;i++)sum+=Number(base[i])*(i%2===0?1:3);return base+((10-(sum%10))%10);}if(field==='sku')return clean+'-'+rnd.slice(0,4);if(field==='referral_code')return 'REF-'+rnd;return clean.slice(0,4)+'-'+d+'-'+rnd;}
function initSelectSearch(input){const select=document.getElementById(input.dataset.target);if(!select)return;const original=Array.from(select.options).map(o=>({value:o.value,text:o.text,selected:o.selected,disabled:o.disabled}));input.addEventListener('input',()=>{const q=input.value.trim().toLowerCase();const current=select.value;select.innerHTML='';original.forEach(o=>{if(o.value===''||o.text.toLowerCase().includes(q)||o.value===current){const option=new Option(o.text,o.value,o.selected,o.selected);option.disabled=o.disabled;select.add(option);}});select.value=current;});}
function initJson(button){const target=document.getElementById(button.dataset.target);const status=document.querySelector('[data-for="'+button.dataset.target+'"]');if(!target)return;const validate=()=>{if(!target.value.trim()){if(status){status.textContent='';status.className='small text-muted smart-json-status';}return true;}try{JSON.parse(target.value);if(status){status.textContent='Valid JSON';status.className='small text-success smart-json-status';}target.classList.remove('is-invalid');return true;}catch(e){if(status){status.textContent=e.message;status.className='small text-danger smart-json-status';}target.classList.add('is-invalid');return false;}};button.addEventListener('click',()=>{try{target.value=JSON.stringify(JSON.parse(target.value||'{}'),null,2);}catch(e){}validate();});target.addEventListener('input',validate);validate();}
function initEditor(toolbar){const editor=document.getElementById(toolbar.dataset.editorToolbar);if(!editor)return;const target=document.getElementById(editor.dataset.target);const actions=[['Bold','bold'],['Italic','italic'],['Underline','underline'],['H2','formatBlock','H2'],['H3','formatBlock','H3'],['Bullets','insertUnorderedList'],['Numbers','insertOrderedList'],['Link','createLink'],['Clear','removeFormat']];actions.forEach(item=>{const button=document.createElement('button');button.type='button';button.className='btn btn-sm btn-outline-secondary';button.textContent=item[0];button.addEventListener('click',()=>{editor.focus();let value=item[2]||null;if(item[1]==='createLink')value=prompt('Enter an HTTPS URL')||'';if(item[1]!=='createLink'||value)document.execCommand(item[1],false,value);target.value=editor.innerHTML;});toolbar.appendChild(button);});editor.addEventListener('input',()=>target.value=editor.innerHTML);}
function keywords(source,form){const result=[];const add=v=>{v=(v||'').trim().toLowerCase();if(v&&v.length>1&&!result.includes(v))result.push(v);};((source.value||'').match(/[\p{L}\p{N}]+/gu)||[]).forEach(add);form.querySelectorAll('select').forEach(s=>{if(/category|brand|vendor/.test(s.name)){const o=s.options[s.selectedIndex];if(o&&o.value)add(o.text.split('—')[0]);}});['bangladesh','online','best price','smart tech omp'].forEach(add);return result.slice(0,20);}
function initForm(form){const source=sourceInput(form);const slug=form.querySelector('[data-auto="slug"]');const metaTitle=form.querySelector('[data-auto="meta-title"]');const keyword=form.querySelector('[data-auto="meta-keywords"]');const toggleEnabled=input=>{const t=form.querySelector('.smart-auto-toggle[data-target="'+input.id+'"]');return !t||t.checked;};const renderKeywords=()=>{if(!source||!keyword)return;const box=form.querySelector('.smart-keyword-chips[data-target="'+keyword.id+'"]');if(!box)return;box.innerHTML='';keywords(source,form).slice(0,12).forEach(word=>{const b=document.createElement('button');b.type='button';b.className='btn btn-sm btn-light border';b.textContent='+'+word;b.addEventListener('click',()=>{const current=keyword.value.split(',').map(v=>v.trim()).filter(Boolean);if(!current.some(v=>v.toLowerCase()===word.toLowerCase()))current.push(word);keyword.value=current.join(', ');});box.appendChild(b);});};const sync=()=>{if(!source)return;if(slug&&toggleEnabled(slug))slug.value=slugify(source.value);if(metaTitle&&toggleEnabled(metaTitle))metaTitle.value=source.value.trim();renderKeywords();};if(source){source.addEventListener('input',sync);form.querySelectorAll('select').forEach(s=>s.addEventListener('change',renderKeywords));if(!slug?.value&&source.value)sync();else renderKeywords();}
form.querySelectorAll('.smart-generate-code').forEach(btn=>btn.addEventListener('click',()=>{const target=document.getElementById(btn.dataset.target);if(target)target.value=codeValue(btn.dataset.field,source?source.value:form.dataset.entity);}));
form.querySelectorAll('input[type="file"][data-preview]').forEach(input=>input.addEventListener('change',()=>{const preview=document.getElementById(input.dataset.preview);const file=input.files&&input.files[0];if(preview&&file&&file.type.startsWith('image/')){preview.src=URL.createObjectURL(file);preview.classList.remove('d-none');}}));
form.addEventListener('submit',event=>{form.querySelectorAll('.smart-rich-editor').forEach(editor=>{const target=document.getElementById(editor.dataset.target);if(target)target.value=editor.innerHTML;});let valid=true;form.querySelectorAll('.smart-json-field').forEach(field=>{if(field.value.trim()){try{JSON.parse(field.value);field.classList.remove('is-invalid');}catch(e){field.classList.add('is-invalid');valid=false;}}});if(keyword&&!keyword.value.trim()&&source)keyword.value=keywords(source,form).join(', ');form.querySelectorAll('[data-auto="code"]').forEach(input=>{if(!input.value.trim())input.value=codeValue(input.name,source?source.value:form.dataset.entity);});if(!valid){event.preventDefault();const first=form.querySelector('.is-invalid');if(first)first.scrollIntoView({behavior:'smooth',block:'center'});}});
}
document.querySelectorAll('[data-smart-form]').forEach(initForm);document.querySelectorAll('.smart-select-search').forEach(initSelectSearch);document.querySelectorAll('.smart-format-json').forEach(initJson);document.querySelectorAll('[data-editor-toolbar]').forEach(initEditor);
})();
