// ═══ GENESIS ═══
// Tidal — Cabines: planta baixa interativa (vista de topo) sobre as imagens mapeadas em deck-layouts.js.
// Cada retângulo de cabine é colorido pelo status das vagas (verde=cheia, âmbar=parcial, tracejado=livre).
// Clique numa cabine filtra o deck e rola até os cards; os botões de deck alternam o mapa e o filtro.

const DeckPlan = ({vagas, usersById, filterDeck, setFilterDeck, onOpenFilter, filtroAtivo, lang}) => {
  const L = window.DECK_LAYOUTS;
  const isMobile = useMobile();
  const [hovered, setHovered] = useState(null);   // chave do retângulo em hover
  const deckIds = (L ? ['9','8','7','6'].filter(d => L[d]) : []);
  const [mapDeck, setMapDeck] = useState(deckIds[0] || null);

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

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

  if (!L || !deckIds.length) {
    return (
      <div style={{
        background:'linear-gradient(180deg, #1F2A2E 0%, #2A363A 100%)',
        borderRadius:24, padding:'22px 26px', marginBottom:24, color:'#F5EFE3',
      }}>
        <div style={{fontFamily:'var(--fm)',fontSize:10,letterSpacing:2,textTransform:'uppercase',color:'rgba(245,239,227,0.5)'}}>
          {lang==='pt'?'planta baixa · Genesis I':'floor plan · Genesis I'}
        </div>
        <div style={{fontFamily:'var(--fm)',fontSize:12,marginTop:8,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>
    );
  }

  const deckLabels = lang==='pt'
    ? {9:'residencial',8:'tripulação',7:'misto',6:'operações'}
    : {9:'residential',8:'crew',7:'mixed',6:'operations'};

  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 scrollToDeck = (d) => {
    const el = document.getElementById('deck-sec-'+d);
    if (el) el.scrollIntoView({behavior:'smooth', block:'start'});
  };

  return (
    <div style={{
      background:'linear-gradient(180deg, #1F2A2E 0%, #2A363A 100%)',
      borderRadius:24, padding:'22px 26px 18px', marginBottom:24,
      color:'#F5EFE3', position:'relative', overflow:'hidden',
    }}>
      {/* eyebrow + título + legenda */}
      <div style={{display:'flex',alignItems:'baseline',justifyContent:'space-between',marginBottom: isMobile ? 12 : 16,flexWrap:'wrap',gap: isMobile ? 10 : 8}}>
        <div>
          <div style={{fontFamily:'var(--fm)',fontSize: isMobile ? 9 : 10,letterSpacing:2,textTransform:'uppercase',color:'rgba(245,239,227,0.5)'}}>
            {lang==='pt'?'planta baixa · Genesis I':'floor plan · Genesis I'}
          </div>
          <div style={{fontFamily:'var(--fs)',fontSize: isMobile ? 20 : 24,letterSpacing:'-0.4px',marginTop:2}}>
            {lang==='pt'?'vista de topo':'top view'} <em style={{fontStyle:'italic',color:'#E8B453'}}>•</em>
            {!isMobile && (
              <span style={{fontFamily:'var(--fm)',fontSize:11,letterSpacing:1.5,textTransform:'uppercase',color:'rgba(245,239,227,0.5)',marginLeft:10}}>
                {lang==='pt'?'clique numa cabine para filtrar':'click a cabin to filter'}
              </span>
            )}
          </div>
        </div>
        <div style={{display:'flex',gap: isMobile ? 10 : 14,fontFamily:'var(--fm)',fontSize: isMobile ? 9.5 : 10.5,letterSpacing:0.5,alignItems:'center',flexWrap:'wrap'}}>
          <LegendDot c="#7BB67E" l={isMobile ? '' : (lang==='pt'?'ocupada':'occupied')}/>
          <LegendDot c="#E8B453" l={isMobile ? '' : (lang==='pt'?'parcial':'partial')}/>
          <LegendDot c="rgba(245,239,227,0.18)" l={isMobile ? '' : (lang==='pt'?'livre':'free')} ring/>
          <LegendDot c="#C36474" l="♀"/>
        </div>
      </div>

      {onOpenFilter && (
        <div style={{marginBottom:14}}>
          <button onClick={onOpenFilter} style={{position:'relative',display:'inline-flex',alignItems:'center',gap:7,padding:'8px 15px',borderRadius:10,cursor:'pointer',fontFamily:'var(--fm)',fontSize:12,fontWeight:600,color:'var(--cream)',background:'rgba(251,247,240,0.1)',border:'1px solid rgba(251,247,240,0.25)'}}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--cream)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M3 5h18l-7 8v6l-4 2v-8z"/></svg>
            {lang==='pt'?'Filtrar cabines':'Filter cabins'}
            {filtroAtivo && <span style={{position:'absolute',top:-3,right:-3,width:10,height:10,borderRadius:'50%',background:'var(--sun)',border:'2px solid #17403E'}}/>}
          </button>
        </div>
      )}

      {/* Seletor de decks */}
      <div style={{display:'flex',gap:8,flexWrap:'wrap',marginBottom:14}}>
        {deckIds.map(d => {
          const {occ, tot} = deckStats(d);
          const active = mapDeck === d;
          return (
            <button key={d}
              onClick={() => { setMapDeck(d); setFilterDeck(filterDeck === d ? 'all' : d); }}
              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 ? 16 : 18,fontWeight:500,lineHeight:1}}>D{d}</span>
              <span style={{fontFamily:'var(--fm)',fontSize:8.5,letterSpacing:1.1,textTransform:'uppercase',color:'rgba(245,239,227,0.5)'}}>{deckLabels[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>

      {/* Imagem do deck + retângulos das cabines */}
      <div style={{position:'relative'}}>
        <div style={{position:'relative',borderRadius:14,overflow:'hidden',border:'1px solid rgba(245,239,227,0.12)',lineHeight:0}}>
          <img src={lay.img} alt={`Deck ${mapDeck}`} draggable={false}
            style={{display:'block',width:'100%',height:'auto',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 = mapDeck + '-' + c.cab + (c.lado || '') + '-' + i;
            const isHover = hovered === key;
            return (
              <div key={key}
                onMouseEnter={() => setHovered(key)}
                onMouseLeave={() => setHovered(null)}
                onClick={() => { if (filterDeck !== mapDeck) setFilterDeck(mapDeck); setTimeout(() => scrollToDeck(mapDeck), 80); }}
                style={{
                  position:'absolute',
                  left:(x/lay.w*100)+'%', top:(y/lay.h*100)+'%',
                  width:(w/lay.w*100)+'%', height:(h/lay.h*100)+'%',
                  background: full ? 'rgba(123,182,126,0.45)' : partial ? 'rgba(232,180,83,0.45)' : 'rgba(245,239,227,0.04)',
                  border: full ? '2px solid #7BB67E' : partial ? '2px solid #E8B453' : '1.5px dashed rgba(245,239,227,0.4)',
                  borderRadius:4, cursor:'pointer',
                  boxShadow: isHover ? '0 0 0 2px rgba(245,239,227,0.6)' : 'none',
                  zIndex: isHover ? 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>
            );
          })}
        </div>

        {/* Tooltip da cabine em hover */}
        {hovered && (() => {
          const idx = parseInt(hovered.split('-').pop(), 10);
          const c = lay.cabins[idx];
          if (!c) return null;
          const first = vagasById[c.vagas[0]];
          return (
            <div style={{
              position:'absolute', top:8, right:8,
              background:'#F5EFE3', color:'#1F2A2E',
              padding:'10px 14px', borderRadius:12, boxShadow:'0 10px 30px rgba(0,0,0,0.4)',
              minWidth:200, pointerEvents:'none', zIndex:10,
              border:'1px solid rgba(31,42,46,0.1)',
            }}>
              <div style={{fontFamily:'var(--fs)',fontSize:18,fontWeight:500,letterSpacing:'-0.2px'}}>
                Cab {c.cab}{c.lado ? ` · ${c.lado}` : ''} <em style={{fontStyle:'italic',color:'var(--muted)',fontSize:13,fontWeight:400}}>{first ? first.cabinType : ''}</em>
              </div>
              <div style={{marginTop:6,display:'flex',flexDirection:'column',gap:3}}>
                {c.vagas.map(vid => {
                  const b = vagasById[vid];
                  const u = b && b.user ? usersById[b.user] : null;
                  const t = u && u.turno && TURNOS[u.turno];
                  return (
                    <div key={vid} style={{display:'flex',alignItems:'center',gap:6,fontSize:11.5,fontFamily:'var(--fm)'}}>
                      <span style={{color:'var(--muted)',fontSize:10}}>{vid}</span>
                      <span style={{flex:1,color: u?'inherit':'var(--muted-2)',fontStyle: u?'normal':'italic'}}>
                        {u ? u.nome : (lang==='pt'?'livre':'free')}
                      </span>
                      {u && u.genero==='F' && <span style={{color:'#C36474'}}>♀</span>}
                      {t && <span style={{width:6,height:6,borderRadius:'50%',background:t.color}}/>}
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })()}
      </div>
    </div>
  );
};

Object.assign(window, { DeckPlan });
