// ═══ GENESIS ═══
// Tidal — Cabines: planta baixa interativa (vista de topo) sobre as imagens mapeadas em deck-layouts.js.
// O mapa é a forma principal de gerenciar vagas: clique numa cabine abre a "janelinha" (painel
// flutuante ancorado na cabine) com cada vaga; dá pra arrastar pessoas do painel "A acomodar"
// direto pra cabine ou pra uma vaga da janelinha. Altura fixa em px (igual pra todos os decks,
// referência = deck-02, a imagem mais panorâmica) para acompanhar o zoom do navegador.
// Cores do mockup: livre=verde, parcial=âmbar, completa=vermelho, selecionada=azul (♀ = ponto rosa).

const DeckPlan = ({vagas, usersById, filterDeck, setFilterDeck, lang,
                   selCabin, onSelCabin, dragging, onCabinDrop, onVagaAction, onUnassign, onHist,
                   mapFull, onToggleFull, kpisSlot, highlight, focusCabin, pool, onPick}) => {
  const L = window.DECK_LAYOUTS;
  const isMobile = useMobile();
  const rootRef = useRef(null);
  const [hovered, setHovered] = useState(null);   // chave do retângulo em hover
  const [dropKey, setDropKey] = useState(null);   // retângulo alvo de drag
  const [pickBerth, setPickBerth] = useState(null); // vaga livre com seletor de pessoa aberto
  const [pickQ, setPickQ] = useState('');           // busca dentro do seletor
  const deckIds = (L ? ['9','8','7','6'].filter(d => L[d]) : []);
  const [mapDeck, setMapDeck] = useState(deckIds[0] || null);

  // Se o filtro externo (modal de filtros) aponta pra um deck mapeado, o mapa acompanha
  useEffect(() => {
    if (L && filterDeck !== 'all' && L[filterDeck]) setMapDeck(filterDeck);
  }, [filterDeck]);

  // Trocar de cabine/janelinha fecha o seletor de pessoa
  useEffect(() => { setPickBerth(null); setPickQ(''); }, [selCabin]);

  // Foco externo (clique num card da aba Plano): troca o deck, seleciona a cabine e rola até o mapa
  useEffect(() => {
    if (!focusCabin || !L) return;
    const num = String(focusCabin.num);
    for (const d of deckIds) {
      const idx = L[d].cabins.findIndex(c => String(c.cab) === num);
      if (idx >= 0) {
        const cc = L[d].cabins[idx];
        setMapDeck(d);
        onSelCabin && onSelCabin(d + '-' + cc.cab + (cc.lado || '') + '-' + idx);
        break;
      }
    }
    if (rootRef.current) rootRef.current.scrollIntoView({ behavior:'smooth', block:'start' });
  }, [focusCabin]);

  const vagasById = useMemo(() => {
    const m = {};
    (vagas||[]).forEach(v => { m[v.id] = v; });
    return m;
  }, [vagas]);

  if (!L || !deckIds.length) {
    return (
      <div style={{padding:'22px 26px', color:'#F5EFE3'}}>
        <div style={{fontFamily:'var(--fm)',fontSize:12,color:'rgba(245,239,227,0.7)',fontStyle:'italic'}}>
          {lang==='pt'?'mapa de decks não carregado (deck-layouts.js ausente)':'deck map not loaded (deck-layouts.js missing)'}
        </div>
      </div>
    );
  }

  // Paleta do mockup
  const COR = {
    livre:       { fill:'rgba(123,182,126,0.55)', borda:'#7BB67E' },
    parcial:     { fill:'rgba(232,180,83,0.5)',   borda:'#E8B453' },
    completa:    { fill:'rgba(192,57,43,0.55)',   borda:'#C0392B' },
    selecionada: { fill:'rgba(127,168,201,0.5)',  borda:'#7FA8C9' },
  };

  const deckStats = (d) => {
    let occ = 0, tot = 0;
    L[d].cabins.forEach(c => c.vagas.forEach(vid => { tot++; if (vagasById[vid] && vagasById[vid].user) occ++; }));
    return {occ, tot};
  };

  const lay = L[mapDeck] || L[deckIds[0]];
  const cabinKey = (c, i) => mapDeck + '-' + c.cab + (c.lado || '') + '-' + i;
  // Altura fixa em px: igual pra todos os decks e acompanha o zoom do navegador (não usar vh)
  const MAP_H = isMobile ? 300 : 540;

  return (
    <div ref={rootRef} style={mapFull
      ? {height:'100%',display:'flex',flexDirection:'column',color:'#F5EFE3'}
      : {color:'#F5EFE3'}}>
      {/* Linha de decks + chips de KPI + fullscreen */}
      <div style={{display:'flex',alignItems:'center',gap:8,flexWrap:'wrap',marginBottom:10}}>
        {deckIds.map(d => {
          const {occ, tot} = deckStats(d);
          const active = mapDeck === d;
          return (
            <button key={d}
              onClick={() => { setMapDeck(d); setFilterDeck(filterDeck === d ? 'all' : d); onSelCabin && onSelCabin(null); }}
              style={{
                display:'inline-flex',alignItems:'baseline',gap:8,
                padding: isMobile ? '8px 12px' : '7px 14px', borderRadius:10, cursor:'pointer',
                background: active ? 'rgba(232,180,83,0.14)' : 'rgba(245,239,227,0.05)',
                border:`1px solid ${active ? 'rgba(232,180,83,0.5)' : 'rgba(245,239,227,0.12)'}`,
                color:'#F5EFE3', transition:'all .15s',
              }}>
              <span style={{fontFamily:'var(--fs)',fontSize: isMobile ? 14 : 15,fontWeight:500,lineHeight:1}}>Deck {'0'+d}</span>
              <span style={{fontFamily:'var(--fm)',fontSize:10.5,color:'rgba(245,239,227,0.65)'}}>{occ}<span style={{color:'rgba(245,239,227,0.35)'}}>/{tot}</span></span>
            </button>
          );
        })}
        <div style={{marginLeft:'auto',display:'flex',alignItems:'center',gap:6,flexWrap:'wrap'}}>
          {kpisSlot}
          {onToggleFull && (
            <button onClick={onToggleFull} title={lang==='pt'?'expandir o mapa':'expand the map'}
              style={{border:'1px solid rgba(245,239,227,0.25)',background:'rgba(251,247,240,0.1)',color:'var(--cream)',borderRadius:8,cursor:'pointer',padding:'5px 9px',fontFamily:'var(--fm)',fontSize:12,lineHeight:1}}>
              ⛶
            </button>
          )}
        </div>
      </div>

      {/* Legenda compacta */}
      <div style={{display:'flex',gap: isMobile ? 10 : 14,fontFamily:'var(--fm)',fontSize: isMobile ? 9.5 : 10.5,letterSpacing:0.5,alignItems:'center',flexWrap:'wrap',marginBottom:10,color:'rgba(245,239,227,0.7)'}}>
        <LegendDot c={COR.livre.borda} l={isMobile ? '' : (lang==='pt'?'livre':'free')}/>
        <LegendDot c={COR.parcial.borda} l={isMobile ? '' : (lang==='pt'?'parcial':'partial')}/>
        <LegendDot c={COR.completa.borda} l={isMobile ? '' : (lang==='pt'?'completa':'full')}/>
        <LegendDot c={COR.selecionada.borda} l={isMobile ? '' : (lang==='pt'?'selecionada':'selected')}/>
        <LegendDot c="#C36474" l="♀"/>
      </div>

      {/* Imagem do deck (altura fixa, centralizada, laterais escuras) + retângulos das cabines */}
      <div style={{
        position:'relative',
        height: mapFull ? undefined : MAP_H,
        flex: mapFull ? '1 1 0' : undefined,
        minHeight: mapFull ? 0 : undefined,
        borderRadius:14, overflow:'hidden',
        border:'1px solid rgba(245,239,227,0.12)',
        background:'rgba(0,0,0,0.28)',
        display:'flex', justifyContent:'center',
      }}
        onClick={() => onSelCabin && onSelCabin(null)}>
        {/* Wrapper no aspect ratio exato da imagem — os rects em % ficam sempre alinhados */}
        <div style={{position:'relative', height:'100%', aspectRatio:`${lay.w}/${lay.h}`, maxWidth:'100%', lineHeight:0}}>
          <img src={lay.img} alt={`Deck ${mapDeck}`} draggable={false}
            style={{position:'absolute', inset:0, width:'100%', height:'100%', userSelect:'none'}}/>
          {lay.cabins.map((c, i) => {
            const [x, y, w, h] = c.r;
            const berths = c.vagas.map(vid => vagasById[vid]).filter(Boolean);
            const occ = berths.filter(b => b.user).length;
            const tot = c.vagas.length;
            const full = tot > 0 && occ === tot;
            const partial = occ > 0 && occ < tot;
            const hasF = berths.some(b => b.user && usersById[b.user] && usersById[b.user].genero === 'F');
            const key = cabinKey(c, i);
            const isHover = hovered === key;
            const isSel = selCabin === key;
            const isDrop = dropKey === key;
            const isHl = highlight && highlight.has(String(c.cab));
            const st = isSel ? COR.selecionada : full ? COR.completa : partial ? COR.parcial : COR.livre;
            return (
              <div key={key}
                onMouseEnter={() => setHovered(key)}
                onMouseLeave={() => setHovered(null)}
                onClick={(e) => { e.stopPropagation(); onSelCabin && onSelCabin(isSel ? null : key); }}
                onDragOver={dragging ? (e) => { e.preventDefault(); if (dropKey !== key) setDropKey(key); } : undefined}
                onDragLeave={() => { if (dropKey === key) setDropKey(null); }}
                onDrop={dragging ? (e) => {
                  e.preventDefault(); e.stopPropagation(); setDropKey(null);
                  // Com vaga livre, o pai atribui na primeira; cheia, abre a janelinha p/ resolver o swap
                  if (occ < tot) { onCabinDrop && onCabinDrop(c.vagas); }
                  else { onSelCabin && onSelCabin(key); }
                } : undefined}
                style={{
                  position:'absolute',
                  left:(x/lay.w*100)+'%', top:(y/lay.h*100)+'%',
                  width:(w/lay.w*100)+'%', height:(h/lay.h*100)+'%',
                  background: st.fill,
                  border:`2px solid ${st.borda}`,
                  borderRadius:4, cursor:'pointer',
                  boxShadow: isDrop ? '0 0 0 3px rgba(245,239,227,0.85)'
                    : isSel ? `0 0 0 3px ${COR.selecionada.borda}`
                    : isHl ? '0 0 0 3px rgba(232,180,83,0.9)'
                    : isHover ? '0 0 0 2px rgba(245,239,227,0.6)' : 'none',
                  zIndex: isSel || isDrop ? 4 : isHover || isHl ? 3 : 1,
                }}>
                <span style={{
                  position:'absolute',left:3,top:1,pointerEvents:'none',
                  fontFamily:'var(--fm)',fontSize:10,fontWeight:600,lineHeight:1.25,
                  color:'rgba(245,239,227,0.92)',textShadow:'0 1px 3px rgba(0,0,0,0.8)',
                }}>
                  {c.cab}{c.lado || ''}
                </span>
                {hasF && (
                  <span style={{
                    position:'absolute',right:3,top:3,width:7,height:7,borderRadius:'50%',
                    background:'#C36474',boxShadow:'0 0 0 1.5px rgba(31,42,46,0.65)',pointerEvents:'none',
                  }}/>
                )}
              </div>
            );
          })}

          {/* Janelinha da cabine selecionada — ancorada na cabine, com clamp pra não vazar do mapa */}
          {selCabin && (() => {
            const idx = parseInt(selCabin.split('-').pop(), 10);
            const c = lay.cabins[idx];
            if (!c) return null;
            const [x, y, w, h] = c.r;
            const berths = c.vagas.map(vid => vagasById[vid]).filter(Boolean);
            const tipo = berths[0] ? berths[0].cabinType : '';
            const xPct = x/lay.w*100, yPct = y/lay.h*100, wPct = w/lay.w*100;
            const goRight = (x + w/2) / lay.w < 0.5;   // cabine na metade esquerda → painel à direita dela
            const estH = pickBerth ? 380 : 64 + berths.length * 58;   // altura estimada p/ o clamp vertical
            const q = pickQ.toLowerCase();
            const poolList = (pool||[]).filter(u => !q || u.nome.toLowerCase().includes(q) || String(u.genesis_id||'').toLowerCase().includes(q) || (u.empresa||'').toLowerCase().includes(q));
            const pos = isMobile
              ? { left:6, right:6, top:`max(6px, min(calc(${yPct}%), calc(100% - ${estH}px)))` }
              : goRight
                ? { left:`calc(${xPct + wPct}% + 10px)`, top:`max(6px, min(calc(${yPct}%), calc(100% - ${estH}px)))` }
                : { left:`calc(${xPct}% - 290px)`,       top:`max(6px, min(calc(${yPct}%), calc(100% - ${estH}px)))` };
            return (
              <div onClick={e => e.stopPropagation()} style={{
                position:'absolute', ...pos, zIndex:12, lineHeight:'normal',
                width: isMobile ? 'auto' : 280,
                background:'#F5EFE3', color:'#1F2A2E',
                borderRadius:16, padding:'14px 16px',
                boxShadow:'0 18px 44px rgba(0,0,0,0.5)',
                border:'1px solid rgba(31,42,46,0.12)',
              }}>
                <div style={{display:'flex',alignItems:'baseline',justifyContent:'space-between',marginBottom:10}}>
                  <div style={{fontFamily:'var(--fs)',fontSize:20,fontWeight:500,letterSpacing:'-0.2px'}}>
                    Cab {c.cab}{c.lado ? ` · ${c.lado}` : ''} <em style={{fontStyle:'italic',color:'var(--muted)',fontSize:13,fontWeight:400}}>{tipo}</em>
                  </div>
                  <button onClick={() => onSelCabin && onSelCabin(null)}
                    style={{border:'none',background:'transparent',cursor:'pointer',fontSize:15,color:'var(--muted)',lineHeight:1,padding:4}}>✕</button>
                </div>
                {pickBerth ? (
                /* Seletor de pessoa p/ a vaga livre (clique na vaga) — drag-and-drop continua valendo */
                <div>
                  <div onClick={()=>{ setPickBerth(null); setPickQ(''); }}
                    style={{cursor:'pointer',fontFamily:'var(--fm)',fontSize:11.5,color:'var(--accent-2)',marginBottom:8,display:'flex',alignItems:'center',gap:6}}>
                    ‹ {lang==='pt'?'voltar':'back'} <span style={{color:'var(--muted)'}}>·</span> <span style={{color:'var(--ink)',fontWeight:600}}>Vaga {pickBerth.id}</span>
                  </div>
                  <input className="input" autoFocus value={pickQ} onChange={e=>setPickQ(e.target.value)}
                    placeholder={lang==='pt'?'buscar nome, ID ou empresa…':'search name, ID or company…'}
                    style={{marginBottom:8,width:'100%',boxSizing:'border-box'}}/>
                  <div className="cab-scroll" style={{maxHeight:240,overflowY:'auto',overflowX:'hidden',paddingRight:6,display:'flex',flexDirection:'column',gap:4}}>
                    {poolList.length ? poolList.map(u => {
                      const turno = u.turno && TURNOS[u.turno];
                      return (
                        <div key={u.id}
                          onClick={()=>{ onPick && onPick(u.id, pickBerth.id); setPickBerth(null); setPickQ(''); }}
                          onMouseEnter={e=>e.currentTarget.style.background='rgba(31,42,46,0.09)'}
                          onMouseLeave={e=>e.currentTarget.style.background='rgba(31,42,46,0.03)'}
                          style={{display:'flex',alignItems:'center',gap:9,padding:'7px 9px',borderRadius:12,cursor:'pointer',border:'1px solid rgba(31,42,46,0.1)',background:'rgba(31,42,46,0.03)'}}>
                          <Avatar user={u} size="sm"/>
                          <div style={{flex:1,minWidth:0}}>
                            <div style={{fontFamily:'var(--fm)',fontSize:12,fontWeight:600,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
                              {u.nome}{u.genero==='F' && <span style={{color:'#C36474'}}> ♀</span>}
                            </div>
                            <div style={{fontFamily:'var(--fm)',fontSize:10,color:'var(--muted)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
                              {[u.empresa, u.funcao].filter(Boolean).join(' · ')}
                            </div>
                          </div>
                          {turno && <span title={turno.label} style={{width:7,height:7,borderRadius:'50%',background:turno.color,flexShrink:0}}/>}
                        </div>
                      );
                    }) : (
                      <div style={{fontFamily:'var(--fm)',fontSize:11.5,color:'var(--muted)',fontStyle:'italic',padding:'10px 4px'}}>
                        {lang==='pt'?'ninguém a acomodar com essa busca':'nobody to assign for this search'}
                      </div>
                    )}
                  </div>
                </div>
                ) : (
                <div style={{display:'flex',flexDirection:'column',gap:6}}>
                  {berths.map(b => {
                    const u = b.user ? usersById[b.user] : null;
                    const t = u && u.turno && TURNOS[u.turno];
                    const vagaDrop = {
                      onDragOver: dragging ? (e) => { e.preventDefault(); e.stopPropagation(); } : undefined,
                      onDrop: dragging ? (e) => { e.preventDefault(); e.stopPropagation(); onVagaAction && onVagaAction(b); } : undefined,
                      onClick: (e) => { e.stopPropagation(); if (dragging) onVagaAction && onVagaAction(b); },
                    };
                    const vagaLivreClick = {
                      ...vagaDrop,
                      onClick: (e) => {
                        e.stopPropagation();
                        if (dragging) { onVagaAction && onVagaAction(b); }
                        else if (onPick) { setPickQ(''); setPickBerth(b); }   // clique abre o seletor de pessoa
                      },
                    };
                    return u ? (
                      <div key={b.id} {...vagaDrop} style={{
                        display:'flex',alignItems:'center',gap:9,padding:'7px 9px',borderRadius:12,
                        background:'rgba(31,42,46,0.05)',border:'1px solid rgba(31,42,46,0.1)',
                        cursor: dragging ? 'copy' : 'default',
                      }}>
                        <Avatar user={u} size="sm"/>
                        <div style={{flex:1,minWidth:0}}>
                          <div style={{fontFamily:'var(--fm)',fontSize:12,fontWeight:600,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
                            {u.nome}{u.genero==='F' && <span style={{color:'#C36474'}}> ♀</span>}
                          </div>
                          <div style={{fontFamily:'var(--fm)',fontSize:10,color:'var(--muted)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>
                            {[u.empresa, u.funcao].filter(Boolean).join(' · ')}
                          </div>
                        </div>
                        {t && <span title={t.label} style={{width:7,height:7,borderRadius:'50%',background:t.color,flexShrink:0}}/>}
                        <span style={{fontFamily:'var(--fm)',fontSize:9.5,color:'var(--muted)'}}>{b.id}</span>
                        {onHist && (
                          <button onClick={(e) => { e.stopPropagation(); onHist(b.id); }}
                            title={lang==='pt'?'histórico da vaga':'berth history'}
                            style={{border:'none',background:'transparent',cursor:'pointer',color:'var(--muted)',fontSize:12,lineHeight:1,padding:'2px 3px',flexShrink:0}}>🕘</button>
                        )}
                        {onUnassign && (
                          <button onClick={(e) => { e.stopPropagation(); onUnassign(u.id); }}
                            title={lang==='pt'?'tirar da vaga (volta para “A acomodar”)':'unassign (back to “To assign”)'}
                            style={{border:'none',background:'transparent',cursor:'pointer',color:'var(--rose)',fontSize:14,lineHeight:1,padding:'2px 3px',flexShrink:0}}>✕</button>
                        )}
                      </div>
                    ) : (
                      <div key={b.id} {...vagaLivreClick} style={{
                        display:'flex',alignItems:'center',gap:9,padding:'9px 10px',borderRadius:12,
                        border:`1.5px dashed ${COR.livre.borda}`,background:'rgba(123,182,126,0.12)',
                        fontFamily:'var(--fm)',fontSize:11,color:'var(--muted)',
                        cursor: dragging ? 'copy' : (onPick ? 'pointer' : 'default'),
                      }}>
                        <span style={{width:28,height:28,borderRadius:9,border:`1.5px dashed ${COR.livre.borda}`,display:'inline-block',flexShrink:0}}/>
                        <span style={{flex:1,fontStyle:'italic'}}>
                          {lang==='pt'?'livre':'free'}{dragging ? (lang==='pt'?' — solte para atribuir':' — drop to assign') : (onPick ? (lang==='pt'?' — clique p/ escolher':' — click to pick') : '')}
                        </span>
                        <span style={{fontSize:9.5}}>{b.id}</span>
                      </div>
                    );
                  })}
                </div>
                )}
              </div>
            );
          })()}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { DeckPlan });
