/* Business & AI — Gerar Pedido (Dashboard ou Funcionalidade)
   Formulário de especificação com auto-save localStorage. */

const getDdModulos = () => (window.PORTAL_MODULES || []).map(m => m.label);
const getDdSubmenus = (modLabel) => {
  if (!modLabel) return [];
  const m = (window.PORTAL_MODULES || []).find(m => m.label === modLabel);
  return m ? m.submenus : [];
};

// ── Defaults ──────────────────────────────────────────────────────────────────
const DD_INIT = {
  m_dashboard:'', m_owner:'', m_date:'', m_version:'1.0',
  id_nome:'', id_owner:'', id_area:'', id_publico:'', id_period:'', id_tool:'',
  obj_main:'', obj_q1:'', obj_q2:'', obj_q3:'', obj_dec:'',
  k1a:'',k1b:'',k1c:'',k1d:'',k1e:'', k2a:'',k2b:'',k2c:'',k2d:'',k2e:'',
  k3a:'',k3b:'',k3c:'',k3d:'',k3e:'', k4a:'',k4b:'',k4c:'',k4d:'',k4e:'',
  k5a:'',k5b:'',k5c:'',k5d:'',k5e:'', k6a:'',k6b:'',k6c:'',k6d:'',k6e:'',
  m1a:'',m1b:'',m1c:'',m1d:'',m1e:'', m2a:'',m2b:'',m2c:'',m2d:'',m2e:'',
  m3a:'',m3b:'',m3c:'',m3d:'',m3e:'', m4a:'',m4b:'',m4c:'',m4d:'',m4e:'',
  m5a:'',m5b:'',m5c:'',m5d:'',m5e:'',
  impl_dep:'', impl_risk:'',
  val_by:'', val_owner_ok:false, val_owner_date:'', val_prod_ok:false, val_prod_date:'',
};

const FN_INIT = {
  m_dashboard:'', m_owner:'', m_date:'', m_version:'1.0',
  fn_modulo:'', fn_tipo:'', fn_publico:'', fn_frequencia:'',
  fn_problema:'', fn_impacto:'', fn_hoje:'',
  fn_descricao:'', fn_fluxo:'',
  io1a:'',io1b:'',io1c:'',io1d:'', io2a:'',io2b:'',io2c:'',io2d:'',
  io3a:'',io3b:'',io3c:'',io3d:'', io4a:'',io4b:'',io4c:'',io4d:'',
  fn_int_erp:false, fn_int_wa:false, fn_int_meta:false, fn_int_pbi:false, fn_int_outra:false,
  fn_int_detalhe:'',
  fn_criterio:'', fn_testes:'',
  fn_criticidade:'', fn_prazo:'', fn_deps:'',
};

const FN_TIPOS = ['Nova página','Novo submenu','Melhoria de existente','Integração','Automação'];
const FN_CRITS = ['Alta','Média','Baixa'];

const WIZARD_QS = {
  dashboard: [
    'O que queres medir ou monitorizar?',
    'Para quem é e que decisões vai suportar?',
    'Que dados ou sistemas estão envolvidos?',
    'Com que frequência vai ser consultado?',
    'Qual a urgência ou prazo desejado?',
  ],
  funcionalidade: [
    'Qual o problema a resolver?',
    'Quem é afectado e com que frequência?',
    'Como funciona o processo hoje (sem esta funcionalidade)?',
    'Que dados entram e saem desta funcionalidade?',
    'Qual o critério de sucesso?',
  ],
};

// ── Print CSS ─────────────────────────────────────────────────────────────────

// ── Design tokens ─────────────────────────────────────────────────────────────
const C = {
  navy:'#112954', blue:'#3859D0', dark:'#283252', body:'#404968',
  muted:'#94A4C4', border:'#E1E7F3', surf:'#F9FAFF', meta:'#EBEFF9', ok:'#2EBD68',
};

const autoH = e => { e.target.style.height='auto'; e.target.style.height=e.target.scrollHeight+'px'; };

// ── Shared components ─────────────────────────────────────────────────────────
const DdLabel = ({ children }) => (
  <div style={{ fontSize:10, fontWeight:700, letterSpacing:'0.08em', color:C.blue, textTransform:'uppercase', marginBottom:4, fontFamily:'var(--font-mono)' }}>{children}</div>
);

const DdInput = ({ value, onChange, placeholder, style }) => (
  <input value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder}
    style={{ width:'100%', border:'none', borderBottom:`1.5px solid ${C.border}`, padding:'5px 0', fontSize:13, color:C.dark, background:'transparent', outline:'none', fontFamily:'var(--font-body)', ...style }} />
);

const DdSelect = ({ value, onChange, options, placeholder }) => (
  <select value={value} onChange={e=>onChange(e.target.value)}
    style={{ width:'100%', border:'none', borderBottom:`1.5px solid ${C.border}`, padding:'5px 0', fontSize:13, color:value?C.dark:C.muted, background:'transparent', outline:'none', fontFamily:'var(--font-body)', cursor:'pointer' }}>
    <option value="">{placeholder||'Seleccionar…'}</option>
    {options.map(o=><option key={o} value={o}>{o}</option>)}
  </select>
);

const DdTextarea = ({ value, onChange, placeholder, rows=3 }) => (
  <textarea value={value} onChange={e=>onChange(e.target.value)} onInput={autoH} placeholder={placeholder} rows={rows}
    style={{ width:'100%', border:`1.5px dashed ${C.border}`, borderRadius:6, padding:'8px 10px', fontSize:13, color:C.dark, background:C.surf, outline:'none', resize:'none', fontFamily:'var(--font-body)', lineHeight:1.55, boxSizing:'border-box' }} />
);

const DdSection = ({ num, title, subtitle, children }) => (
  <div style={{ marginBottom:28 }}>
    <div style={{ display:'flex', alignItems:'center', gap:14, padding:'10px 18px', background:C.navy, borderRadius:'8px 8px 0 0' }}>
      <span style={{ fontFamily:'var(--font-mono)', fontSize:22, fontWeight:800, color:'rgba(255,255,255,0.18)', lineHeight:1 }}>{num}</span>
      <div>
        <div style={{ fontSize:13, fontWeight:700, color:'#fff', letterSpacing:'0.04em', textTransform:'uppercase' }}>{title}</div>
        {subtitle && <div style={{ fontSize:11, color:'rgba(255,255,255,0.55)', marginTop:1 }}>{subtitle}</div>}
      </div>
    </div>
    <div style={{ border:`1.5px solid ${C.border}`, borderTop:'none', borderRadius:'0 0 8px 8px', padding:'20px 18px', background:'#fff' }}>{children}</div>
  </div>
);

const DdTableTA = ({ value, onChange, bg }) => (
  <textarea value={value} onChange={e=>onChange(e.target.value)} onInput={autoH} rows={2}
    style={{ width:'100%', border:'none', padding:'6px 8px', fontSize:12, color:C.dark, background:bg||'transparent', outline:'none', resize:'none', fontFamily:'var(--font-body)', lineHeight:1.5, minHeight:44, boxSizing:'border-box' }} />
);

// ── Main component ────────────────────────────────────────────────────────────
const BusinessAIDefinirDashboard = ({ user }) => {
  const [tipo, setTipo] = React.useState('dashboard');
  const [fieldsDash, setFieldsDash] = React.useState(DD_INIT);
  const [fieldsFunc, setFieldsFunc] = React.useState(FN_INIT);
  const [selMod, setSelMod] = React.useState('');
  const [selSub, setSelSub] = React.useState('');
  const [selOutro, setSelOutro] = React.useState('');
  const [saved, setSaved] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [aiPanel, setAiPanel] = React.useState({ open:false, mode:'prompt', input:'', wizardAnswers:{ q1:'',q2:'',q3:'',q4:'',q5:'' }, loading:false, error:null });
  const [aiToast, setAiToast] = React.useState(false);

  const fields    = tipo === 'dashboard' ? fieldsDash : fieldsFunc;
  const setFields = tipo === 'dashboard' ? setFieldsDash : setFieldsFunc;
  const formKey   = tipo === 'dashboard' ? 'dd_dashboard_form_v1' : 'dd_func_form_v1';
  const initVal   = tipo === 'dashboard' ? DD_INIT : FN_INIT;

  // Mount: restore from localStorage
  React.useEffect(() => {
    try {
      const s = JSON.parse(localStorage.getItem('dd_dashboard_selects_v1') || '{}');
      if (s.sel_tipo)    setTipo(s.sel_tipo);
      if (s.sel_modulo)  setSelMod(s.sel_modulo);
      if (s.sel_submenu) setSelSub(s.sel_submenu);
      if (s.sel_outro)   setSelOutro(s.sel_outro);
      const fd = JSON.parse(localStorage.getItem('dd_dashboard_form_v1') || '{}');
      if (Object.keys(fd).length) setFieldsDash(p=>({...p,...fd}));
      const ff = JSON.parse(localStorage.getItem('dd_func_form_v1') || '{}');
      if (Object.keys(ff).length) setFieldsFunc(p=>({...p,...ff}));
    } catch {}
  }, []);

  // Auto-save fields
  React.useEffect(() => {
    try { localStorage.setItem(formKey, JSON.stringify(fields)); } catch {}
    setSaved(true);
    const t = setTimeout(() => setSaved(false), 1800);
    return () => clearTimeout(t);
  }, [fields]);

  // Auto-save selects + tipo
  React.useEffect(() => {
    try { localStorage.setItem('dd_dashboard_selects_v1', JSON.stringify({ sel_tipo:tipo, sel_modulo:selMod, sel_submenu:selSub, sel_outro:selOutro })); } catch {}
  }, [tipo, selMod, selSub, selOutro]);

  const set = (k, v) => setFields(prev => ({ ...prev, [k]: v }));

  const handleSubmit = async () => {
    const name = (fields.m_dashboard || '').trim();
    if (!name) { alert(`Preencha o nome ${tipo==='dashboard'?'do dashboard':'da funcionalidade'} no cabeçalho antes de submeter.`); return; }
    const id = 'dd_' + Date.now() + '_' + Math.random().toString(36).slice(2,6);
    try {
      await fetch('/api/dashboard-requests', {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ id, tipo, fields, sel_mod:selMod, sel_sub:selSub, sel_outro:selOutro }),
      });
    } catch(e) { console.error('[DD] submit error:', e); }
    setSubmitted(true);
    setTimeout(() => setSubmitted(false), 3500);
    // Clear form after submission
    setFields(initVal);
    setSelMod(''); setSelSub(''); setSelOutro('');
    try { localStorage.removeItem(formKey); localStorage.removeItem('dd_dashboard_selects_v1'); } catch {}
  };

  const handleClear = () => {
    if (!window.confirm('Apagar todos os campos? Esta acção é irreversível.')) return;
    setFields(initVal);
    setSelMod(''); setSelSub(''); setSelOutro('');
    try { localStorage.removeItem(formKey); } catch {}
  };

  const handleGenerate = async () => {
    setAiPanel(p => ({ ...p, loading:true, error:null }));
    const inputPayload = aiPanel.mode === 'prompt'
      ? aiPanel.input
      : WIZARD_QS[tipo].reduce((acc, q, i) => { acc[`q${i+1}`] = `${q} ${aiPanel.wizardAnswers[`q${i+1}`]}`; return acc; }, {});
    try {
      const r = await fetch('/api/business/generate-pedido', {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ type:tipo, mode:aiPanel.mode, input:inputPayload }),
      });
      if (!r.ok) { const e = await r.json(); throw new Error(e.error || 'Erro ao gerar'); }
      const { fields: generated } = await r.json();
      setFields(prev => ({ ...prev, ...generated }));
      setAiPanel(p => ({ ...p, open:false, loading:false }));
      setAiToast(true);
      setTimeout(() => setAiToast(false), 4000);
    } catch (e) {
      setAiPanel(p => ({ ...p, loading:false, error:e.message }));
    }
  };

  const submenus = getDdSubmenus(selMod);
  const showOutro = selSub === 'Outro';
  const thStyle = { padding:'8px 10px', fontSize:11, fontWeight:700, color:'#fff', textAlign:'left', letterSpacing:'0.05em', textTransform:'uppercase' };
  const selStyle = { padding:'7px 10px', fontSize:13, border:`1.5px solid rgba(255,255,255,0.2)`, borderRadius:6, background:'rgba(255,255,255,0.12)', color:'#fff', outline:'none', cursor:'pointer', fontFamily:'var(--font-body)', minWidth:200 };

  // Dashboard table helpers
  const kRow = (n, bg) => {
    return (
      <tr key={n} style={{ background:bg }}>
        {['a','b','c','d','e'].map((l,i) => {
          const widths = ['20%','26%','24%','18%','12%'];
          return <td key={l} style={{ width:widths[i], borderRight:i<4?`1px solid ${C.border}`:'none', verticalAlign:'top' }}><DdTableTA value={fields[`k${n}${l}`]} onChange={v=>set(`k${n}${l}`,v)} bg={bg} /></td>;
        })}
      </tr>
    );
  };
  const mRow = (n, bg) => {
    return (
      <tr key={n} style={{ background:bg }}>
        {['a','b','c','d','e'].map((l,i) => {
          const widths = ['24%','16%','16%','16%','28%'];
          return <td key={l} style={{ width:widths[i], borderRight:i<4?`1px solid ${C.border}`:'none', verticalAlign:'top' }}><DdTableTA value={fields[`m${n}${l}`]} onChange={v=>set(`m${n}${l}`,v)} bg={bg} /></td>;
        })}
      </tr>
    );
  };
  // Funcionalidade IO table helper
  const ioRow = (n, bg) => (
    <tr key={n} style={{ background:bg }}>
      {['a','b','c','d'].map((l,i) => (
        <td key={l} style={{ width:'25%', borderRight:i<3?`1px solid ${C.border}`:'none', verticalAlign:'top' }}><DdTableTA value={fields[`io${n}${l}`]} onChange={v=>set(`io${n}${l}`,v)} bg={bg} /></td>
      ))}
    </tr>
  );

  const isTipoFn = tipo === 'funcionalidade';

  return (
    <div id="dd-print-root" className="scrollbar" style={{ height:'100%', overflowY:'auto', background:'#f4f6fb' }}>
      <div style={{ maxWidth:940, margin:'0 auto', padding:'28px 24px 80px' }}>

        {/* Toolbar */}
        <div className="dd-no-print" style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:20 }}>
          <div>
            <div style={{ fontSize:11, fontFamily:'var(--font-mono)', color:'var(--text-dim)', letterSpacing:'0.08em', textTransform:'uppercase' }}>BUSINESS & AI · GERAR PEDIDO</div>
            <h2 style={{ margin:'4px 0 0', fontSize:22, fontWeight:500, color:'var(--text)', letterSpacing:'-0.01em' }}>
              Gerar Pedido
            </h2>
            <p style={{ margin:'6px 0 0', fontSize:13, color:'var(--text-dim)', lineHeight:1.55, maxWidth:560 }}>
              {isTipoFn
                ? 'Especificação estruturada de uma nova funcionalidade ou melhoria ao portal. Preenche as secções relevantes e submete para aprovação do Board.'
                : 'Especificação estruturada de um novo dashboard ou vista analítica. Define KPIs, fontes de dados e critérios de sucesso antes de submeter para aprovação.'}
            </p>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            {saved && !submitted && (
              <span style={{ display:'flex', alignItems:'center', gap:5, fontSize:11, color:C.ok, fontFamily:'var(--font-mono)' }}>
                <span style={{ width:7, height:7, borderRadius:'50%', background:C.ok, display:'inline-block' }} />guardado
              </span>
            )}
            {submitted && (
              <span style={{ display:'flex', alignItems:'center', gap:5, fontSize:11, color:C.ok, fontFamily:'var(--font-mono)', fontWeight:600 }}>
                <span style={{ width:7, height:7, borderRadius:'50%', background:C.ok, display:'inline-block' }} />submetido para aprovação
              </span>
            )}
            <button onClick={()=>setAiPanel(p=>({...p,open:!p.open,error:null}))} className="btn btn-xs" style={{ fontSize:12, background:C.blue, color:'#fff', border:'none', borderRadius:6 }}>✦ Gerar com IA</button>
            <button onClick={handleClear} className="btn btn-xs btn-ghost" style={{ fontSize:12 }}>Limpar</button>
            <button onClick={handleSubmit} className="btn btn-xs btn-primary" style={{ fontSize:12 }}>Submeter para aprovação</button>
          </div>
        </div>

        {/* Tipo toggle + context selector — navy panel */}
        <div className="dd-no-print" style={{ background:C.navy, borderRadius:10, padding:'16px 20px', marginBottom:24, display:'flex', alignItems:'flex-end', gap:16, flexWrap:'wrap' }}>
          {/* Tipo toggle */}
          <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
            <div style={{ fontSize:10, fontWeight:700, color:'rgba(255,255,255,0.5)', letterSpacing:'0.08em', textTransform:'uppercase' }}>Tipo de pedido</div>
            <div style={{ display:'flex', gap:4 }}>
              {[['dashboard','Dashboard'],['funcionalidade','Funcionalidade']].map(([t,label])=>(
                <button key={t} onClick={()=>setTipo(t)}
                  style={{ padding:'6px 14px', borderRadius:6, border:'none', cursor:'pointer', fontSize:12, fontWeight:600,
                    background: tipo===t ? '#fff' : 'rgba(255,255,255,0.12)',
                    color: tipo===t ? C.navy : 'rgba(255,255,255,0.75)',
                    fontFamily:'var(--font-body)', transition:'all .15s' }}>
                  {label}
                </button>
              ))}
            </div>
          </div>

          <div style={{ width:1, height:40, background:'rgba(255,255,255,0.15)', flexShrink:0 }} />

          {/* Módulo */}
          <div>
            <div style={{ fontSize:10, fontWeight:700, color:'rgba(255,255,255,0.5)', letterSpacing:'0.08em', textTransform:'uppercase', marginBottom:6 }}>Módulo</div>
            <select value={selMod} onChange={e=>{setSelMod(e.target.value);setSelSub('');setSelOutro('');}} style={selStyle}>
              <option value="">Seleccionar módulo…</option>
              {getDdModulos().map(m=><option key={m} value={m}>{m}</option>)}
            </select>
          </div>

          {/* Submenu */}
          <div>
            <div style={{ fontSize:10, fontWeight:700, color:'rgba(255,255,255,0.5)', letterSpacing:'0.08em', textTransform:'uppercase', marginBottom:6 }}>Submenu</div>
            <select value={selSub} onChange={e=>{setSelSub(e.target.value);setSelOutro('');}} disabled={!selMod} style={{...selStyle, opacity:selMod?1:0.45}}>
              <option value="">Seleccionar submenu…</option>
              {submenus.map(s=><option key={s} value={s}>{s}</option>)}
            </select>
          </div>

          {showOutro && (
            <div style={{ flex:1, minWidth:180 }}>
              <div style={{ fontSize:10, fontWeight:700, color:'rgba(255,255,255,0.5)', letterSpacing:'0.08em', textTransform:'uppercase', marginBottom:6 }}>Nome livre</div>
              <input value={selOutro} onChange={e=>setSelOutro(e.target.value)} placeholder="Nome do submenu…" style={{...selStyle, width:'100%', boxSizing:'border-box'}} />
            </div>
          )}

          {selMod && selSub && (
            <div style={{ padding:'6px 12px', background:'rgba(255,255,255,0.1)', borderRadius:6, fontSize:11, color:'rgba(255,255,255,0.7)', fontFamily:'var(--font-mono)', whiteSpace:'nowrap' }}>
              {selMod} › {selSub==='Outro'?selOutro||'Outro':selSub}
            </div>
          )}
        </div>

        {/* AI Panel */}
        {aiPanel.open && (
          <div className="dd-no-print" style={{ background:'#f0f4ff', border:`1.5px solid ${C.blue}`, borderRadius:10, padding:'18px 20px', marginBottom:20 }}>
            <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:16 }}>
              <span style={{ fontSize:11, fontWeight:700, color:C.blue, letterSpacing:'0.08em', textTransform:'uppercase', fontFamily:'var(--font-mono)' }}>Geração por IA</span>
              <div style={{ display:'flex', gap:3, background:'#e4eaff', borderRadius:6, padding:3 }}>
                {[['prompt','Prompt Livre'],['wizard','Wizard Guiado']].map(([m,label])=>(
                  <button key={m} onClick={()=>setAiPanel(p=>({...p,mode:m,error:null}))}
                    style={{ padding:'5px 12px', borderRadius:4, border:'none', cursor:'pointer', fontSize:12, fontWeight:600,
                      background:aiPanel.mode===m?'#fff':'transparent', color:aiPanel.mode===m?C.blue:C.muted,
                      fontFamily:'var(--font-body)', transition:'all .15s', boxShadow:aiPanel.mode===m?'0 1px 3px rgba(0,0,0,0.1)':'none' }}>
                    {label}
                  </button>
                ))}
              </div>
              <button onClick={()=>setAiPanel(p=>({...p,open:false,error:null}))} style={{ marginLeft:'auto', background:'none', border:'none', cursor:'pointer', color:C.muted, fontSize:20, lineHeight:1, padding:'0 2px' }}>×</button>
            </div>

            {aiPanel.mode==='prompt' && (
              <div>
                <div style={{ fontSize:12, color:C.body, marginBottom:8 }}>Descreve em linguagem natural o que precisas:</div>
                <textarea value={aiPanel.input} onChange={e=>setAiPanel(p=>({...p,input:e.target.value}))}
                  placeholder={tipo==='dashboard'
                    ? 'Ex: Quero um dashboard de vendas mensais por comercial, com comparação ao ano anterior e meta de crescimento...'
                    : 'Ex: Precisamos de uma funcionalidade que permita ao gestor de vendas ver os alertas de clientes em risco de churn...'}
                  rows={3}
                  style={{ width:'100%', border:`1.5px solid ${C.border}`, borderRadius:6, padding:'8px 10px', fontSize:13, color:C.dark, outline:'none', resize:'vertical', fontFamily:'var(--font-body)', lineHeight:1.55, boxSizing:'border-box', background:'#fff' }} />
              </div>
            )}

            {aiPanel.mode==='wizard' && (
              <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
                {WIZARD_QS[tipo].map((q,i)=>(
                  <div key={i}>
                    <div style={{ fontSize:11, fontWeight:700, color:C.blue, letterSpacing:'0.06em', marginBottom:4, fontFamily:'var(--font-mono)' }}>Q{i+1} · {q}</div>
                    <input value={aiPanel.wizardAnswers[`q${i+1}`]||''} onChange={e=>setAiPanel(p=>({...p,wizardAnswers:{...p.wizardAnswers,[`q${i+1}`]:e.target.value}}))}
                      placeholder="A tua resposta…"
                      style={{ width:'100%', border:`1.5px solid ${C.border}`, borderRadius:6, padding:'7px 10px', fontSize:13, color:C.dark, background:'#fff', outline:'none', fontFamily:'var(--font-body)', boxSizing:'border-box' }} />
                  </div>
                ))}
              </div>
            )}

            {aiPanel.error && (
              <div style={{ marginTop:10, fontSize:12, color:'#c0392b', background:'#fdf2f2', border:'1px solid #fbc8c8', borderRadius:6, padding:'8px 10px' }}>{aiPanel.error}</div>
            )}

            <div style={{ marginTop:14, display:'flex', justifyContent:'flex-end' }}>
              {(() => {
                const canGen = aiPanel.mode==='prompt'
                  ? aiPanel.input.trim().length > 0
                  : WIZARD_QS[tipo].some((_,i)=>(aiPanel.wizardAnswers[`q${i+1}`]||'').trim().length>0);
                return (
                  <button onClick={handleGenerate} disabled={aiPanel.loading||!canGen}
                    style={{ padding:'8px 22px', borderRadius:7, border:'none', cursor: (aiPanel.loading||!canGen)?'not-allowed':'pointer', fontSize:13, fontWeight:700,
                      background:C.blue, color:'#fff', fontFamily:'var(--font-body)', opacity:(aiPanel.loading||!canGen)?0.55:1 }}>
                    {aiPanel.loading ? 'A gerar…' : 'Gerar'}
                  </button>
                );
              })()}
            </div>
          </div>
        )}

        {/* AI success toast */}
        {aiToast && (
          <div className="dd-no-print" style={{ background:'#d4edda', border:'1px solid #b8dfc4', borderRadius:8, padding:'10px 16px', marginBottom:16, display:'flex', alignItems:'center', gap:8, fontSize:13, color:'#155724' }}>
            <span style={{ fontWeight:700 }}>✓</span>
            <span>Campos preenchidos pela IA — revê e ajusta o que precisares antes de submeter.</span>
          </div>
        )}

        {/* Meta strip */}
        <div style={{ background:C.meta, borderRadius:8, padding:'14px 20px', marginBottom:24, display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:20 }}>
          {[[isTipoFn?'Funcionalidade':'Dashboard','m_dashboard',isTipoFn?'Nome da funcionalidade':'Nome'],['Owner','m_owner','Responsável'],['Data','m_date','DD / MM / AAAA'],['Versão','m_version','1.0']].map(([label,k,ph])=>(
            <div key={k}>
              <DdLabel>{label}</DdLabel>
              <DdInput value={fields[k]} onChange={v=>set(k,v)} placeholder={ph} />
            </div>
          ))}
        </div>

        {/* ── DASHBOARD FORM ──────────────────────────────────────────────── */}
        {!isTipoFn && (<>

          <DdSection num="01" title="Identificação" subtitle="Contexto base do dashboard">
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'16px 28px' }}>
              {[['id_nome','Nome do dashboard','Ex.: Performance Comercial — Mensal'],['id_owner','Owner / Responsável','Quem aprova e mantém'],['id_area','Área de negócio','Comercial · Operações · Financeira…'],['id_publico','Público-alvo','Quem consome e que decisões toma'],['id_period','Periodicidade de actualização','Tempo real · Diária · Semanal · Mensal'],['id_tool','Ferramenta / Plataforma','Power BI · Looker · Outra']].map(([k,label,ph])=>(
                <div key={k}><DdLabel>{label}</DdLabel><DdInput value={fields[k]} onChange={v=>set(k,v)} placeholder={ph} /></div>
              ))}
            </div>
          </DdSection>

          <DdSection num="02" title="Objectivo e Propósito" subtitle="Porque é que este dashboard existe">
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <div><DdLabel>Objectivo principal</DdLabel><DdTextarea value={fields.obj_main} onChange={v=>set('obj_main',v)} placeholder="Descreva, numa frase, a finalidade do dashboard e o problema de negócio que resolve." rows={2} /></div>
              {[['obj_q1','1. Que pergunta deve esta vista responder?'],['obj_q2','2. …'],['obj_q3','3. …']].map(([k,ph])=>(
                <div key={k}><DdLabel>Pergunta a responder</DdLabel><DdTextarea value={fields[k]} onChange={v=>set(k,v)} placeholder={ph} rows={2} /></div>
              ))}
              <div><DdLabel>Decisões que suporta</DdLabel><DdTextarea value={fields.obj_dec} onChange={v=>set('obj_dec',v)} placeholder="Que acções ou decisões serão tomadas com base nesta informação." rows={2} /></div>
            </div>
          </DdSection>

          <DdSection num="03" title="KPIs e Métricas" subtitle="Definição, fórmula de cálculo e fonte de dados">
            <div style={{ overflowX:'auto' }}>
              <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>
                <thead><tr style={{ background:C.blue }}>
                  {[['20%','Métrica'],['26%','Definição'],['24%','Fórmula de cálculo'],['18%','Fonte de dados'],['12%','Granularidade']].map(([w,h])=><th key={h} style={{...thStyle,width:w}}>{h}</th>)}
                </tr></thead>
                <tbody style={{ border:`1px solid ${C.border}` }}>{[1,2,3,4,5,6].map(n=>kRow(n,n%2===0?C.surf:'#fff'))}</tbody>
              </table>
            </div>
            <div style={{ marginTop:10, fontSize:11, color:C.muted, fontStyle:'italic' }}>Granularidade = nível de detalhe da métrica (ex.: por dia, por cliente, por região).</div>
          </DdSection>

          <DdSection num="04" title="Resultados Esperados e Metas" subtitle="O que define o sucesso de cada KPI">
            <div style={{ overflowX:'auto' }}>
              <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>
                <thead><tr style={{ background:C.blue }}>
                  {[['24%','KPI'],['16%','Baseline actual'],['16%','Meta'],['16%','Prazo'],['28%','Critério de sucesso']].map(([w,h])=><th key={h} style={{...thStyle,width:w}}>{h}</th>)}
                </tr></thead>
                <tbody style={{ border:`1px solid ${C.border}` }}>{[1,2,3,4,5].map(n=>mRow(n,n%2===0?C.surf:'#fff'))}</tbody>
              </table>
            </div>
          </DdSection>

          <DdSection num="05" title="Notas de Implementação" subtitle="Dependências, riscos e pressupostos">
            <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
              <div><DdLabel>Dependências de dados</DdLabel><DdTextarea value={fields.impl_dep} onChange={v=>set('impl_dep',v)} placeholder="Tabelas, integrações ou pipelines necessários. Indique se algum dado ainda não existe." rows={3} /></div>
              <div><DdLabel>Pressupostos e riscos</DdLabel><DdTextarea value={fields.impl_risk} onChange={v=>set('impl_risk',v)} placeholder="Qualidade de dados, definições ambíguas, prazos de disponibilidade." rows={3} /></div>
              <div style={{ borderTop:`1.5px solid ${C.border}`, paddingTop:16, display:'flex', flexDirection:'column', gap:12 }}>
                <div style={{ display:'flex', alignItems:'center', gap:12 }}>
                  <span style={{ fontSize:12, color:C.body, whiteSpace:'nowrap', fontWeight:500 }}>Métricas validadas contra a fonte por</span>
                  <input value={fields.val_by} onChange={e=>set('val_by',e.target.value)} placeholder="Nome / cargo" style={{ flex:1, border:'none', borderBottom:`1.5px solid ${C.border}`, padding:'4px 0', fontSize:13, color:C.dark, background:'transparent', outline:'none', fontFamily:'var(--font-body)' }} />
                </div>
                {[['val_owner_ok','val_owner_date','Aprovado pelo owner'],['val_prod_ok','val_prod_date','Em produção']].map(([kOk,kDate,label])=>(
                  <div key={kOk} style={{ display:'flex', alignItems:'center', gap:12 }}>
                    <input type="checkbox" checked={!!fields[kOk]} onChange={e=>set(kOk,e.target.checked)} style={{ width:16, height:16, accentColor:C.blue, cursor:'pointer', flexShrink:0 }} />
                    <span style={{ fontSize:12, color:C.body, fontWeight:500, minWidth:160 }}>{label}</span>
                    <input value={fields[kDate]} onChange={e=>set(kDate,e.target.value)} placeholder="DD / MM / AAAA" style={{ border:'none', borderBottom:`1.5px solid ${C.border}`, padding:'4px 0', fontSize:13, color:C.dark, background:'transparent', outline:'none', fontFamily:'var(--font-body)', width:130 }} />
                  </div>
                ))}
              </div>
            </div>
          </DdSection>

        </>)}

        {/* ── FUNCIONALIDADE FORM ─────────────────────────────────────────── */}
        {isTipoFn && (<>

          <DdSection num="01" title="Identificação" subtitle="Contexto base da funcionalidade">
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'16px 28px' }}>
              <div><DdLabel>Módulo alvo</DdLabel><DdInput value={fields.fn_modulo} onChange={v=>set('fn_modulo',v)} placeholder="Ex.: Comercial, Marketing, SAT…" /></div>
              <div><DdLabel>Tipo</DdLabel><DdSelect value={fields.fn_tipo} onChange={v=>set('fn_tipo',v)} options={FN_TIPOS} placeholder="Tipo de funcionalidade…" /></div>
              <div><DdLabel>Público-alvo / Utilizadores</DdLabel><DdInput value={fields.fn_publico} onChange={v=>set('fn_publico',v)} placeholder="Quem vai usar esta ferramenta" /></div>
              <div><DdLabel>Frequência de uso estimada</DdLabel><DdInput value={fields.fn_frequencia} onChange={v=>set('fn_frequencia',v)} placeholder="Diária · Semanal · Por evento…" /></div>
            </div>
          </DdSection>

          <DdSection num="02" title="Problema e Contexto" subtitle="Porque é que esta funcionalidade é necessária">
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <div><DdLabel>Problema actual</DdLabel><DdTextarea value={fields.fn_problema} onChange={v=>set('fn_problema',v)} placeholder="Descreva o problema ou lacuna que existe hoje." rows={3} /></div>
              <div><DdLabel>Impacto no trabalho</DdLabel><DdTextarea value={fields.fn_impacto} onChange={v=>set('fn_impacto',v)} placeholder="Como este problema afecta a produtividade, qualidade ou resultado." rows={2} /></div>
              <div><DdLabel>Como é feito hoje</DdLabel><DdTextarea value={fields.fn_hoje} onChange={v=>set('fn_hoje',v)} placeholder="Processo actual (manual, Excel, outra ferramenta, não existe…)." rows={2} /></div>
            </div>
          </DdSection>

          <DdSection num="03" title="Solução Proposta" subtitle="O que deve a funcionalidade fazer">
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <div><DdLabel>Descrição da funcionalidade</DdLabel><DdTextarea value={fields.fn_descricao} onChange={v=>set('fn_descricao',v)} placeholder="Descreva o que a ferramenta deve fazer, numa ou duas frases." rows={3} /></div>
              <div><DdLabel>Fluxo de trabalho esperado</DdLabel><DdTextarea value={fields.fn_fluxo} onChange={v=>set('fn_fluxo',v)} placeholder="Passo a passo: o utilizador abre → faz X → o sistema faz Y → resultado Z." rows={4} /></div>
            </div>
          </DdSection>

          <DdSection num="04" title="Inputs e Outputs" subtitle="Dados que entram e saem da funcionalidade">
            <div style={{ overflowX:'auto' }}>
              <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>
                <thead><tr style={{ background:C.blue }}>
                  {['Input','Fonte','Output','Destino'].map(h=><th key={h} style={{...thStyle,width:'25%'}}>{h}</th>)}
                </tr></thead>
                <tbody style={{ border:`1px solid ${C.border}` }}>{[1,2,3,4].map(n=>ioRow(n,n%2===0?C.surf:'#fff'))}</tbody>
              </table>
            </div>
            <div style={{ marginTop:10, fontSize:11, color:C.muted, fontStyle:'italic' }}>Input = dados que a funcionalidade recebe. Output = o que produz. Fonte/Destino = sistema de origem ou destino.</div>
          </DdSection>

          <DdSection num="05" title="Integrações Necessárias" subtitle="Sistemas externos que esta funcionalidade precisa de aceder">
            <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
              <div style={{ display:'flex', gap:24, flexWrap:'wrap' }}>
                {[['fn_int_erp','ERP Primavera'],['fn_int_wa','WhatsApp / HeyDigi'],['fn_int_meta','Meta Ads'],['fn_int_pbi','Power BI'],['fn_int_outra','Outra']].map(([k,label])=>(
                  <label key={k} style={{ display:'flex', alignItems:'center', gap:8, cursor:'pointer', fontSize:13, color:C.dark }}>
                    <input type="checkbox" checked={!!fields[k]} onChange={e=>set(k,e.target.checked)} style={{ width:15, height:15, accentColor:C.blue }} />
                    {label}
                  </label>
                ))}
              </div>
              <div><DdLabel>Detalhe das integrações</DdLabel><DdTextarea value={fields.fn_int_detalhe} onChange={v=>set('fn_int_detalhe',v)} placeholder="Descreva que dados precisam de ser lidos ou escritos em cada sistema." rows={2} /></div>
            </div>
          </DdSection>

          <DdSection num="06" title="Critério de Aceitação" subtitle="O que define que esta funcionalidade está entregue">
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <div><DdLabel>O que define «entregue»</DdLabel><DdTextarea value={fields.fn_criterio} onChange={v=>set('fn_criterio',v)} placeholder="Ex.: O utilizador consegue fazer X sem erros. O sistema guarda Y na BD. O relatório mostra Z." rows={3} /></div>
              <div><DdLabel>Testes de validação</DdLabel><DdTextarea value={fields.fn_testes} onChange={v=>set('fn_testes',v)} placeholder="Cenários de teste que o departamento vai validar antes de aprovar." rows={3} /></div>
            </div>
          </DdSection>

          <DdSection num="07" title="Prioridade e Contexto" subtitle="Urgência, prazo e dependências">
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'16px 28px' }}>
              <div>
                <DdLabel>Criticidade</DdLabel>
                <DdSelect value={fields.fn_criticidade} onChange={v=>set('fn_criticidade',v)} options={FN_CRITS} placeholder="Seleccionar…" />
              </div>
              <div><DdLabel>Prazo desejado</DdLabel><DdInput value={fields.fn_prazo} onChange={v=>set('fn_prazo',v)} placeholder="Ex.: Q3 2026, Agosto, Urgente" /></div>
              <div style={{ gridColumn:'1/-1' }}><DdLabel>Dependências</DdLabel><DdTextarea value={fields.fn_deps} onChange={v=>set('fn_deps',v)} placeholder="Existe outra funcionalidade, integração ou dado que tem de existir primeiro?" rows={2} /></div>
            </div>
          </DdSection>

        </>)}

      </div>
    </div>
  );
};

window.BusinessAIDefinirDashboard = BusinessAIDefinirDashboard;
