/* Floor plan with editor — tables (drag/resize/add), walls, chairs, rooms */
const { useState: fS, useEffect: fE, useRef: fR } = React;

const ROOM_COLORS = ['#F0EDE3', '#E4EAF6', '#F6E4EA', '#E4F6EA', '#F6F0E4'];
const SNAP = 10;
const snap = (n) => Math.round(n / SNAP) * SNAP;

// Compute chair positions for a table (relative to table top-left)
function chairsFor(t) {
  const seats = t.cap[1];
  const chairs = [];
  const CH = 12;
  const GAP = 4;
  if (t.shape === 'round') {
    const cx = t.w / 2, cy = t.h / 2;
    const r = Math.min(t.w, t.h) / 2 + GAP + CH/2;
    for (let i = 0; i < seats; i++) {
      const a = (i / seats) * Math.PI * 2 - Math.PI/2;
      chairs.push({ x: cx + r * Math.cos(a) - CH/2, y: cy + r * Math.sin(a) - CH/2 });
    }
  } else {
    // Distribute seats around the rectangle perimeter, proportional to side lengths.
    const perim = 2 * (t.w + t.h);
    let topN = Math.max(1, Math.round(seats * t.w / perim));
    let botN = topN;
    let leftN = Math.max(0, Math.round((seats - 2 * topN) / 2));
    let rightN = leftN;
    let total = topN + botN + leftN + rightN;
    // adjust to match seats exactly
    while (total < seats) { (t.w >= t.h ? (topN++) : (leftN++)); total = topN + (botN = topN) + leftN + (rightN = leftN); if (total < seats) { (t.w >= t.h ? botN++ : rightN++); total++; } }
    while (total > seats) { (t.w >= t.h ? (topN--) : (leftN--)); total = topN + (botN = topN) + leftN + (rightN = leftN); }
    for (let i = 0; i < topN; i++) {
      const x = (t.w / (topN + 1)) * (i + 1) - CH/2;
      chairs.push({ x, y: -CH - GAP });
    }
    for (let i = 0; i < botN; i++) {
      const x = (t.w / (botN + 1)) * (i + 1) - CH/2;
      chairs.push({ x, y: t.h + GAP });
    }
    for (let i = 0; i < leftN; i++) {
      const y = (t.h / (leftN + 1)) * (i + 1) - CH/2;
      chairs.push({ x: -CH - GAP, y });
    }
    for (let i = 0; i < rightN; i++) {
      const y = (t.h / (rightN + 1)) * (i + 1) - CH/2;
      chairs.push({ x: t.w + GAP, y });
    }
  }
  return chairs;
}

function FloorView({ tables, setTables, rooms, setRooms, walls, setWalls, reservations, now, selectedId, onSelect }) {
  const [editMode, setEditMode] = fS(false);
  const [selType, setSelType] = fS(null); // 'table' | 'wall'
  const [selId, setSelId] = fS(null);
  const [drag, setDrag] = fS(null);
  const canvasRef = fR(null);

  const nowMin = now.getHours() * 60 + now.getMinutes();
  const stateOf = (tableId) => {
    const rs = reservations.filter(r => r.table === tableId);
    const current = rs.find(r => r.start <= nowMin && r.end > nowMin && r.status !== 'finished');
    if (current?.status === 'seated') return { state: 'occupied', res: current };
    const arriving = rs.find(r => r.status === 'arriving');
    if (arriving) return { state: 'arriving', res: arriving };
    const upcoming = rs.find(r => r.status === 'confirmed' && r.start - nowMin <= 60 && r.start > nowMin);
    if (upcoming) return { state: 'confirmed', res: upcoming };
    return { state: 'free', res: null };
  };

  const startDrag = (e, kind, id, mode) => {
    if (!editMode) return;
    e.preventDefault(); e.stopPropagation();
    let ent;
    if (kind === 'table') ent = tables.find(x => x.id === id);
    else if (kind === 'wall') ent = walls.find(x => x.id === id);
    else if (kind === 'room') ent = rooms.find(x => x.id === id);
    setSelType(kind); setSelId(id);
    setDrag({
      kind, id, mode,
      startX: e.clientX, startY: e.clientY,
      // Room labels store position as labelX/labelY; tables/walls use x/y.
      origX: kind === 'room' ? ent.labelX : ent.x,
      origY: kind === 'room' ? ent.labelY : ent.y,
      origW: ent.w, origH: ent.h,
    });
  };

  fE(() => {
    if (!drag) return;
    const update = (id, patch) => {
      if (drag.kind === 'table') setTables(prev => prev.map(t => t.id === id ? { ...t, ...patch } : t));
      else if (drag.kind === 'wall') setWalls(prev => prev.map(w => w.id === id ? { ...w, ...patch } : w));
      else if (drag.kind === 'room') setRooms(prev => prev.map(r => r.id === id ? { ...r, ...patch } : r));
    };
    const onMove = (e) => {
      const dx = e.clientX - drag.startX;
      const dy = e.clientY - drag.startY;
      if (drag.mode === 'move') {
        if (drag.kind === 'room') {
          update(drag.id, { labelX: snap(drag.origX + dx), labelY: snap(drag.origY + dy) });
        } else {
          update(drag.id, { x: snap(drag.origX + dx), y: snap(drag.origY + dy) });
        }
      } else if (drag.mode === 'resize') {
        update(drag.id, {
          w: Math.max(20, snap(drag.origW + dx)),
          h: Math.max(20, snap(drag.origH + dy)),
        });
      }
    };
    const onUp = () => setDrag(null);
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
  }, [drag, setTables, setWalls, setRooms]);

  const addTable = (shape = 'rect') => {
    const id = 'nt' + Math.random().toString(36).slice(2, 6);
    const lastNum = Math.max(0, ...tables
      .filter(t => /^Bord \d+$/.test(t.name))
      .map(t => parseInt(t.name.replace('Bord ',''), 10)));
    setTables(prev => [...prev, {
      id, name: `Bord ${lastNum + 1}`,
      cap: [2, 4], room: rooms[0]?.id || 'Stuen',
      shape, x: 220, y: 220, w: shape === 'round' ? 100 : 90, h: shape === 'round' ? 100 : 90,
    }]);
    setSelType('table'); setSelId(id);
  };

  const addWall = (orient) => {
    const id = 'w' + Math.random().toString(36).slice(2, 6);
    setWalls(prev => [...prev, {
      id, x: 300, y: 300,
      w: orient === 'h' ? 200 : 4,
      h: orient === 'h' ? 4 : 200,
    }]);
    setSelType('wall'); setSelId(id);
  };

  const clearPlan = () => {
    if (window.confirm('Tøm hele bordplanen? Alle borde og vægge fjernes — reservationer beholdes, men du skal placere borde igen.')) {
      setTables([]); setWalls([]); setSelId(null);
    }
  };

  const deleteSelected = () => {
    if (selType === 'table') {
      setTables(prev => prev.filter(t => t.id !== selId));
    } else if (selType === 'wall') {
      setWalls(prev => prev.filter(w => w.id !== selId));
    }
    setSelId(null); setSelType(null);
  };

  const updateTable = (id, patch) => setTables(prev => prev.map(t => t.id === id ? { ...t, ...patch } : t));

  const sel = selType === 'table' ? tables.find(t => t.id === selId) : walls.find(w => w.id === selId);

  return (
    <div className="floor" style={{position: 'relative', display: 'block'}}>
      <div style={{minWidth: 0}}>
        {/* Toolbar */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14,
          padding: '8px 14px', background: 'var(--surface)',
          border: '1px solid var(--line)', borderRadius: 12,
          flexWrap: 'wrap',
        }}>
          <button className={`btn ${editMode ? 'btn-accent' : 'btn-soft'}`}
            onClick={() => { setEditMode(!editMode); setSelId(null); }}>
            <Icon name="edit" size={14}/> {editMode ? 'Færdig' : 'Rediger plan'}
          </button>
          {editMode && (
            <>
              <div style={{height: 22, width: 1, background: 'var(--line)', margin: '0 4px'}}/>
              <button className="btn btn-soft" onClick={() => addTable('rect')}>
                <Icon name="plus" size={14}/> Firkantet
              </button>
              <button className="btn btn-soft" onClick={() => addTable('round')}>
                <Icon name="plus" size={14}/> Rundt
              </button>
              <button className="btn btn-soft" onClick={() => addWall('h')}>
                <Icon name="plus" size={14}/> Væg ↔
              </button>
              <button className="btn btn-soft" onClick={() => addWall('v')}>
                <Icon name="plus" size={14}/> Væg ↕
              </button>
              <div style={{flex: 1}}/>
              <span style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600}}>
                {tables.length} borde · {tables.reduce((a,t) => a + t.cap[1], 0)} pladser
              </span>
              <button className="btn btn-ghost" style={{color: 'var(--danger)', borderColor: 'rgba(224,83,58,0.3)'}}
                onClick={clearPlan}>
                <Icon name="x" size={14}/> Tøm plan
              </button>
            </>
          )}
          {!editMode && (
            <span style={{fontSize: 12, color: 'var(--muted)', marginLeft: 8}}>
              Klik et bord for at se reservationen · skift til redigering for at tilrette bordplanen
            </span>
          )}
        </div>

        <div style={{overflowX: 'auto', paddingBottom: 8}}>
        <div className="floor-canvas" ref={canvasRef}
          style={{
            backgroundImage: editMode
              ? `radial-gradient(circle, var(--line-strong) 1px, transparent 1px)`
              : `radial-gradient(circle, var(--line) 1px, transparent 1px)`,
            backgroundSize: '20px 20px',
          }}
          onClick={() => editMode && setSelId(null)}>

          {/* Room labels — draggable in edit mode */}
          {rooms.map((r) => {
            const isSel = editMode && selType === 'room' && selId === r.id;
            return (
              <div key={r.id}
                className={`floor-room-label ${editMode ? 'draggable' : ''} ${isSel ? 'selected' : ''}`}
                style={{
                  top: r.labelY, left: r.labelX,
                  cursor: editMode ? (drag?.id === r.id ? 'grabbing' : 'grab') : 'default',
                }}
                onMouseDown={editMode ? (e) => startDrag(e, 'room', r.id, 'move') : undefined}
                onClick={(e) => { if (editMode) { e.stopPropagation(); setSelType('room'); setSelId(r.id); } }}>
                {r.label}
              </div>
            );
          })}

          {/* Walls */}
          {walls.map(w => {
            const isSel = editMode && selType === 'wall' && selId === w.id;
            return (
              <div key={w.id}
                className={`floor-wall ${isSel ? 'selected' : ''}`}
                style={{
                  position: 'absolute',
                  left: w.x, top: w.y, width: w.w, height: w.h,
                  cursor: editMode ? (drag?.id === w.id ? 'grabbing' : 'grab') : 'default',
                }}
                onMouseDown={(e) => startDrag(e, 'wall', w.id, 'move')}
                onClick={(e) => { e.stopPropagation(); if (editMode) { setSelType('wall'); setSelId(w.id); } }}>
                {isSel && (
                  <>
                    <button className="floor-delete"
                      onMouseDown={(e) => e.stopPropagation()}
                      onClick={(e) => { e.stopPropagation(); deleteSelected(); }}>
                      <Icon name="x" size={12} stroke={2.5}/>
                    </button>
                    <div className="floor-resize"
                      onMouseDown={(e) => startDrag(e, 'wall', w.id, 'resize')} />
                  </>
                )}
              </div>
            );
          })}

          {!editMode && (
            <>
              <div style={{position: 'absolute', bottom: 24, left: 220, fontSize: 10, fontWeight: 700, letterSpacing: '0.15em', color: 'var(--muted)', textTransform: 'uppercase'}}>↓ INDGANG</div>
              <div style={{position: 'absolute', bottom: 24, right: 24, fontSize: 10, fontWeight: 700, letterSpacing: '0.15em', color: 'var(--muted)', textTransform: 'uppercase'}}>KØKKEN ↑</div>
            </>
          )}

          {tables.map(t => {
            const { state, res } = stateOf(t.id);
            const isSel = editMode ? (selType === 'table' && selId === t.id) : (selectedId === res?.id);
            const cls = ['floor-table', t.shape, editMode ? 'free' : state, isSel ? 'selected' : ''].filter(Boolean).join(' ');
            const onMouseDown = editMode ? (e) => startDrag(e, 'table', t.id, 'move') : undefined;
            const handleClick = (e) => {
              e.stopPropagation();
              if (editMode) { setSelType('table'); setSelId(t.id); return; }
              res && onSelect(res.id);
            };
            const chairs = chairsFor(t);
            return (
              <div key={t.id} className={cls}
                style={{
                  left: t.x, top: t.y, width: t.w, height: t.h, position: 'absolute',
                  cursor: editMode ? (drag?.id === t.id ? 'grabbing' : 'grab') : (res ? 'pointer' : 'default'),
                }}
                onMouseDown={onMouseDown}
                onClick={handleClick}>
                {/* chairs */}
                {chairs.map((c, i) => (
                  <div key={i} className={`chair ${state === 'occupied' ? 'occupied' : ''}`}
                    style={{ position: 'absolute', left: c.x, top: c.y, width: 12, height: 12 }}/>
                ))}

                {editMode ? (
                  <>
                    <div style={{fontFamily: 'var(--display)', fontWeight: 800, fontSize: 16}}>{t.name.replace('Bord ','')}</div>
                    <div className="ft-meta">{t.cap[0]}–{t.cap[1]} pers</div>
                    {isSel && (
                      <>
                        <button className="floor-delete"
                          onMouseDown={(e) => e.stopPropagation()}
                          onClick={(e) => { e.stopPropagation(); deleteSelected(); }}>
                          <Icon name="x" size={12} stroke={2.5}/>
                        </button>
                        <div className="floor-resize"
                          onMouseDown={(e) => startDrag(e, 'table', t.id, 'resize')} />
                      </>
                    )}
                  </>
                ) : (
                  <>
                    <div style={{fontFamily: 'var(--display)', fontWeight: 800}}>{t.name.replace('Bord ', '')}</div>
                    {res
                      ? <div className="ft-meta">{res.name.split(' ')[0]} · {res.pax}p</div>
                      : <div className="ft-meta">{t.cap[0]}–{t.cap[1]}</div>}
                  </>
                )}
              </div>
            );
          })}

          {tables.length === 0 && editMode && (
            <div style={{
              position: 'absolute', inset: 0,
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
              gap: 8, color: 'var(--muted)', pointerEvents: 'none',
            }}>
              <Icon name="grid" size={40} stroke={1.5}/>
              <div style={{fontFamily: 'var(--display)', fontWeight: 800, fontSize: 22, letterSpacing: '-0.02em', color: 'var(--ink)'}}>Tom plan</div>
              <div style={{fontSize: 13}}>Tilføj firkantede, runde borde og vægge fra værktøjslinjen ovenfor</div>
            </div>
          )}

          {!editMode && tables.length > 0 && (
            <div className="floor-legend">
              <div style={{fontSize: 10, fontWeight: 700, letterSpacing: '0.12em', color: 'var(--muted)', textTransform: 'uppercase', marginBottom: 4}}>Status nu</div>
              <div className="row"><span className="sw" style={{background: 'var(--accent)'}}/> Siddende</div>
              <div className="row"><span className="sw" style={{background: 'var(--accent-soft)'}}/> Bekræftet i dag</div>
              <div className="row"><span className="sw" style={{background: 'var(--warn-soft)', borderColor: '#C9941F'}}/> Ankommer</div>
              <div className="row"><span className="sw" style={{background: 'var(--surface)'}}/> Ledigt</div>
            </div>
          )}
        </div>
        </div>
      </div>

      {/* Edit side panel — floats over canvas */}
      {editMode && (
        <aside style={{
          position: 'absolute',
          top: 70, right: 8, bottom: 28,
          width: 320, flexShrink: 0,
          background: 'var(--surface)',
          border: '1px solid var(--line)', borderRadius: 12,
          padding: 18,
          overflow: 'auto',
          boxShadow: 'var(--shadow-lg)',
          zIndex: 10,
        }}>
          <div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 700, marginBottom: 12}}>
            {selType === 'table' ? 'Bordets egenskaber' : selType === 'wall' ? 'Væggens egenskaber' : 'Vælg et element'}
          </div>
          {selType === 'table' && sel && (
            <>
              <div className="field">
                <label>Navn</label>
                <input value={sel.name} onChange={e => updateTable(sel.id, { name: e.target.value })} />
              </div>
              <div className="field">
                <label>Antal pladser (kapacitet)</label>
                <div style={{display: 'flex', gap: 8, alignItems: 'center', marginBottom: 8}}>
                  <input type="number" value={sel.cap[0]} min={1} max={20}
                    style={{width: 70}}
                    onChange={e => updateTable(sel.id, { cap: [Math.max(1, +e.target.value || 1), sel.cap[1]] })} />
                  <span style={{color: 'var(--muted)'}}>til</span>
                  <input type="number" value={sel.cap[1]} min={1} max={20}
                    style={{width: 70}}
                    onChange={e => updateTable(sel.id, { cap: [sel.cap[0], Math.max(sel.cap[0], +e.target.value || sel.cap[0])] })} />
                  <span style={{color: 'var(--muted)', fontSize: 12}}>pers</span>
                </div>
                <div style={{fontSize: 11, color: 'var(--muted)'}}>Stolene tegnes automatisk rundt om bordet ud fra max-kapacitet.</div>
              </div>
              <div className="field">
                <label>Rum</label>
                <select value={sel.room} onChange={e => updateTable(sel.id, { room: e.target.value })}>
                  {rooms.map(r => <option key={r.id} value={r.id}>{r.label}</option>)}
                </select>
              </div>
              <div className="field">
                <label>Form</label>
                <div style={{display: 'flex', gap: 6}}>
                  <button className={`chip ${sel.shape === 'rect' ? 'active' : ''}`}
                    onClick={() => updateTable(sel.id, { shape: 'rect' })}>Firkantet</button>
                  <button className={`chip ${sel.shape === 'round' ? 'active' : ''}`}
                    onClick={() => updateTable(sel.id, { shape: 'round' })}>Rund</button>
                </div>
              </div>
              <div className="field">
                <label>Størrelse (px)</label>
                <div style={{display: 'flex', gap: 8}}>
                  <input type="number" value={sel.w} min={50} step={10}
                    onChange={e => updateTable(sel.id, { w: Math.max(50, +e.target.value || 50) })} />
                  <input type="number" value={sel.h} min={50} step={10}
                    onChange={e => updateTable(sel.id, { h: Math.max(50, +e.target.value || 50) })} />
                </div>
              </div>
              <button className="btn btn-ghost" style={{color: 'var(--danger)', borderColor: 'rgba(224,83,58,0.3)', width: '100%', justifyContent: 'center', marginTop: 8}}
                onClick={deleteSelected}>
                <Icon name="x" size={14}/> Slet bord
              </button>
            </>
          )}
          {selType === 'wall' && sel && (
            <>
              <div className="field">
                <label>Størrelse</label>
                <div style={{display: 'flex', gap: 8}}>
                  <input type="number" value={sel.w} min={4} step={10}
                    onChange={e => setWalls(prev => prev.map(w => w.id === sel.id ? { ...w, w: Math.max(4, +e.target.value || 4) } : w))} />
                  <input type="number" value={sel.h} min={4} step={10}
                    onChange={e => setWalls(prev => prev.map(w => w.id === sel.id ? { ...w, h: Math.max(4, +e.target.value || 4) } : w))} />
                </div>
              </div>
              <button className="btn btn-ghost" style={{color: 'var(--danger)', borderColor: 'rgba(224,83,58,0.3)', width: '100%', justifyContent: 'center', marginTop: 8}}
                onClick={deleteSelected}>
                <Icon name="x" size={14}/> Slet væg
              </button>
            </>
          )}
          {!sel && (
            <div style={{fontSize: 13, color: 'var(--muted)', lineHeight: 1.5}}>
              Vælg et bord eller en væg for at redigere — eller tilføj et nyt element fra værktøjslinjen.
            </div>
          )}

          <div style={{borderTop: '1px solid var(--line)', margin: '18px 0 12px'}}/>
          <div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 700, marginBottom: 8}}>
            Rum
          </div>
          {rooms.map((r, i) => (
            <div key={r.id} style={{display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6}}>
              <span style={{width: 14, height: 14, borderRadius: 4, background: ROOM_COLORS[i % ROOM_COLORS.length], border: '1.5px solid var(--ink)'}}/>
              <input value={r.label}
                style={{flex: 1, padding: '6px 8px', fontSize: 13, border: '1px solid var(--line)', borderRadius: 6, background: 'transparent'}}
                onChange={e => setRooms(prev => prev.map(x => x.id === r.id ? { ...x, label: e.target.value } : x))} />
              <span style={{fontSize: 11, color: 'var(--muted)'}}>
                {tables.filter(t => t.room === r.id).length}
              </span>
              <button className="btn-icon" style={{width: 24, height: 24}}
                onClick={() => {
                  if (tables.some(t => t.room === r.id)) { alert('Flyt eller slet borde i rummet først.'); return; }
                  setRooms(prev => prev.filter(x => x.id !== r.id));
                }}>
                <Icon name="x" size={12}/>
              </button>
            </div>
          ))}
          <button className="btn btn-soft" style={{width: '100%', justifyContent: 'center', marginTop: 6}}
            onClick={() => {
              const id = 'rm' + Math.random().toString(36).slice(2,5);
              setRooms(prev => [...prev, { id, label: 'Nyt rum', labelX: 30, labelY: 80 + prev.length * 24 }]);
            }}>
            <Icon name="plus" size={13}/> Tilføj rum
          </button>
        </aside>
      )}
    </div>
  );
}

window.FloorView = FloorView;
