/* Business & AI — Gestão de Pedidos (Kanban)
   Fluxo: Submetido → Em análise → Aprovado → Em desenvolvimento → Em teste → Entregue
                                    ↘ Rejeitado           ↘ Em espera (dependência)    */

const DD_ESTADOS = [
  { id: 'submetido',          label: 'Submetido',          color: '#3859D0' },
  { id: 'em-analise',         label: 'Em análise',         color: '#f59e0b' },
  { id: 'aprovado',           label: 'Aprovado',           color: '#2EBD68' },
  { id: 'em-espera',          label: 'Em espera',          color: '#94A4C4' },
  { id: 'em-desenvolvimento', label: 'Em desenvolvimento', color: '#8b5cf6' },
  { id: 'em-teste',           label: 'Em teste',           color: '#0ea5e9' },
  { id: 'entregue',           label: 'Entregue',           color: '#10b981' },
  { id: 'rejeitado',          label: 'Rejeitado',          color: '#ef4444' },
];

const DD_TRANS = {
  'submetido':          { next: 'em-analise',        nextLabel: 'Iniciar análise',  canReject: false, canHold: false, prev: null },
  'em-analise':         { next: 'aprovado',           nextLabel: 'Aprovar',          canReject: true,  canHold: false, prev: 'submetido' },
  'aprovado':           { next: 'em-desenvolvimento', nextLabel: 'Iniciar dev.',     canReject: false, canHold: true,  prev: 'em-analise' },
  'em-espera':          { next: 'em-desenvolvimento', nextLabel: 'Retomar dev.',     canReject: false, canHold: false, prev: 'aprovado' },
  'em-desenvolvimento': { next: 'em-teste',           nextLabel: 'Iniciar testes',   canReject: false, canHold: false, prev: 'aprovado' },
  'em-teste':           { next: 'entregue',           nextLabel: 'Marcar entregue', canReject: false, canHold: false, prev: 'em-desenvolvimento' },
  'entregue':           { next: null,                                                canReject: false, canHold: false, prev: 'em-teste' },
  'rejeitado':          { next: null,                                                canReject: false, canHold: false, prev: 'em-analise' },
};

const ddRowToReq = (r) => ({
  id:              r.id,
  tipo:            r.tipo || 'dashboard',
  estado:          r.estado,
  fields:          r.fields || {},
  selMod:          r.sel_mod       || '',
  selSub:          r.sel_sub       || '',
  selOutro:        r.sel_outro     || '',
  motivo_rejeicao: r.motivo_rejeicao || '',
  submitted_by:    r.submitted_by  || '',
  submitted_name:  r.submitted_name || '',
  criado_em:       r.created_at,
  atualizado_em:   r.updated_at,
});

// ── Shared style constants ─────────────────────────────────────────────────────
const GD_C = {
  navy:'#112954', blue:'#3859D0', dark:'#283252', body:'#404968',
  muted:'#94A4C4', border:'#E1E7F3', surf:'#F9FAFF', meta:'#EBEFF9',
};
const gdAutoH = e => { e.target.style.height='auto'; e.target.style.height=e.target.scrollHeight+'px'; };

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

const GdView = ({ label, value }) => !value ? null : (
  <div>
    <GdLabel>{label}</GdLabel>
    <div style={{ fontSize:13, color:GD_C.dark, padding:'4px 0 6px', borderBottom:`1.5px solid ${GD_C.border}`, minHeight:24, whiteSpace:'pre-wrap', lineHeight:1.55 }}>{value}</div>
  </div>
);

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

const GdTA = ({ label, value, onChange, placeholder, bg }) => (
  <div>
    {label && <GdLabel>{label}</GdLabel>}
    <textarea value={value||''} onChange={e=>onChange(e.target.value)} onInput={gdAutoH} placeholder={placeholder||''}
      rows={2}
      style={{ width:'100%', border:`1.5px dashed ${GD_C.border}`, borderRadius:6, padding:'8px 10px', fontSize:13, color:GD_C.dark, background:bg||GD_C.surf, outline:'none', resize:'none', fontFamily:'var(--font-body)', boxSizing:'border-box', lineHeight:1.5 }} />
  </div>
);

const GdSection = ({ num, title, sub }) => (
  <div style={{ background:GD_C.navy, borderRadius:8, padding:'12px 18px', marginBottom:16, display:'flex', alignItems:'center', gap:14 }}>
    <div style={{ fontSize:20, fontWeight:800, color:'rgba(255,255,255,0.25)', fontFamily:'var(--font-display)', lineHeight:1 }}>{num}</div>
    <div>
      <div style={{ fontSize:13, fontWeight:700, color:'#fff', letterSpacing:'0.02em' }}>{title}</div>
      {sub && <div style={{ fontSize:11, color:'rgba(255,255,255,0.5)', marginTop:2 }}>{sub}</div>}
    </div>
  </div>
);

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

const GdCheck = ({ label, checked, onChange, editing }) => editing ? (
  <label style={{ display:'flex', alignItems:'center', gap:8, cursor:'pointer', fontSize:13, color:GD_C.dark }}>
    <input type="checkbox" checked={!!checked} onChange={e=>onChange(e.target.checked)}
      style={{ width:15, height:15, accentColor:GD_C.blue, cursor:'pointer' }} />
    {label}
  </label>
) : checked ? (
  <div style={{ fontSize:13, color:GD_C.dark, display:'flex', alignItems:'center', gap:6 }}>
    <span style={{ color:GD_C.blue }}>✓</span> {label}
  </div>
) : null;

const GdCell = ({ value, onChange, bg, editing }) => editing ? (
  <textarea value={value||''} onChange={e=>onChange(e.target.value)} onInput={gdAutoH} rows={1}
    style={{ width:'100%', border:'none', padding:'6px 8px', fontSize:12, color:GD_C.dark, background:bg||'#fff', outline:'none', resize:'none', fontFamily:'var(--font-body)', boxSizing:'border-box' }} />
) : (
  <div style={{ fontSize:12, color:GD_C.dark, padding:'6px 8px', minHeight:28, whiteSpace:'pre-wrap', lineHeight:1.4 }}>{value||''}</div>
);

// ── Detail Modal ───────────────────────────────────────────────────────────────
const DashDetailModal = ({ req, onClose, onSave, onDelete }) => {
  const [editing, setEditing] = React.useState(false);
  const [fields, setFields] = React.useState({ ...req.fields });
  const [selMod,   setSelMod]   = React.useState(req.selMod   || '');
  const [selSub,   setSelSub]   = React.useState(req.selSub   || '');
  const [selOutro, setSelOutro] = React.useState(req.selOutro || '');
  const [saving, setSaving] = React.useState(false);

  const set = (k, v) => setFields(prev => ({ ...prev, [k]: v }));
  const est  = DD_ESTADOS.find(e => e.id === req.estado);
  const isFn = req.tipo === 'funcionalidade';

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

  const handleSave = async () => {
    setSaving(true);
    await onSave(req.id, { fields, sel_mod: selMod, sel_sub: selSub, sel_outro: selOutro });
    setSaving(false);
    setEditing(false);
  };

  const handleCancel = () => {
    setFields({ ...req.fields });
    setSelMod(req.selMod || ''); setSelSub(req.selSub || ''); setSelOutro(req.selOutro || '');
    setEditing(false);
  };

  const submenus = React.useMemo(() => {
    if (!selMod) return [];
    const m = (window.PORTAL_MODULES || []).find(m => m.label === selMod);
    return m ? m.submenus : [];
  }, [selMod]);

  const thSt = { padding:'8px 10px', fontSize:11, fontWeight:700, color:'#fff', textAlign:'left', letterSpacing:'0.05em', textTransform:'uppercase', background:GD_C.navy };
  const tdSt = (bg) => ({ borderRight:`1px solid ${GD_C.border}`, verticalAlign:'top', background:bg||'#fff' });

  const kRow = (n, bg) => {
    const ks = ['a','b','c','d','e'].map(l => `k${n}${l}`);
    return (
      <tr key={n} style={{ background:bg }}>
        {ks.map((k,i) => <td key={k} style={{ ...tdSt(bg), ...(i===4?{borderRight:'none'}:{}) }}><GdCell value={fields[k]} onChange={v=>set(k,v)} bg={bg} editing={editing} /></td>)}
      </tr>
    );
  };
  const mRow = (n, bg) => {
    const ks = ['a','b','c','d','e'].map(l => `m${n}${l}`);
    return (
      <tr key={n} style={{ background:bg }}>
        {ks.map((k,i) => <td key={k} style={{ ...tdSt(bg), ...(i===4?{borderRight:'none'}:{}) }}><GdCell value={fields[k]} onChange={v=>set(k,v)} bg={bg} editing={editing} /></td>)}
      </tr>
    );
  };
  const ioRow = (n, bg) => {
    const ks = ['a','b','c','d'].map(l => `io${n}${l}`);
    return (
      <tr key={n} style={{ background:bg }}>
        {ks.map((k,i) => <td key={k} style={{ ...tdSt(bg), ...(i===3?{borderRight:'none'}:{}) }}><GdCell value={fields[k]} onChange={v=>set(k,v)} bg={bg} editing={editing} /></td>)}
      </tr>
    );
  };

  const titleText = isFn
    ? (fields.fn_descricao ? fields.fn_descricao.substring(0,80) : (fields.fn_tipo || '(funcionalidade)'))
    : (fields.m_dashboard || fields.id_nome || '(sem título)');

  // Context selector (nav module/submenu) — shared for both tipos in edit mode
  const CtxSelector = () => (
    <div style={{ background:GD_C.navy, borderRadius:10, padding:'14px 18px', marginBottom:22, display:'flex', gap:16, flexWrap:'wrap', alignItems:'flex-end' }}>
      <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={{ 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', minWidth:180, fontFamily:'var(--font-body)' }}>
          <option value="">Seleccionar módulo…</option>
          {(window.PORTAL_MODULES||[]).map(m=><option key={m.label} value={m.label}>{m.label}</option>)}
        </select>
      </div>
      <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={{ 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', minWidth:180, fontFamily:'var(--font-body)', opacity:selMod?1:0.45 }}>
          <option value="">Seleccionar submenu…</option>
          {submenus.map(s=><option key={s} value={s}>{s}</option>)}
        </select>
      </div>
      {selSub==='Outro' && (
        <div style={{ flex:1, minWidth:160 }}>
          <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={{ 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', width:'100%', boxSizing:'border-box', fontFamily:'var(--font-body)' }} />
        </div>
      )}
    </div>
  );

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:9999 }}
         onClick={onClose}>
      <div style={{ background:'#f4f6fb', borderRadius:14, width:'min(920px,95vw)', maxHeight:'92vh', display:'flex', flexDirection:'column', boxShadow:'0 24px 80px rgba(0,0,0,.28)', overflow:'hidden' }}
           onClick={e=>e.stopPropagation()}>

        {/* Sticky header */}
        <div style={{ background:'#fff', borderBottom:`1px solid ${GD_C.border}`, padding:'16px 24px', display:'flex', alignItems:'center', gap:12, flexShrink:0 }}>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:2 }}>
              <div style={{ fontSize:11, fontFamily:'var(--font-mono)', color:GD_C.muted, textTransform:'uppercase', letterSpacing:'0.07em' }}>
                {selMod}{selSub ? ` · ${selSub==='Outro'?(selOutro||'Outro'):selSub}` : ''}
              </div>
              <span style={{ padding:'2px 8px', borderRadius:10, background:isFn?'#ede9fe':'#eff6ff', color:isFn?'#7c3aed':'#3859D0', fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.05em' }}>
                {isFn ? 'Funcionalidade' : 'Dashboard'}
              </span>
            </div>
            <div style={{ fontSize:17, fontWeight:600, color:GD_C.dark }}>{titleText}</div>
          </div>
          {est && <div style={{ padding:'3px 12px', borderRadius:20, background:est.color+'18', color:est.color, fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', flexShrink:0 }}>{est.label}</div>}
          {!editing && <button onClick={()=>onDelete(req.id)} className="btn btn-sm" style={{ fontSize:12, flexShrink:0, background:'#dc2626', color:'#fff', borderColor:'#dc2626' }}>Apagar</button>}
          {!editing && <button onClick={()=>setEditing(true)} className="btn btn-sm btn-primary" style={{ fontSize:12, flexShrink:0 }}>Editar</button>}
          {editing  && <button onClick={handleSave} disabled={saving} className="btn btn-sm btn-primary" style={{ fontSize:12, flexShrink:0 }}>{saving?'A guardar…':'Guardar'}</button>}
          {editing  && <button onClick={handleCancel} className="btn btn-sm" style={{ fontSize:12, flexShrink:0 }}>Cancelar</button>}
          <button onClick={onClose} style={{ background:'none', border:'none', cursor:'pointer', fontSize:22, color:GD_C.muted, lineHeight:1, padding:'0 0 0 8px', flexShrink:0 }}>×</button>
        </div>

        {/* Scrollable body */}
        <div className="scrollbar" style={{ overflowY:'auto', padding:'24px 28px 48px', flex:1 }}>

          {editing && <CtxSelector />}

          {/* ═══ DASHBOARD FORM ═══ */}
          {!isFn && (<>
            <div style={{ background:GD_C.meta, borderRadius:8, padding:'14px 18px', marginBottom:22, display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:16 }}>
              {editing ? (<>
                <GdInput label="Dashboard" value={fields.m_dashboard} onChange={v=>set('m_dashboard',v)} placeholder="Nome" />
                <GdInput label="Owner" value={fields.m_owner} onChange={v=>set('m_owner',v)} placeholder="Responsável" />
                <GdInput label="Data" value={fields.m_date} onChange={v=>set('m_date',v)} placeholder="DD / MM / AAAA" />
                <GdInput label="Versão" value={fields.m_version} onChange={v=>set('m_version',v)} placeholder="1.0" />
              </>) : (<>
                <GdView label="Dashboard" value={fields.m_dashboard} />
                <GdView label="Owner" value={fields.m_owner} />
                <GdView label="Data" value={fields.m_date} />
                <GdView label="Versão" value={fields.m_version} />
              </>)}
            </div>

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

            <GdSection num="2" title="Objectivo e Propósito" sub="Porque é que este dashboard existe" />
            <div style={{ display:'flex', flexDirection:'column', gap:12, marginBottom:24 }}>
              {editing ? (<>
                <GdTA label="Objetivo principal" 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." />
                <GdTA label="Pergunta 1" value={fields.obj_q1} onChange={v=>set('obj_q1',v)} placeholder="1. Que pergunta deve esta vista responder?" />
                <GdTA label="Pergunta 2" value={fields.obj_q2} onChange={v=>set('obj_q2',v)} placeholder="2. …" />
                <GdTA label="Pergunta 3" value={fields.obj_q3} onChange={v=>set('obj_q3',v)} placeholder="3. …" />
                <GdTA label="Decisões que suporta" value={fields.obj_dec} onChange={v=>set('obj_dec',v)} placeholder="Que ações ou decisões serão tomadas com base nesta informação." />
              </>) : (<>
                <GdView label="Objetivo principal" value={fields.obj_main} />
                <GdView label="Pergunta 1" value={fields.obj_q1} />
                <GdView label="Pergunta 2" value={fields.obj_q2} />
                <GdView label="Pergunta 3" value={fields.obj_q3} />
                <GdView label="Decisões que suporta" value={fields.obj_dec} />
              </>)}
            </div>

            <GdSection num="3" title="KPIs e Métricas" sub="Definição, fórmula de cálculo e fonte de dados" />
            <div style={{ overflowX:'auto', marginBottom:24 }}>
              <table style={{ width:'100%', borderCollapse:'collapse', border:`1px solid ${GD_C.border}`, borderRadius:8, overflow:'hidden', tableLayout:'fixed' }}>
                <colgroup><col style={{width:'20%'}}/><col style={{width:'26%'}}/><col style={{width:'24%'}}/><col style={{width:'18%'}}/><col style={{width:'12%'}}/></colgroup>
                <thead><tr>{['Métrica','Definição','Fórmula de cálculo','Fonte de dados','Granularidade'].map(h=><th key={h} style={thSt}>{h}</th>)}</tr></thead>
                <tbody>{[1,2,3,4,5,6].map(n=>kRow(n, n%2===0?GD_C.surf:'#fff'))}</tbody>
              </table>
            </div>

            <GdSection num="4" title="Resultados Esperados e Metas" sub="O que define o sucesso de cada KPI" />
            <div style={{ overflowX:'auto', marginBottom:24 }}>
              <table style={{ width:'100%', borderCollapse:'collapse', border:`1px solid ${GD_C.border}`, borderRadius:8, overflow:'hidden', tableLayout:'fixed' }}>
                <colgroup><col style={{width:'24%'}}/><col style={{width:'16%'}}/><col style={{width:'16%'}}/><col style={{width:'16%'}}/><col style={{width:'28%'}}/></colgroup>
                <thead><tr>{['KPI','Baseline atual','Meta','Prazo','Critério de sucesso'].map(h=><th key={h} style={thSt}>{h}</th>)}</tr></thead>
                <tbody>{[1,2,3,4,5].map(n=>mRow(n, n%2===0?GD_C.surf:'#fff'))}</tbody>
              </table>
            </div>

            <GdSection num="5" title="Notas de Implementação" sub="Dependências, riscos e pressupostos" />
            <div style={{ display:'flex', flexDirection:'column', gap:12, marginBottom:16 }}>
              {editing ? (<>
                <GdTA label="Dependências de dados" 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." />
                <GdTA label="Pressupostos e riscos" value={fields.impl_risk} onChange={v=>set('impl_risk',v)} placeholder="Qualidade de dados, definições ambíguas, prazos de disponibilidade." />
              </>) : (<>
                <GdView label="Dependências de dados" value={fields.impl_dep} />
                <GdView label="Pressupostos e riscos" value={fields.impl_risk} />
              </>)}
            </div>
          </>)}

          {/* ═══ FUNCIONALIDADE FORM ═══ */}
          {isFn && (<>
            <GdSection num="1" title="Identificação" sub="Tipo de pedido, módulo alvo e audiência" />
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:24 }}>
              {editing ? (<>
                <GdSelectComp label="Tipo de funcionalidade" value={fields.fn_tipo} onChange={v=>set('fn_tipo',v)} options={FN_TIPOS} editing={editing} placeholder="Tipo de pedido…" />
                <GdInput label="Módulo alvo" value={fields.fn_modulo} onChange={v=>set('fn_modulo',v)} placeholder="Módulo existente que afecta" />
                <GdInput label="Público-alvo" value={fields.fn_publico} onChange={v=>set('fn_publico',v)} placeholder="Quem vai usar" />
                <GdInput label="Frequência de uso" value={fields.fn_frequencia} onChange={v=>set('fn_frequencia',v)} placeholder="Diária · Semanal · Pontual…" />
              </>) : (<>
                <GdView label="Tipo de funcionalidade" value={fields.fn_tipo} />
                <GdView label="Módulo alvo" value={fields.fn_modulo} />
                <GdView label="Público-alvo" value={fields.fn_publico} />
                <GdView label="Frequência de uso" value={fields.fn_frequencia} />
              </>)}
            </div>

            <GdSection num="2" title="Problema e Contexto" sub="Situação actual e impacto esperado" />
            <div style={{ display:'flex', flexDirection:'column', gap:12, marginBottom:24 }}>
              {editing ? (<>
                <GdTA label="Problema / necessidade" value={fields.fn_problema} onChange={v=>set('fn_problema',v)} placeholder="Que problema concreto resolve ou que necessidade satisfaz?" />
                <GdTA label="Impacto esperado" value={fields.fn_impacto} onChange={v=>set('fn_impacto',v)} placeholder="Que melhoria concreta traz? Quantificável se possível." />
                <GdTA label="Como é feito hoje" value={fields.fn_hoje} onChange={v=>set('fn_hoje',v)} placeholder="Processo manual, outra ferramenta, não é feito…" />
              </>) : (<>
                <GdView label="Problema / necessidade" value={fields.fn_problema} />
                <GdView label="Impacto esperado" value={fields.fn_impacto} />
                <GdView label="Como é feito hoje" value={fields.fn_hoje} />
              </>)}
            </div>

            <GdSection num="3" title="Solução Proposta" sub="Descrição funcional e fluxo de utilização" />
            <div style={{ display:'flex', flexDirection:'column', gap:12, marginBottom:24 }}>
              {editing ? (<>
                <GdTA label="Descrição da solução" value={fields.fn_descricao} onChange={v=>set('fn_descricao',v)} placeholder="Descreva a funcionalidade proposta — o que faz, como aparece ao utilizador." />
                <GdTA label="Fluxo de utilização" value={fields.fn_fluxo} onChange={v=>set('fn_fluxo',v)} placeholder="Passo-a-passo: o utilizador faz X → o sistema faz Y → resultado Z." />
              </>) : (<>
                <GdView label="Descrição da solução" value={fields.fn_descricao} />
                <GdView label="Fluxo de utilização" value={fields.fn_fluxo} />
              </>)}
            </div>

            <GdSection num="4" title="Inputs e Outputs" sub="Dados necessários à entrada e resultados produzidos" />
            <div style={{ overflowX:'auto', marginBottom:24 }}>
              <table style={{ width:'100%', borderCollapse:'collapse', border:`1px solid ${GD_C.border}`, borderRadius:8, overflow:'hidden', tableLayout:'fixed' }}>
                <colgroup><col style={{width:'25%'}}/><col style={{width:'25%'}}/><col style={{width:'25%'}}/><col style={{width:'25%'}}/></colgroup>
                <thead><tr>{['Input','Fonte','Output','Destino'].map(h=><th key={h} style={thSt}>{h}</th>)}</tr></thead>
                <tbody>{[1,2,3,4].map(n=>ioRow(n, n%2===0?GD_C.surf:'#fff'))}</tbody>
              </table>
            </div>

            <GdSection num="5" title="Integrações" sub="Sistemas e APIs que esta funcionalidade vai tocar" />
            <div style={{ marginBottom:24 }}>
              <div style={{ display:'flex', flexWrap:'wrap', gap:16, marginBottom:12 }}>
                <GdCheck label="ERP / Primavera" checked={fields.fn_int_erp}   onChange={v=>set('fn_int_erp',v)}   editing={editing} />
                <GdCheck label="WhatsApp / Heydigi" checked={fields.fn_int_wa} onChange={v=>set('fn_int_wa',v)}   editing={editing} />
                <GdCheck label="Meta Ads"  checked={fields.fn_int_meta}        onChange={v=>set('fn_int_meta',v)} editing={editing} />
                <GdCheck label="Power BI"  checked={fields.fn_int_pbi}         onChange={v=>set('fn_int_pbi',v)}  editing={editing} />
                <GdCheck label="Outra"     checked={fields.fn_int_outra}       onChange={v=>set('fn_int_outra',v)} editing={editing} />
              </div>
              {editing
                ? <GdTA label="Detalhe de integrações" value={fields.fn_int_detalhe} onChange={v=>set('fn_int_detalhe',v)} placeholder="Especifique endpoints, tabelas ou dados necessários de cada sistema." />
                : <GdView label="Detalhe de integrações" value={fields.fn_int_detalhe} />
              }
            </div>

            <GdSection num="6" title="Critério de Aceitação" sub="O que tem de funcionar para a funcionalidade ser considerada entregue" />
            <div style={{ display:'flex', flexDirection:'column', gap:12, marginBottom:24 }}>
              {editing ? (<>
                <GdTA label="Critério de aceitação" value={fields.fn_criterio} onChange={v=>set('fn_criterio',v)} placeholder="Lista os critérios que definem que a funcionalidade está completa e correcta." />
                <GdTA label="Casos de teste" value={fields.fn_testes} onChange={v=>set('fn_testes',v)} placeholder="Cenários concretos: dado X → esperado Y. Inclui casos de erro." />
              </>) : (<>
                <GdView label="Critério de aceitação" value={fields.fn_criterio} />
                <GdView label="Casos de teste" value={fields.fn_testes} />
              </>)}
            </div>

            <GdSection num="7" title="Prioridade e Contexto" sub="Urgência, prazo e dependências" />
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:16, marginBottom:16 }}>
              {editing ? (<>
                <GdSelectComp label="Criticidade" value={fields.fn_criticidade} onChange={v=>set('fn_criticidade',v)} options={FN_CRITS} editing={editing} placeholder="Nível de criticidade…" />
                <GdInput label="Prazo desejado" value={fields.fn_prazo} onChange={v=>set('fn_prazo',v)} placeholder="DD / MM / AAAA ou sprint" />
                <GdTA label="Dependências" value={fields.fn_deps} onChange={v=>set('fn_deps',v)} placeholder="Outros pedidos, dados ou recursos necessários." />
              </>) : (<>
                <GdView label="Criticidade" value={fields.fn_criticidade} />
                <GdView label="Prazo desejado" value={fields.fn_prazo} />
                <GdView label="Dependências" value={fields.fn_deps} />
              </>)}
            </div>
          </>)}

          {req.motivo_rejeicao && (
            <div style={{ marginTop:8, padding:'12px 16px', background:'#fef2f2', borderRadius:8 }}>
              <GdLabel>Motivo de rejeição</GdLabel>
              <div style={{ fontSize:13, color:'#dc2626', lineHeight:1.5 }}>{req.motivo_rejeicao}</div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ── Kanban Card ────────────────────────────────────────────────────────────────
const GerirDashCard = ({ req, onAdvance, onReject, onGoBack, onHold, onDelete, onDetail }) => {
  const tr    = DD_TRANS[req.estado] || {};
  const isFn  = req.tipo === 'funcionalidade';
  const name  = isFn
    ? (req.fields?.fn_descricao ? req.fields.fn_descricao.substring(0,60) : (req.fields?.fn_tipo || '(funcionalidade)'))
    : (req.fields?.m_dashboard || req.fields?.id_nome || '(sem título)');
  const owner   = req.fields?.m_owner || req.fields?.id_owner || req.submitted_name || '—';
  const modulo  = req.selMod || '—';
  const submenu = req.selSub === 'Outro' ? (req.selOutro || 'Outro') : (req.selSub || '—');
  const date    = req.criado_em ? new Date(req.criado_em).toLocaleDateString('pt-PT') : '—';

  return (
    <div onClick={() => onDetail(req)}
      style={{ background:'#fff', borderRadius:8, border:'1px solid #E1E7F3', padding:'12px 14px', marginBottom:8, cursor:'pointer', transition:'box-shadow .15s' }}
      onMouseEnter={e => e.currentTarget.style.boxShadow='0 2px 12px rgba(17,41,84,.08)'}
      onMouseLeave={e => e.currentTarget.style.boxShadow='none'}>

      <div style={{ marginBottom:6 }}>
        <span style={{ padding:'2px 7px', borderRadius:10, background:isFn?'#ede9fe':'#eff6ff', color:isFn?'#7c3aed':'#3859D0', fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.04em' }}>
          {isFn ? 'Funcionalidade' : 'Dashboard'}
        </span>
      </div>
      <div style={{ fontSize:13, fontWeight:600, color:'#283252', marginBottom:4, lineHeight:1.3, fontFamily:'var(--font-body)' }}>{name}</div>
      <div style={{ fontSize:11, color:'#94A4C4', marginBottom:6, fontFamily:'var(--font-mono)', textTransform:'uppercase', letterSpacing:'0.04em' }}>
        {modulo}{submenu && submenu !== '—' ? ` · ${submenu}` : ''}
      </div>
      <div style={{ fontSize:11, color:'#404968' }}>{owner}</div>
      <div style={{ fontSize:10, color:'#94A4C4', marginTop:2 }}>{date}</div>

      {req.motivo_rejeicao && (
        <div style={{ marginTop:8, padding:'6px 8px', background:'#fef2f2', borderRadius:4, fontSize:11, color:'#dc2626', lineHeight:1.4 }}>
          {req.motivo_rejeicao}
        </div>
      )}

      <div style={{ marginTop:10, display:'flex', gap:6, flexWrap:'wrap' }} onClick={e=>e.stopPropagation()}>
        {tr.prev && (
          <button onClick={()=>onGoBack(req.id)} className="btn btn-xs"
            style={{ fontSize:11, padding:'3px 8px', color:'#94A4C4', borderColor:'#E1E7F3' }}>
            ← Recuar
          </button>
        )}
        {tr.canHold && (
          <button onClick={()=>onHold(req.id)} className="btn btn-xs"
            style={{ fontSize:11, padding:'3px 8px', color:'#64748b', borderColor:'#cbd5e1', background:'#f8fafc' }}>
            ⏸ Em espera
          </button>
        )}
        {tr.next && (
          <button onClick={()=>onAdvance(req.id)} className="btn btn-xs btn-primary"
            style={{ fontSize:11, padding:'3px 8px' }}>
            {tr.nextLabel} →
          </button>
        )}
        {tr.canReject && (
          <button onClick={()=>onReject(req.id)} className="btn btn-xs"
            style={{ fontSize:11, padding:'3px 8px', color:'#dc2626', borderColor:'#fca5a5', background:'#fff5f5' }}>
            Rejeitar
          </button>
        )}
      </div>
    </div>
  );
};

// ── Main Screen ────────────────────────────────────────────────────────────────
const BusinessAIGerirDashboards = () => {
  const [requests,     setRequests]     = React.useState([]);
  const [loading,      setLoading]      = React.useState(true);
  const [rejectTarget, setRejectTarget] = React.useState(null);
  const [rejectMotivo, setRejectMotivo] = React.useState('');
  const [deleteTarget, setDeleteTarget] = React.useState(null);
  const [detail,       setDetail]       = React.useState(null);
  const [tipoFilter,   setTipoFilter]   = React.useState('todos');

  const fetchRequests = () => {
    fetch('/api/dashboard-requests')
      .then(r => r.json())
      .then(rows => { setRequests(rows.map(ddRowToReq)); setLoading(false); })
      .catch(() => setLoading(false));
  };

  React.useEffect(() => {
    fetchRequests();
    const interval = setInterval(fetchRequests, 5000);
    return () => clearInterval(interval);
  }, []);

  const patchRequest = async (id, body) => {
    await fetch(`/api/dashboard-requests/${id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    fetchRequests();
  };

  const handleGoBack = (id) => {
    const req = requests.find(r => r.id === id);
    if (!req) return;
    const prev = DD_TRANS[req.estado]?.prev;
    if (!prev) return;
    const extra = req.estado === 'rejeitado' ? { motivo_rejeicao: '' } : {};
    patchRequest(id, { estado: prev, ...extra });
  };

  const handleAdvance = (id) => {
    const req = requests.find(r => r.id === id);
    if (!req) return;
    const next = DD_TRANS[req.estado]?.next;
    if (next) patchRequest(id, { estado: next });
  };

  const handleHold    = (id) => patchRequest(id, { estado: 'em-espera' });
  const handleOpenReject = (id) => { setRejectTarget(id); setRejectMotivo(''); };

  const handleConfirmDelete = async () => {
    await fetch(`/api/dashboard-requests/${deleteTarget}`, { method: 'DELETE' });
    setDeleteTarget(null);
    fetchRequests();
  };
  const handleConfirmReject = () => {
    patchRequest(rejectTarget, { estado: 'rejeitado', motivo_rejeicao: rejectMotivo });
    setRejectTarget(null);
  };

  const visible  = tipoFilter === 'todos' ? requests : requests.filter(r => r.tipo === tipoFilter);
  const totalAll = requests.length;

  const CHIPS = [
    { id:'todos',          label:'Todos',           color:'#283252' },
    { id:'dashboard',      label:'Dashboard',        color:'#3859D0' },
    { id:'funcionalidade', label:'Funcionalidade',   color:'#7c3aed' },
  ];

  return (
    <div className="scrollbar" style={{ height:'100%', overflowY:'auto', background:'#f4f6fb' }}>
      <div style={{ padding:'28px 24px 80px', minWidth:1200 }}>

        {/* Header */}
        <div style={{ marginBottom:18, display:'flex', alignItems:'flex-end', justifyContent:'space-between' }}>
          <div>
            <div style={{ fontSize:11, fontFamily:'var(--font-mono)', color:'var(--text-dim)', letterSpacing:'0.08em', textTransform:'uppercase' }}>BUSINESS & AI · GESTÃO DE PEDIDOS</div>
            <h2 style={{ margin:'4px 0 0', fontSize:22, fontWeight:500, color:'var(--text)', letterSpacing:'-0.01em' }}>Gestão de Pedidos</h2>
          </div>
          {totalAll > 0 && <div style={{ fontSize:12, color:'#94A4C4', fontFamily:'var(--font-mono)' }}>{totalAll} pedido{totalAll!==1?'s':''}</div>}
        </div>

        {/* Tipo filter chips */}
        <div style={{ display:'flex', gap:8, marginBottom:20 }}>
          {CHIPS.map(chip => {
            const active = tipoFilter === chip.id;
            const count  = chip.id === 'todos' ? totalAll : requests.filter(r => r.tipo === chip.id).length;
            return (
              <button key={chip.id} onClick={() => setTipoFilter(chip.id)}
                style={{ padding:'5px 14px', borderRadius:20, fontSize:12, fontWeight:600, cursor:'pointer', transition:'all .15s',
                  background: active ? chip.color : '#fff',
                  color:      active ? '#fff' : chip.color,
                  border:     `1.5px solid ${active ? chip.color : '#E1E7F3'}`,
                  fontFamily: 'var(--font-body)',
                }}>
                {chip.label}{count > 0 ? ` (${count})` : ''}
              </button>
            );
          })}
        </div>

        {loading ? (
          <div style={{ textAlign:'center', padding:'80px 0', color:'#94A4C4', fontSize:13 }}>A carregar…</div>
        ) : totalAll === 0 ? (
          <div style={{ textAlign:'center', padding:'80px 0', color:'#94A4C4' }}>
            <div style={{ fontSize:32, marginBottom:12 }}>—</div>
            <div style={{ fontSize:14 }}>Nenhum pedido submetido ainda.</div>
            <div style={{ fontSize:12, marginTop:6 }}>Usa <strong>Definir Pedido</strong> para criar e submeter um pedido.</div>
          </div>
        ) : (
          <div style={{ display:'grid', gridTemplateColumns:'repeat(8, minmax(155px, 1fr))', gap:12, alignItems:'start' }}>
            {DD_ESTADOS.map(est => {
              const col = visible.filter(r => r.estado === est.id);
              return (
                <div key={est.id}>
                  <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:10, paddingBottom:8, borderBottom:`2px solid ${est.color}` }}>
                    <span style={{ fontSize:10, fontWeight:700, color:'#283252', textTransform:'uppercase', letterSpacing:'0.05em', fontFamily:'var(--font-mono)', flex:1, lineHeight:1.3 }}>{est.label}</span>
                    {col.length > 0 && <span style={{ fontSize:10, background:est.color+'22', color:est.color, borderRadius:10, padding:'1px 7px', fontWeight:700, flexShrink:0 }}>{col.length}</span>}
                  </div>
                  {col.length === 0 ? (
                    <div style={{ border:'1.5px dashed #E1E7F3', borderRadius:8, padding:'20px 8px', textAlign:'center', fontSize:10, color:'#c4cde0' }}>vazio</div>
                  ) : col.map(req => (
                    <GerirDashCard key={req.id} req={req}
                      onAdvance={handleAdvance} onReject={handleOpenReject}
                      onGoBack={handleGoBack}   onHold={handleHold}
                      onDelete={setDeleteTarget} onDetail={setDetail} />
                  ))}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Reject modal */}
      {rejectTarget && (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.45)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:9999 }}
             onClick={() => setRejectTarget(null)}>
          <div style={{ background:'#fff', borderRadius:12, padding:28, width:420, boxShadow:'0 20px 60px rgba(0,0,0,.22)' }}
               onClick={e=>e.stopPropagation()}>
            <div style={{ fontSize:16, fontWeight:600, color:'#283252', marginBottom:6 }}>Rejeitar pedido</div>
            <div style={{ fontSize:13, color:'#404968', marginBottom:14 }}>Indique o motivo da rejeição (opcional — ficará visível no card).</div>
            <textarea value={rejectMotivo} onChange={e=>setRejectMotivo(e.target.value)}
              placeholder="Motivo da rejeição…" rows={3}
              style={{ width:'100%', border:'1.5px solid #E1E7F3', borderRadius:6, padding:'8px 10px', fontSize:13, color:'#283252', outline:'none', resize:'vertical', boxSizing:'border-box', fontFamily:'var(--font-body)' }} />
            <div style={{ display:'flex', gap:8, justifyContent:'flex-end', marginTop:16 }}>
              <button onClick={() => setRejectTarget(null)} className="btn btn-sm">Cancelar</button>
              <button onClick={handleConfirmReject} className="btn btn-sm" style={{ background:'#dc2626', color:'#fff', borderColor:'#dc2626' }}>Confirmar rejeição</button>
            </div>
          </div>
        </div>
      )}

      {/* Delete confirmation modal */}
      {deleteTarget && (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.45)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:9999 }}
             onClick={() => setDeleteTarget(null)}>
          <div style={{ background:'#fff', borderRadius:12, padding:28, width:380, boxShadow:'0 20px 60px rgba(0,0,0,.22)' }}
               onClick={e=>e.stopPropagation()}>
            <div style={{ fontSize:16, fontWeight:600, color:'#283252', marginBottom:8 }}>Apagar pedido?</div>
            <div style={{ fontSize:13, color:'#404968', marginBottom:20, lineHeight:1.55 }}>Esta acção é irreversível. O pedido será eliminado permanentemente.</div>
            <div style={{ display:'flex', gap:8, justifyContent:'flex-end' }}>
              <button onClick={() => setDeleteTarget(null)} className="btn btn-sm">Cancelar</button>
              <button onClick={handleConfirmDelete} className="btn btn-sm" style={{ background:'#dc2626', color:'#fff', borderColor:'#dc2626' }}>Apagar</button>
            </div>
          </div>
        </div>
      )}

      {/* Detail modal */}
      {detail && (
        <DashDetailModal
          req={detail}
          onClose={() => setDetail(null)}
          onSave={async (id, body) => { await patchRequest(id, body); setDetail(null); }}
          onDelete={(id) => { setDetail(null); setDeleteTarget(id); }}
        />
      )}
    </div>
  );
};
window.BusinessAIGerirDashboards = BusinessAIGerirDashboards;
