// js/components/common/Modal.jsx
// Modal overlay React + showConfirm DOM helper (Promise-based).
// Movido de index.html em Fase 5 do refactor (2026-04-29): L588-L651
// Deps: Icon (window.Icon — carregado antes via Icon.jsx)
(function() {
  'use strict';

  // CÓPIA EXATA do index.html L588-L600
  function Modal({title,onClose,children,large}){
    return(
      <div className="modal-overlay" onClick={e=>e.target===e.currentTarget&&onClose()}>
        <div className={`modal ${large?'modal-lg':''}`}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:20}}>
            <h3 style={{color:'#2563EB',fontSize:16}}>{title}</h3>
            <button onClick={onClose} style={{background:'none',color:'#9CA3AF',padding:4}}><Icon n="x"/></button>
          </div>
          {children}
        </div>
      </div>
    );
  }

  // CÓPIA EXATA do index.html L606-L651
  // ── CONFIRM MODAL (DOM-based, Promise) — [A-07] ──────────────────
  // Substitui window.confirm() em todos os componentes.
  // Uso: if(await showConfirm('Mensagem?')) { doThing(); }
  // Uso com opções: await showConfirm({title:'Atenção', message:'...', confirmText:'Sim', confirmColor:'#EA580C'})
  function showConfirm(msgOrOpts){
    const opts=typeof msgOrOpts==='string'?{message:msgOrOpts}:msgOrOpts;
    const{title='Confirmar',message=opts.message||'',confirmText='Confirmar',confirmColor='#DC2626'}=opts;
    return new Promise((resolve)=>{
      const ov=document.createElement('div');
      ov.style.cssText='position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:99999;font-family:inherit';
      const _box=document.createElement('div');
      _box.style.cssText='background:#fff;border-radius:12px;padding:24px;max-width:420px;width:90%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,.3)';
      const _icon=document.createElement('div');
      _icon.style.cssText='font-size:44px;margin-bottom:12px';
      _icon.textContent='⚠️';
      const _h3=document.createElement('h3');
      _h3.style.cssText='margin:0 0 10px;font-size:17px;color:#1B2A4A;font-weight:700';
      _h3.textContent=title;
      const _p=document.createElement('p');
      _p.style.cssText='margin:0 0 20px;font-size:14px;color:#374151;white-space:pre-wrap';
      _p.textContent=message;
      const _btnRow=document.createElement('div');
      _btnRow.style.cssText='display:flex;gap:12px;justify-content:center';
      const _btnCancel=document.createElement('button');
      _btnCancel.id='_cm_cancel';
      _btnCancel.style.cssText='padding:10px 24px;border-radius:8px;border:1px solid #ddd;background:#f5f5f5;color:#333;font-size:14px;font-weight:600;cursor:pointer;min-width:100px';
      _btnCancel.textContent='Cancelar';
      const _btnOk=document.createElement('button');
      _btnOk.id='_cm_ok';
      _btnOk.style.cssText=`padding:10px 24px;border-radius:8px;border:none;background:${confirmColor};color:#fff;font-size:14px;font-weight:600;cursor:pointer;min-width:100px`;
      _btnOk.textContent=confirmText;
      _btnRow.appendChild(_btnCancel);
      _btnRow.appendChild(_btnOk);
      _box.appendChild(_icon);
      _box.appendChild(_h3);
      _box.appendChild(_p);
      _box.appendChild(_btnRow);
      ov.appendChild(_box);
      document.body.appendChild(ov);
      const done=(v)=>{document.body.removeChild(ov);document.removeEventListener('keydown',esc);resolve(v);};
      ov.querySelector('#_cm_cancel').onclick=()=>done(false);
      ov.querySelector('#_cm_ok').onclick=()=>done(true);
      ov.onclick=(e)=>{if(e.target===ov)done(false);};
      const esc=(e)=>{if(e.key==='Escape')done(false);};
      document.addEventListener('keydown',esc);
      setTimeout(()=>ov.querySelector('#_cm_cancel').focus(),50);
    });
  }

  // ── PROMPT MODAL (DOM-based, Promise) — [ONDA3 P2 2026-05-11] ─────
  // Substitui window.prompt() — visual coerente com showConfirm + textarea/input.
  // Uso: const r = await showPrompt({title, message, placeholder, minLength, multiline, confirmText, confirmColor});
  // Retorna string do usuário ou null se cancelou.
  function showPrompt(opts){
    opts=opts||{};
    const{title='Informar valor',message='',placeholder='',defaultValue='',minLength=0,multiline=false,confirmText='Confirmar',confirmColor='#1B2A4A',cancelText='Cancelar'}=opts;
    return new Promise((resolve)=>{
      const ov=document.createElement('div');
      ov.style.cssText='position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:99999;font-family:inherit';
      const _box=document.createElement('div');
      _box.style.cssText='background:#fff;border-radius:12px;padding:24px;max-width:460px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,.3)';
      const _h3=document.createElement('h3');
      _h3.style.cssText='margin:0 0 8px;font-size:17px;color:#1B2A4A;font-weight:700';
      _h3.textContent=title;
      const _p=document.createElement('p');
      _p.style.cssText='margin:0 0 14px;font-size:13px;color:#374151;white-space:pre-wrap';
      _p.textContent=message;
      const _input=document.createElement(multiline?'textarea':'input');
      if(!multiline)_input.type='text';
      _input.value=defaultValue||'';
      _input.placeholder=placeholder||'';
      _input.style.cssText='width:100%;padding:10px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:14px;box-sizing:border-box;font-family:inherit'+(multiline?';min-height:80px;resize:vertical':'');
      const _hint=document.createElement('div');
      _hint.style.cssText='margin-top:6px;font-size:11px;color:#6B7280;min-height:14px';
      const _btnRow=document.createElement('div');
      _btnRow.style.cssText='display:flex;gap:12px;justify-content:flex-end;margin-top:18px';
      const _btnCancel=document.createElement('button');
      _btnCancel.id='_pm_cancel';
      _btnCancel.style.cssText='padding:10px 20px;border-radius:8px;border:1px solid #ddd;background:#f5f5f5;color:#333;font-size:14px;font-weight:600;cursor:pointer;min-width:100px';
      _btnCancel.textContent=cancelText;
      const _btnOk=document.createElement('button');
      _btnOk.id='_pm_ok';
      _btnOk.style.cssText=`padding:10px 20px;border-radius:8px;border:none;background:${confirmColor};color:#fff;font-size:14px;font-weight:600;cursor:pointer;min-width:100px`;
      _btnOk.textContent=confirmText;
      _btnRow.appendChild(_btnCancel);
      _btnRow.appendChild(_btnOk);
      _box.appendChild(_h3);
      _box.appendChild(_p);
      _box.appendChild(_input);
      _box.appendChild(_hint);
      _box.appendChild(_btnRow);
      ov.appendChild(_box);
      document.body.appendChild(ov);
      const validate=()=>{
        const v=(_input.value||'').trim();
        if(minLength>0&&v.length<minLength){
          _hint.textContent=`Mínimo ${minLength} caracteres (atual: ${v.length}).`;
          _hint.style.color='#DC2626';
          _btnOk.disabled=true;
          _btnOk.style.opacity='0.55';
          _btnOk.style.cursor='not-allowed';
          return false;
        }
        _hint.textContent=v?`${v.length} caracteres`:'';
        _hint.style.color='#6B7280';
        _btnOk.disabled=false;
        _btnOk.style.opacity='1';
        _btnOk.style.cursor='pointer';
        return true;
      };
      _input.addEventListener('input',validate);
      validate();
      const done=(v)=>{document.body.removeChild(ov);document.removeEventListener('keydown',esc);resolve(v);};
      _btnCancel.onclick=()=>done(null);
      _btnOk.onclick=()=>{if(validate())done((_input.value||'').trim());};
      ov.onclick=(e)=>{if(e.target===ov)done(null);};
      const esc=(e)=>{
        if(e.key==='Escape')done(null);
        if(e.key==='Enter'&&!multiline){e.preventDefault();if(validate())done((_input.value||'').trim());}
      };
      document.addEventListener('keydown',esc);
      setTimeout(()=>_input.focus(),50);
    });
  }

  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.Modal = Modal;
  window.ZNX.components.showConfirm = showConfirm;
  window.ZNX.components.showPrompt = showPrompt;
  window.Modal = Modal;
  window.showConfirm = showConfirm;
  window.showPrompt = showPrompt;

  window.ZNX.refactor_phase_5_loaded = window.ZNX.refactor_phase_5_loaded || {};
  window.ZNX.refactor_phase_5_loaded.Modal = true;
  window.ZNX.refactor_phase_5_loaded.showConfirm = true;
  window.ZNX.refactor_phase_5_loaded.showPrompt = true;

})();
