// building.jsx
// Renders the SimTower-style cutaway of Gumbo HQ.
// Floors stacked top-to-bottom, central elevator shaft, agents walking,
// substrate basement floors with flowing packet dots.

const ACCENT = {
  blue:    { stripe: '#2563eb', glow: '#60a5fa', tile: '#dbeafe' },
  cayenne: { stripe: '#d65c73', glow: '#df7e8f', tile: '#fce4e8' },
  pine:    { stripe: '#38573e', glow: '#6b8f71', tile: '#e0ebe2' },
  okra:    { stripe: '#6a9d62', glow: '#87b482', tile: '#e6f0e4' },
  orange:  { stripe: '#f97316', glow: '#fb923c', tile: '#ffedd5' },
};

// ---- helpers ----
function tilePx(n) { return n * window.TILE; }

// Sprite — a chunky 2-tile-tall pixel-y figure, drawn with stacked divs.
function Sprite({ agent, walking }) {
  const isHuman = agent.type === 'human';
  const a = ACCENT[agent.color] || ACCENT.blue;
  const skin = isHuman ? '#e8c39e' : '#cbd5e1';
  const shirt = a.stripe;
  const head = isHuman ? skin : a.glow;
  const bob = walking ? (Math.floor(agent.step / 4) % 2) : 0;

  return (
    <div className="sprite" style={{
      transform: `translateY(${bob ? -1 : 0}px)`,
    }}>
      {/* halo for agents */}
      {!isHuman && (
        <div className="sprite-halo" style={{ background: a.glow }}/>
      )}
      {/* head */}
      <div className="sprite-head" style={{ background: head, border: `1px solid ${isHuman ? '#92703f' : a.stripe}` }}>
        {!isHuman && <div className="sprite-eye"/>}
      </div>
      {/* body */}
      <div className="sprite-body" style={{ background: shirt }}>
        {isHuman && <div className="sprite-belt"/>}
        {!isHuman && <div className="sprite-led" style={{ background: '#fff' }}/>}
      </div>
      {/* legs */}
      <div className="sprite-legs">
        <div style={{ background: isHuman ? '#1e3a8a' : a.stripe, transform: `translateY(${bob ? 0 : -1}px)` }}/>
        <div style={{ background: isHuman ? '#1e3a8a' : a.stripe, transform: `translateY(${bob ? -1 : 0}px)` }}/>
      </div>
    </div>
  );
}

// Workstation — a desk/console at a station x. Color hints at floor accent.
function Workstation({ x, accent, kind }) {
  const a = ACCENT[accent] || ACCENT.blue;
  return (
    <div className="ws" style={{ left: tilePx(x) - 10 }}>
      <div className="ws-monitor" style={{ background: a.stripe, boxShadow: `0 0 4px ${a.glow}` }}>
        <div className="ws-screen"/>
      </div>
      <div className="ws-desk"/>
    </div>
  );
}

// One floor row.
function FloorRow({ floor, idx, agents, packets, onClickAgent, onClickFloor, selectedId, selectedFloorIdx, time }) {
  const W = window.FLOOR_W, H = window.FLOOR_H, TILE = window.TILE;
  const a = ACCENT[floor.accent] || ACCENT.blue;
  const isSub = floor.kind === 'sub';
  const isLobby = floor.kind === 'lobby';
  const isRoof = floor.kind === 'roof';

  if (isRoof) {
    return (
      <div className={`floor floor-roof ${selectedFloorIdx === idx ? 'floor-selected' : ''}`}
           onClick={() => onClickFloor(idx)}
           style={{ width: W * TILE, height: H * TILE * 0.85 }}>
        {/* roof trim */}
        <div className="roof-trim"/>
        <div className="roof-sign">
          <div className="roof-sign-glow"/>
          <img className="roof-sign-logo" src="assets/wordmark-white.svg" alt="Gumbo"/>
        </div>
        {/* antenna */}
        <div className="antenna">
          <div className="antenna-pole"/>
          <div className="antenna-blink"/>
        </div>
      </div>
    );
  }

  const dim = time === 'night';
  const floorAgents = agents.filter(ag => ag.floor === idx && ag.state !== 'in-elev');

  return (
    <div className={`floor ${isSub ? 'floor-sub' : ''} ${isLobby ? 'floor-lobby' : ''} ${selectedFloorIdx === idx ? 'floor-selected' : ''}`}
         onClick={() => onClickFloor(idx)}
         style={{ width: W * TILE, height: H * TILE, background: isSub ? '#0a1628' : (dim ? '#1e293b' : '#fafaf7') }}>

      {/* Left label gutter */}
      <div className="floor-label">
        <div className="floor-code">{floor.code}</div>
        <div className="floor-name">{floor.label}</div>
      </div>

      {/* Floor accent stripe */}
      <div className="floor-stripe" style={{ background: a.stripe }}/>

      {/* Window grid behind interior (for non-sub) */}
      {!isSub && (
        <div className="floor-windows">
          {Array.from({ length: 14 }).map((_, i) => {
            // Keep the night skyline calm and stable. This used to call
            // Math.random() during render, so every simulation tick reshuffled
            // the lights across every floor — visually brutal in night mode.
            const litAtNight = ((idx * 17 + i * 11) % 10) < 7;
            return (
              <div key={i} className="window-tile" style={{
                background: dim ? (litAtNight ? a.glow : '#0f172a') : '#dde7f0',
                opacity: dim ? (litAtNight ? 0.38 : 0.28) : 0.5,
              }}/>
            );
          })}
        </div>
      )}

      {/* Substrate floors render as pipes/circuits */}
      {isSub && (
        <SubstrateRow floor={floor} idx={idx} packets={packets} accent={a}/>
      )}

      {/* Workstations (only for room/lobby) */}
      {!isSub && floor.stations.map((sx, i) => (
        <Workstation key={i} x={sx} accent={floor.accent} kind={floor.dept}/>
      ))}

      {/* Elevator shaft cutout — floor floor across, but a darker rectangle */}
      <div className="elev-cutout" style={{
        left: tilePx(window.ELEV_X),
        width: tilePx(window.ELEV_W),
      }}/>

      {/* Agents on this floor */}
      {floorAgents.map(ag => {
        const isWorking = ag.state === 'work' && ag.activity === 'working';
        const isIdle = ag.state === 'idle';
        const walking = ag.state === 'walk' || ag.activity === 'strolling';
        return (
        <div key={ag.id}
             onClick={(e) => { e.stopPropagation(); onClickAgent(ag.id); }}
             className={`agent-wrap ${selectedId === ag.id ? 'selected' : ''} state-${ag.state} activity-${ag.activity || 'working'} ${isWorking ? 'is-working' : ''} ${isIdle ? 'is-idle' : ''}`}
             title={`${ag.name} · ${isWorking ? 'working' : (ag.activity || ag.state)}`}
             style={{
               left: tilePx(ag.x) - 5,
               bottom: ag.activity === 'lounging' ? 2 : 4,
             }}>
          {isIdle && <div className="idle-mat"/>}
          <Sprite agent={ag} walking={walking}/>
          {isWorking && <div className="work-sparks"><i/><i/><i/></div>}
          {isIdle && <div className="idle-label">{ag.activity}</div>}
          {selectedId === ag.id && <div className="select-ring"/>}
        </div>
        );
      })}

      {/* Lobby: doors */}
      {isLobby && (
        <>
          <div className="lobby-door" style={{ left: 8 }}/>
          <div className="lobby-door" style={{ right: 8 }}/>
          <div className="lobby-floor-line"/>
        </>
      )}
    </div>
  );
}

// Substrate row visualization: pipes + flowing packets.
function SubstrateRow({ floor, idx, packets, accent }) {
  const TILE = window.TILE;
  const W = window.FLOOR_W;
  const myPackets = packets.filter(p => p.floor === idx);
  return (
    <>
      {/* circuit grid */}
      <div className="sub-grid"/>
      {/* pipe lines */}
      <div className="sub-pipe" style={{ top: '38%', background: accent.stripe }}/>
      <div className="sub-pipe" style={{ top: '62%', background: accent.glow }}/>
      {/* nodes */}
      {[6, 14, 22, 30].map((x, i) => (
        <div key={i} className="sub-node" style={{ left: tilePx(x) - 4, top: '32%' }}/>
      ))}
      {[10, 18, 26, 34].map((x, i) => (
        <div key={i} className="sub-node" style={{ left: tilePx(x) - 4, top: '56%' }}/>
      ))}
      {/* flowing packets */}
      {myPackets.map(p => {
        const c = ACCENT[p.color] || ACCENT.blue;
        return (
          <div key={p.id} className="packet" style={{
            left: tilePx(p.x),
            top: p.id % 2 ? '38%' : '62%',
            background: c.stripe,
            boxShadow: `0 0 6px ${c.glow}`,
          }}/>
        );
      })}
      {/* code label */}
      <div className="sub-readout">
        {floor.id === 'bus'      && '> bus.publish("agent.task.complete")  ⏎'}
        {floor.id === 'memory'   && '> memory.write({entity:"PR#482", v:7})  ⏎'}
        {floor.id === 'skills'   && '> skills.equip("git.review", agent:"Roux-7")  ⏎'}
        {floor.id === 'identity' && '> identity.verify(actor:"Praline", scope:"crm.write")  ⏎'}
      </div>
    </>
  );
}

// Elevator car, rendered absolutely positioned over the building.
function ElevatorCar({ elevator, floors, agents }) {
  const TILE = window.TILE;
  // Find pixel y of elevator floor (top of that floor row in building).
  // We'll let parent compute floor offsets and pass a yMap.
  return null; // rendered inside Building with positioning context
}

// Main building component
function Building({ agents, elevator, packets, selectedId, selectedFloorIdx, selectedElevator, onClickAgent, onClickFloor, onClickElevator, showBeam, time }) {
  const TILE = window.TILE, W = window.FLOOR_W, H = window.FLOOR_H;

  // Compute heights & y offsets for each floor row.
  const heights = window.FLOORS.map(f => {
    if (f.kind === 'roof') return H * TILE * 0.85;
    return H * TILE;
  });
  const yOffsets = [];
  let y = 0;
  for (const h of heights) { yOffsets.push(y); y += h; }
  const totalH = y;

  // Elevator car y: top of its floor row, bottom-aligned to that floor
  const elevFloorIdx = elevator.floor;
  const elevY = yOffsets[elevFloorIdx];
  const elevH = H * TILE;
  const passengerAgents = agents.filter(a => elevator.passengers.has(a.id));

  return (
    <div className="building" style={{ width: W * TILE + 80, height: totalH + 30 }}>
      {showBeam && <div className="roof-beam" aria-hidden="true"/>}
      {/* Building exterior shadow strip */}
      <div className="building-side-l"/>
      <div className="building-side-r"/>

      {/* Floor stack */}
      <div className="floor-stack">
        {window.FLOORS.map((f, i) => (
          <FloorRow key={f.id}
                    floor={f} idx={i}
                    agents={agents}
                    packets={packets}
                    onClickAgent={onClickAgent}
                    onClickFloor={onClickFloor}
                    selectedId={selectedId}
                    selectedFloorIdx={selectedFloorIdx}
                    time={time}/>
        ))}
      </div>

      {/* Elevator shaft (full height behind floors)  */}
      <div className={`elev-shaft ${selectedElevator ? 'selected' : ''}`} onClick={(e) => { e.stopPropagation(); onClickElevator(); }} style={{
        left: tilePx(window.ELEV_X) + 80,   // +80 for left gutter
        width: tilePx(window.ELEV_W),
        top: heights[0],                     // skip roof
        height: totalH - heights[0] - 12,
      }}>
        {/* Cable */}
        <div className="elev-cable"/>
        {/* Floor markers along shaft */}
        {window.FLOORS.map((f, i) => {
          if (f.kind === 'roof') return null;
          return (
            <div key={i} className="elev-marker" style={{
              top: yOffsets[i] - heights[0] + (H * TILE) - 8,
            }}/>
          );
        })}
      </div>

      {/* Elevator car */}
      <div className={`elev-car ${selectedElevator ? 'selected' : ''}`} onClick={(e) => { e.stopPropagation(); onClickElevator(); }} style={{
        left: tilePx(window.ELEV_X) + 80 + 2,
        width: tilePx(window.ELEV_W) - 4,
        top: elevY + (elevH - elevH * 0.85),
        height: elevH * 0.85 - 6,
      }}>
        <div className="elev-car-led"/>
        {/* Passengers in elevator (mini sprites) */}
        <div className="elev-passengers">
          {passengerAgents.slice(0, 4).map(a => (
            <div key={a.id} className="elev-pass" onClick={(e) => { e.stopPropagation(); onClickAgent(a.id); }}>
              <Sprite agent={a} walking={false}/>
            </div>
          ))}
        </div>
      </div>

      {/* Sidewalk strip */}
      <div className="sidewalk" style={{ top: totalH }}/>
      {/* Sky scanlines (decorative — sit on top of everything but pointer-events none) */}
    </div>
  );
}

Object.assign(window, { Building, Sprite, ACCENT });
