// Estetic Hall — планы зала (top-down).
// mode='hall'  — общий зал: 7 парикмахеров (синие столы) + 2 визажиста.
// mode='nails' — отдельная комната: маникюр (5) + педикюр (2).
// readonly + bookedRoomIds — режим «карта забронированных мест» для админ-дашборда.

const FloorPlan = ({ rooms, onSelect, hovered, setHovered, mode = 'hall', readonly = false, bookedRoomIds = null }) => {
  const occupied = bookedRoomIds ? new Set(bookedRoomIds.map(Number)) : null;
  const colorFor = (st) => st === 'free' ? '#5d8a72' : st === 'partial' ? '#c9913d' : '#b56666';
  const statusColorOf = (room) => occupied
    ? (occupied.has(Number(room.id)) ? '#b56666' : '#5d8a72')
    : colorFor(room.status);

  const byZone = (z) => rooms.filter(r => r.zone === z);
  const hair = byZone('hair'), nails = byZone('nails'), makeup = byZone('makeup'), ped = byZone('pedicure');

  const noop = () => {};
  const select = readonly ? noop : (onSelect || noop);
  const setHov = readonly ? noop : (setHovered || noop);

  // ====== Ячейка-место ======
  // blueTable=true → столы парикмахеров синие. В readonly-режиме заливка показывает занятость.
  const Cell = ({ room, x, y, w, h, wall, blueTable }) => {
    if (!room) return null;
    const isH = !readonly && hovered === room.id;
    const stColor = statusColorOf(room);

    let mirror, chairCx, chairCy, numX, numY;
    if (wall === 'top') {
      mirror = { x: x + 4, y: y - 3, w: w - 8, h: 4 };
      chairCx = x + w / 2; chairCy = y + h + 14;
      numX = x + w / 2; numY = y + h / 2 + 5;
    } else if (wall === 'bot') {
      mirror = { x: x + 4, y: y + h - 1, w: w - 8, h: 4 };
      chairCx = x + w / 2; chairCy = y - 14;
      numX = x + w / 2; numY = y + h / 2 + 5;
    } else if (wall === 'right') {
      mirror = { x: x + w - 1, y: y + 4, w: 4, h: h - 8 };
      chairCx = x - 14; chairCy = y + h / 2;
      numX = x + w / 2; numY = y + h / 2 + 5;
    } else { // left
      mirror = { x: x - 3, y: y + 4, w: 4, h: h - 8 };
      chairCx = x + w + 14; chairCy = y + h / 2;
      numX = x + w / 2; numY = y + h / 2 + 5;
    }

    // Заливка стола
    let tableFill = '#cba374', tableStroke = '#7a5a30', numColor = '#0f1419', tableOpacity = 0.92;
    if (readonly) {
      tableFill = stColor; tableOpacity = 0.5; tableStroke = stColor; numColor = '#0f1419';
    } else if (isH) {
      tableFill = stColor; tableOpacity = 0.55; tableStroke = stColor; numColor = '#ffffff';
    } else if (blueTable) {
      tableFill = '#066aab'; tableOpacity = 0.9; tableStroke = '#044270'; numColor = '#ffffff';
    }

    return (
      <g onMouseEnter={() => setHov(room.id)} onMouseLeave={() => setHov(null)}
         onClick={() => select(room)} style={{ cursor: readonly ? 'default' : 'pointer' }}>
        <rect x={x} y={y} width={w} height={h} rx="2"
              fill={tableFill} fillOpacity={tableOpacity}
              stroke={tableStroke} strokeWidth="0.7" />
        {(wall === 'top' || wall === 'bot') && (
          <rect x={x + 3} y={wall === 'top' ? y + 4 : y + 2} width={w - 6} height="4" fill="rgba(255,255,255,0.45)" />
        )}
        {(wall === 'left' || wall === 'right') && (
          <rect x={wall === 'left' ? x + 4 : x + w - 8} y={y + 3} width="4" height={h - 6} fill="rgba(255,255,255,0.45)" />
        )}
        <rect x={mirror.x} y={mirror.y} width={mirror.w} height={mirror.h} fill="#1a1f2d" opacity="0.82" />
        <circle cx={chairCx} cy={chairCy} r="9" fill="#066aab" opacity="0.78" />
        <circle cx={chairCx} cy={chairCy} r="5.5" fill="#066aab" />
        <text x={numX} y={numY} textAnchor="middle"
              fontFamily="Cardo" fontStyle="italic" fontSize="14"
              fill={numColor} fontWeight="500">{room.num}</text>
        <circle cx={x + w - 6} cy={y + 6} r="2.4" fill={stColor} stroke="#ffffff" strokeWidth="0.6" />
      </g>
    );
  };

  const tilePattern = (
    <defs>
      <pattern id="floor-tile" x="0" y="0" width="56" height="56" patternUnits="userSpaceOnUse">
        <rect width="56" height="56" fill="#f3f5f8" />
        <line x1="56" y1="0" x2="56" y2="56" stroke="rgba(15,20,25,0.07)" strokeWidth="0.6" />
        <line x1="0" y1="56" x2="56" y2="56" stroke="rgba(15,20,25,0.07)" strokeWidth="0.6" />
        <line x1="56" y1="0" x2="56" y2="56" stroke="rgba(255,255,255,0.5)" strokeWidth="0.5" transform="translate(-0.4 0)" />
      </pattern>
    </defs>
  );

  const hoverHint = (x, y) => {
    if (readonly) return null;
    const room = hovered ? rooms.find(r => r.id === hovered) : null;
    return (
      <text x={x} y={y} textAnchor="end" fontFamily="Inter" fontSize="9.5"
            fill={room ? '#0f1419' : '#6e7682'} fontWeight={room ? 600 : 400}>
        {room
          ? `${room.num} · ${room.name} · от ${room.prices.hour}₽/ч`
          : 'Наведите на место · кликните, чтобы забронировать'}
      </text>
    );
  };

  // ============================================================
  // ПЛАН 2 — Маникюр + Педикюр (отдельная комната)
  // ============================================================
  if (mode === 'nails') {
    const pedPos = [
      { x: 70, y: 78, w: 130, h: 58, wall: 'top' },
      { x: 250, y: 78, w: 130, h: 58, wall: 'top' },
    ];
    const manicurePos = [
      { x: 50, y: 300, w: 120, h: 52, wall: 'left' },
      { x: 50, y: 420, w: 120, h: 52, wall: 'left' },
      { x: 280, y: 280, w: 120, h: 50, wall: 'right' },
      { x: 280, y: 392, w: 120, h: 50, wall: 'right' },
      { x: 280, y: 504, w: 120, h: 50, wall: 'right' },
    ];
    return (
      <svg viewBox="0 0 450 640" style={{ width: '100%', height: '100%', display: 'block' }} xmlns="http://www.w3.org/2000/svg">
        {tilePattern}
        {/* Комната педикюра (верх) */}
        <rect x="24" y="24" width="402" height="190" fill="url(#floor-tile)" stroke="#0f1419" strokeWidth="2.4" />
        {/* Комната маникюра (низ) */}
        <rect x="24" y="244" width="402" height="372" fill="url(#floor-tile)" stroke="#0f1419" strokeWidth="2.4" />
        <rect x="28" y="28" width="394" height="182" fill="#066aab" opacity="0.03" rx="2" />
        <rect x="28" y="248" width="394" height="364" fill="#066aab" opacity="0.03" rx="2" />

        {ped.slice(0, 2).map((r, i) => pedPos[i] && <Cell key={r.id} room={r} {...pedPos[i]} />)}
        {nails.slice(0, 5).map((r, i) => manicurePos[i] && <Cell key={r.id} room={r} {...manicurePos[i]} />)}

        <text x="225" y="56" textAnchor="middle" fontFamily="Cardo" fontStyle="italic" fontSize="15" fill="#066aab">Педикюр</text>
        <text x="225" y="71" textAnchor="middle" fontFamily="Inter" fontSize="8" letterSpacing="2" fill="#6e7682">2 МЕСТА</text>
        <text x="225" y="272" textAnchor="middle" fontFamily="Cardo" fontStyle="italic" fontSize="15" fill="#066aab">Маникюр</text>
        <text x="225" y="287" textAnchor="middle" fontFamily="Inter" fontSize="8" letterSpacing="2" fill="#6e7682">5 МЕСТ</text>
        {hoverHint(424, 632)}
      </svg>
    );
  }

  // ============================================================
  // ПЛАН 1 — Общий зал: 7 парикмахеров (синие) + 2 визажиста
  // ============================================================
  const hairTopPos = Array.from({ length: 4 }, (_, i) => ({ x: 210 + i * 116, y: 86, w: 88, h: 48, wall: 'top' }));
  const hairBotPos = Array.from({ length: 3 }, (_, i) => ({ x: 340 + i * 108, y: 566, w: 84, h: 46, wall: 'bot' }));
  const makeupPos = [
    { x: 46, y: 300, w: 104, h: 62, wall: 'left' },
    { x: 46, y: 380, w: 104, h: 62, wall: 'left' },
  ];

  return (
    <svg viewBox="0 0 740 700" style={{ width: '100%', height: '100%', display: 'block' }} xmlns="http://www.w3.org/2000/svg">
      {tilePattern}

      {/* ===== Общий зал ===== */}
      <rect x="44" y="70" width="664" height="560" fill="url(#floor-tile)" stroke="#0f1419" strokeWidth="2.4" />

      {/* ===== Подложки зон ===== */}
      <rect x="184" y="78" width="470" height="78" fill="#066aab" opacity="0.03" rx="2" />
      <rect x="320" y="548" width="340" height="74" fill="#066aab" opacity="0.03" rx="2" />
      <rect x="42" y="292" width="132" height="158" fill="#066aab" opacity="0.035" rx="2" />

      {/* ===== Ресепшн — L-стойка в левом верхнем углу (коричневая) ===== */}
      <g>
        <path d="M 46 84 L 168 84 L 168 150 L 108 150 L 108 250 L 46 250 Z" fill="#a67c52" />
        <path d="M 46 84 L 168 84 L 168 150 L 108 150 L 108 250 L 46 250 Z" fill="none" stroke="#7a5a30" strokeWidth="0.6" />
        <rect x="62" y="98" width="34" height="22" rx="2" fill="rgba(255,255,255,0.2)" />
        <line x1="79" y1="120" x2="79" y2="124" stroke="rgba(255,255,255,0.45)" strokeWidth="1.6" />
        <circle cx="74" cy="206" r="9" fill="#7a5a30" opacity="0.6" />
        <circle cx="74" cy="206" r="5.5" fill="#7a5a30" />
        <text x="78" y="130" textAnchor="middle" fontFamily="Cardo" fontStyle="italic" fontSize="13" fill="#ffffff" transform="rotate(-90 78 130)">Ресепшн</text>
      </g>

      {/* ===== 2 кресла-мойки — у правой стены ===== */}
      <g>
        <rect x="672" y="400" width="34" height="120" rx="3" fill="#ffffff" stroke="#066aab" strokeWidth="0.9" />
        {[435, 490].map((cy, i) => (
          <g key={i}>
            <ellipse cx="685" cy={cy} rx="13" ry="9" fill="#0f1419" opacity="0.8" />
            <rect x="698" y={cy - 2} width="6" height="4" fill="#6e7682" />
          </g>
        ))}
        <text x="660" y="462" textAnchor="middle" transform="rotate(-90 660 462)" fontFamily="Cardo" fontStyle="italic" fontSize="11" fill="#6e7682">2 кресла-мойки</text>
      </g>

      {/* ===== Места ===== */}
      {hair.slice(0, 4).map((r, i) => hairTopPos[i] && <Cell key={r.id} room={r} blueTable {...hairTopPos[i]} />)}
      {hair.slice(4, 7).map((r, i) => hairBotPos[i] && <Cell key={r.id} room={r} blueTable {...hairBotPos[i]} />)}
      {makeup.map((r, i) => makeupPos[i] && <Cell key={r.id} room={r} {...makeupPos[i]} />)}

      {/* ===== Разделительный столб между П6 и П7 ===== */}
      <g>
        <rect x="537" y="556" width="15" height="62" fill="#3a4250" stroke="#0f1419" strokeWidth="1.2" />
        <line x1="537" y1="556" x2="552" y2="618" stroke="#0f1419" strokeWidth="0.6" opacity="0.45" />
        <line x1="552" y1="556" x2="537" y2="618" stroke="#0f1419" strokeWidth="0.6" opacity="0.45" />
      </g>

      {/* ===== Раковина в углу возле П7 ===== */}
      <g>
        <rect x="650" y="576" width="46" height="34" rx="4" fill="#ffffff" stroke="#066aab" strokeWidth="0.9" />
        <ellipse cx="673" cy="593" rx="14" ry="9" fill="#0f1419" opacity="0.8" />
        <rect x="671" y="578" width="4" height="6" fill="#6e7682" />
        <text x="673" y="620" textAnchor="middle" fontFamily="Cardo" fontStyle="italic" fontSize="9" fill="#6e7682">раковина</text>
      </g>

      {/* ===== ФОТОЗОНА — нижний левый угол ===== */}
      <g>
        <path d="M 184 558 L 184 548 L 196 548" fill="none" stroke="#066aab" strokeWidth="1.4" strokeLinecap="round" />
        <path d="M 304 548 L 316 548 L 316 558" fill="none" stroke="#066aab" strokeWidth="1.4" strokeLinecap="round" />
        <path d="M 184 612 L 184 622 L 196 622" fill="none" stroke="#066aab" strokeWidth="1.4" strokeLinecap="round" />
        <path d="M 304 622 L 316 622 L 316 612" fill="none" stroke="#066aab" strokeWidth="1.4" strokeLinecap="round" />
        <rect x="184" y="548" width="132" height="74" fill="#066aab" opacity="0.04" />
        <text x="250" y="582" textAnchor="middle" fontFamily="Cardo" fontStyle="italic" fontSize="17" fill="#066aab">Фотозона</text>
        <text x="250" y="597" textAnchor="middle" fontFamily="Inter" fontSize="6.8" letterSpacing="1.8" fill="#6e7682">КОНТЕНТ · СЪЁМКА</text>
      </g>

      {/* ===== Вход — нижний левый угол ===== */}
      <g>
        <rect x="62" y="626" width="56" height="8" fill="url(#floor-tile)" />
        <line x1="68" y1="630" x2="68" y2="584" stroke="#0f1419" strokeWidth="2.4" strokeLinecap="round" />
        <path d="M 68 584 A 46 46 0 0 1 114 630" fill="none" stroke="#0f1419" strokeWidth="0.8" strokeDasharray="3 2" opacity="0.55" />
        <text x="128" y="612" fontFamily="Cardo" fontStyle="italic" fontSize="14" fill="#066aab">Вход</text>
      </g>

      {/* ===== Подписи зон ===== */}
      <text x="400" y="206" textAnchor="middle" fontFamily="Cardo" fontStyle="italic" fontSize="13" fill="#6e7682">парикмахерская · 7 мест</text>
      <text x="30" y="372" textAnchor="middle" transform="rotate(-90 30 372)" fontFamily="Cardo" fontStyle="italic" fontSize="13" fill="#6e7682">визаж · 2</text>

      {hoverHint(700, 688)}
    </svg>
  );
};

window.FloorPlan = FloorPlan;
