// MissionChef — Reservations: Calendar sidebar + Floorplan with decor (walls, plants, bar, doors)

function ReservationsScreen({ Topbar }) {
  const store = useStore();
  const [selectedRes, setSelectedRes] = React.useState(null);
  const [showNewRes, setShowNewRes] = React.useState(false);
  const [editMode, setEditMode] = React.useState(false);
  const [sourceFilter, setSourceFilter] = React.useState('all');
  const [drag, setDrag] = React.useState(null); // { kind: 'table'|'decor', id, ox, oy }
  const [selectedDecor, setSelectedDecor] = React.useState(null);
  const [activeRoom, setActiveRoom] = React.useState((store.rooms && store.rooms[0]?.id) || 'rm-main');
  const planRef = React.useRef(null);
  const rooms = store.rooms || [];
  const roomTables = store.tables.filter(t => (t.room || 'rm-main') === activeRoom);
  const roomDecor = store.decor.filter(d => (d.room || 'rm-main') === activeRoom);

  const onMouseDown = (e, kind, item) => {
    if (!editMode && kind === 'decor') return;
    const rect = planRef.current.getBoundingClientRect();
    setDrag({ kind, id: item.id, ox: e.clientX - rect.left - item.x, oy: e.clientY - rect.top - item.y });
    if (kind === 'decor') setSelectedDecor(item.id);
  };
  const onMouseMove = (e) => {
    if (!drag) return;
    const rect = planRef.current.getBoundingClientRect();
    const x = Math.max(0, Math.min(rect.width - 30, e.clientX - rect.left - drag.ox));
    const y = Math.max(0, Math.min(rect.height - 30, e.clientY - rect.top - drag.oy));
    if (drag.kind === 'table') mcApi.patch(`/tables/${drag.id}`, { x, y });
    else mcApi.patch(`/decor/${drag.id}`, { x, y });
  };

  const filteredRes = store.reservations.filter(r => sourceFilter === 'all' || r.source === sourceFilter);
  const selected = selectedRes && store.reservations.find(r => r.id === selectedRes);

  // jump to the room of the selected reservation
  React.useEffect(() => {
    if (selected) {
      const t = store.tables.find(x => x.id === selected.tableId);
      if (t && t.room && t.room !== activeRoom) setActiveRoom(t.room);
    }
  }, [selectedRes]);

  const addDecor = (kind) => {
    const defaults = {
      wall:     { room: activeRoom, kind: 'wall',     x: 100, y: 150, w: 120, h: 6 },
      planter:  { room: activeRoom, kind: 'planter',  x: 100, y: 150, w: 6, h: 80 },
      plant:    { room: activeRoom, kind: 'plant',    x: 100, y: 150 },
      bar:      { room: activeRoom, kind: 'bar',      x: 100, y: 150, w: 140, h: 30, label: 'Theke' },
      window:   { room: activeRoom, kind: 'window',   x: 100, y: 4,   w: 160, h: 6 },
      door:     { room: activeRoom, kind: 'door',     x: 100, y: 4,   w: 60,  h: 6 },
      kitchen:  { room: activeRoom, kind: 'kitchen',  x: 100, y: 150, w: 100, h: 30, label: 'Pass' },
      restroom: { room: activeRoom, kind: 'restroom', x: 100, y: 150, w: 60,  h: 30, label: 'WC' },
    };
    mcApi.post('/decor', defaults[kind]);
  };

  return (
    <>
      <Topbar
        title="Reservierungen"
        subtitle={`${fmtDATE(new Date())} · ${store.reservations.length} Buchungen`}
        actions={
          <div style={{ display: 'flex', gap: 8 }}>
            <button className={editMode ? 'mc-btn ink sm' : 'mc-btn ghost sm'} onClick={() => { setEditMode(v => !v); setSelectedDecor(null); }}>
              <McIcon2 name="edit" size={14} />{editMode ? 'Plan fertig' : 'Plan bearbeiten'}
            </button>
            <button className="mc-btn leaf sm" onClick={() => setShowNewRes(true)}>
              <McIcon2 name="plus" size={14} />Neue Reservierung
            </button>
          </div>
        }
      />
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {/* LEFT: list */}
        <div className="mc-scroll" style={{ width: 360, borderRight: '1px solid var(--mc-rule)', overflow: 'auto', background: 'var(--mc-surface)' }}>
          <div style={{ padding: 16, borderBottom: '1px solid var(--mc-rule)' }}>
            <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
              {['Heute', 'Morgen', 'Woche'].map((l, i) => (
                <Pill key={l} tone={i === 0 ? 'ink' : 'default'}>{l}</Pill>
              ))}
            </div>
            <div className="mc-eyebrow" style={{ marginBottom: 6 }}>Quelle</div>
            <select className="mc-input" style={{ fontSize: 12, padding: '6px 10px' }} value={sourceFilter} onChange={e => setSourceFilter(e.target.value)}>
              <option value="all">Alle Quellen</option>
              <option value="Telefon">Telefon</option>
              <option value="Website">Website</option>
              <option value="Google">Google Maps</option>
              <option value="Google Reservations">Google Reservations</option>
              <option value="Manuell">Manuell</option>
            </select>
          </div>
          {filteredRes.map(r => {
            const t = store.tables.find(x => x.id === r.tableId);
            const active = selectedRes === r.id;
            return (
              <div key={r.id} onClick={() => setSelectedRes(r.id)} className="mc-row" style={{
                padding: '14px 18px', borderBottom: '1px solid var(--mc-rule)',
                cursor: 'pointer', background: active ? 'var(--mc-surface-2)' : 'transparent',
                borderLeft: active ? '3px solid var(--mc-leaf)' : '3px solid transparent',
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <div className="mc-mono" style={{ fontSize: 16, fontWeight: 500 }}>{fmtTIME(new Date(r.at))}</div>
                  <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                    <SourceIcon source={r.source} />
                    <StatusDot tone={r.status === 'checked-in' ? 'ok' : r.status === 'waitlist' ? 'warn' : 'info'} />
                  </div>
                </div>
                <div style={{ fontSize: 14, fontWeight: 500, marginTop: 4 }}>{r.name}</div>
                <div style={{ fontSize: 12, color: 'var(--mc-ink-dim)', marginTop: 2 }}>
                  {r.party} Gäste · T{t?.label} · {r.source}
                </div>
                {r.note && <div style={{ fontSize: 11, color: 'var(--mc-ember-700)', marginTop: 4, fontStyle: 'italic' }}>{r.note}</div>}
              </div>
            );
          })}
        </div>

        {/* CENTER: floorplan */}
        <div style={{ flex: 1, padding: 28, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 14, alignItems: 'flex-end' }}>
            <div>
              <div className="mc-eyebrow">Tischplan · {rooms.find(r => r.id === activeRoom)?.name || ''}</div>
              <div style={{ fontSize: 18, fontWeight: 500, marginTop: 4 }}>
                {editMode ? 'Bearbeitungsmodus · Elemente ziehen' : `${roomTables.length} Tische · ${roomTables.reduce((s,t)=>s+t.seats,0)} Plätze`}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 14, fontSize: 12, color: 'var(--mc-ink-muted)' }}>
              <span><StatusDot tone="ok" /> Frei</span>
              <span><StatusDot tone="info" /> Reserviert</span>
              <span><StatusDot tone="warn" /> Besetzt</span>
            </div>
          </div>

          {/* Edit toolbar */}
          {editMode && (
            <div style={{ background: 'var(--mc-ink)', color: 'var(--mc-bg)', padding: 12, marginBottom: 12, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
              <span className="mc-eyebrow" style={{ color: 'var(--mc-ink-dim)', marginRight: 6 }}>Hinzufügen:</span>
              {[
                ['table', 'Tisch', 'plate'],
                ['wall', 'Wand', 'menu'],
                ['planter', 'Trennpflanzer', 'menu'],
                ['plant', 'Pflanze', 'sparkle'],
                ['bar', 'Bar / Theke', 'cart'],
                ['window', 'Fenster', 'menu'],
                ['door', 'Tür', 'arrow'],
                ['kitchen', 'Pass', 'flame'],
                ['restroom', 'WC', 'user'],
              ].map(([k, lbl, ic]) => (
                <button key={k} onClick={() => k === 'table' ? mcApi.post('/tables', { room: activeRoom, label: String(roomTables.length + 1).padStart(2,'0'), seats: 4, x: 120, y: 150, shape: 'square' }) : addDecor(k)} style={{
                  background: 'transparent', color: 'var(--mc-bg)', border: '1px solid var(--mc-ink-muted)',
                  padding: '6px 10px', cursor: 'pointer', fontSize: 11, display: 'inline-flex', alignItems: 'center', gap: 6,
                  fontFamily: 'inherit',
                }}>
                  <McIcon2 name={ic} size={12} />{lbl}
                </button>
              ))}
              {selectedDecor && (
                <button onClick={() => { mcApi.delete(`/decor/${selectedDecor}`); setSelectedDecor(null); }} style={{
                  marginLeft: 'auto', background: 'var(--mc-ember)', color: '#1B1B17', border: 'none',
                  padding: '6px 12px', cursor: 'pointer', fontSize: 11, display: 'inline-flex', alignItems: 'center', gap: 6,
                  fontFamily: 'inherit', fontWeight: 500,
                }}>
                  <McIcon2 name="trash" size={12} />Element löschen
                </button>
              )}
            </div>
          )}

          {/* Room tabs */}
          <div style={{ display: 'flex', gap: 0, marginBottom: 14, borderBottom: '1px solid var(--mc-rule)' }}>
            {rooms.map(rm => {
              const tablesInRoom = store.tables.filter(t => (t.room || 'rm-main') === rm.id);
              const seated = tablesInRoom.filter(t => t.status === 'seated').length;
              const reserved = tablesInRoom.filter(t => t.status === 'reserved').length;
              const active = activeRoom === rm.id;
              return (
                <button key={rm.id} onClick={() => { setActiveRoom(rm.id); setSelectedDecor(null); }} style={{
                  background: 'transparent', border: 'none', cursor: 'pointer',
                  padding: '12px 20px 14px', borderBottom: active ? '2px solid var(--mc-leaf-700)' : '2px solid transparent',
                  marginBottom: -1,
                  display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-start',
                  fontFamily: 'inherit', color: active ? 'var(--mc-ink)' : 'var(--mc-ink-muted)',
                }}>
                  <span style={{ fontSize: 14, fontWeight: active ? 500 : 400 }}>{rm.name}</span>
                  <span className="mc-mono" style={{ fontSize: 10, color: 'var(--mc-ink-dim)', display: 'flex', gap: 8 }}>
                    <span>{tablesInRoom.length} Tische</span>
                    {seated > 0 && <span style={{ color: 'var(--mc-ember-700)' }}>{seated} besetzt</span>}
                    {reserved > 0 && <span style={{ color: 'var(--mc-info)' }}>{reserved} reserviert</span>}
                  </span>
                </button>
              );
            })}
          </div>

          <div ref={planRef}
               onMouseMove={onMouseMove}
               onMouseUp={() => setDrag(null)}
               onMouseLeave={() => setDrag(null)}
               onClick={(e) => { if (e.target === planRef.current) setSelectedDecor(null); }}
               style={{
            flex: 1, background: 'var(--mc-surface-2)', border: '2px solid var(--mc-rule-strong)',
            position: 'relative', minHeight: 480, overflow: 'hidden',
            backgroundImage: 'radial-gradient(circle, var(--mc-rule-strong) 1px, transparent 1px)',
            backgroundSize: '20px 20px',
          }}>
            {/* Decor (rendered behind tables) */}
            {store.decor.filter(d => (d.room || 'rm-main') === activeRoom).map(d => (
              <DecorElement key={d.id} d={d} editMode={editMode}
                            selected={selectedDecor === d.id}
                            onMouseDown={(e) => onMouseDown(e, 'decor', d)} />
            ))}

            {/* Tables */}
            {store.tables.filter(t => (t.room || 'rm-main') === activeRoom).map(t => {
              const isLong = t.shape === 'long';
              const w = isLong ? 90 : 60;
              const h = 60;
              const color = t.status === 'seated' ? 'var(--mc-ember)' : t.status === 'reserved' ? 'var(--mc-info)' : 'var(--mc-leaf-700)';
              return (
                <div key={t.id} onMouseDown={(e) => onMouseDown(e, 'table', t)} style={{
                  position: 'absolute', left: t.x - w/2, top: t.y - h/2, width: w, height: h,
                  borderRadius: t.shape === 'round' ? '50%' : 4,
                  border: `2px solid ${color}`, background: 'var(--mc-surface)',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                  cursor: 'grab', userSelect: 'none',
                  boxShadow: drag?.id === t.id ? '0 6px 18px rgba(0,0,0,.18)' : 'none',
                  zIndex: 2,
                }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{t.label}</div>
                  <div style={{ fontSize: 10, color: 'var(--mc-ink-dim)' }}>{t.seats} Pl</div>
                </div>
              );
            })}
          </div>
        </div>

        {/* RIGHT: detail panel */}
        {selected && (
          <div style={{ width: 320, borderLeft: '1px solid var(--mc-rule)', background: 'var(--mc-surface)', padding: 24, overflow: 'auto' }} className="mc-scroll">
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div className="mc-eyebrow">Reservierung</div>
              <button onClick={() => setSelectedRes(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--mc-ink-dim)' }}><McIcon2 name="x" size={14} /></button>
            </div>
            <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.015em', marginTop: 10 }}>{selected.name}</div>
            <div className="mc-mono" style={{ fontSize: 14, color: 'var(--mc-leaf-700)', marginTop: 4 }}>{fmtTIME(new Date(selected.at))} · {selected.party} Gäste</div>

            <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 12 }}>
              {[
                ['Tisch', 'T' + store.tables.find(t => t.id === selected.tableId)?.label],
                ['Telefon', selected.phone],
                ['Quelle', <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><SourceIcon source={selected.source} />{selected.source}</span>],
                ['Status', selected.status],
              ].map(([k, v]) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid var(--mc-rule)', paddingBottom: 8 }}>
                  <span style={{ fontSize: 12, color: 'var(--mc-ink-dim)' }}>{k}</span>
                  <span style={{ fontSize: 13 }}>{v}</span>
                </div>
              ))}
              {selected.note && (
                <div style={{ padding: 12, background: 'var(--mc-surface-2)', borderLeft: '3px solid var(--mc-ember)' }}>
                  <div className="mc-eyebrow" style={{ marginBottom: 4 }}>Notiz</div>
                  <div style={{ fontSize: 13 }}>{selected.note}</div>
                </div>
              )}
            </div>

            <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 8 }}>
              <button className="mc-btn leaf" onClick={() => mcApi.patch(`/reservations/${selected.id}`, { status: 'checked-in' })}>
                <McIcon2 name="check" size={14} />Check-in
              </button>
              <button className="mc-btn ghost sm" onClick={() => { mcApi.delete(`/reservations/${selected.id}`); setSelectedRes(null); }}>
                <McIcon2 name="trash" size={14} />Stornieren
              </button>
            </div>
          </div>
        )}
      </div>

      {showNewRes && <NewReservationModal onClose={() => setShowNewRes(false)} />}
    </>
  );
}

// ─── DECOR ELEMENT ──────────────────────────────────────────────────────────
function DecorElement({ d, editMode, selected, onMouseDown }) {
  const baseStyle = {
    position: 'absolute', left: d.x, top: d.y,
    cursor: editMode ? 'grab' : 'default',
    userSelect: 'none',
    outline: selected && editMode ? '2px dashed var(--mc-ink)' : 'none',
    outlineOffset: 2,
    zIndex: 1,
  };

  if (d.kind === 'wall') {
    return <div onMouseDown={onMouseDown} style={{ ...baseStyle, width: d.w, height: d.h, background: 'var(--mc-ink)' }} />;
  }
  if (d.kind === 'window') {
    return <div onMouseDown={onMouseDown} style={{ ...baseStyle, width: d.w, height: d.h, background: 'var(--mc-info)', borderRadius: 1, opacity: 0.6 }} />;
  }
  if (d.kind === 'door') {
    return (
      <div onMouseDown={onMouseDown} style={{ ...baseStyle, width: d.w, height: d.h, background: 'var(--mc-bg)', border: '2px dashed var(--mc-ink)' }} />
    );
  }
  if (d.kind === 'planter') {
    return (
      <div onMouseDown={onMouseDown} style={{ ...baseStyle, width: d.w, height: d.h, background: 'repeating-linear-gradient(0deg, var(--mc-leaf-700) 0px, var(--mc-leaf-700) 4px, var(--mc-leaf) 4px, var(--mc-leaf) 8px)', borderRadius: 2 }} />
    );
  }
  if (d.kind === 'plant') {
    return (
      <div onMouseDown={onMouseDown} style={{ ...baseStyle, width: 32, height: 32 }}>
        <svg width="32" height="32" viewBox="0 0 32 32">
          <ellipse cx="16" cy="28" rx="9" ry="3" fill="#8A6A3A" />
          <rect x="10" y="22" width="12" height="6" fill="#A8743F" />
          <path d="M16 22 L16 10 M16 16 Q10 12 8 6 M16 16 Q22 12 24 6 M16 12 Q12 8 10 4 M16 12 Q20 8 22 4" stroke="#6E8A28" strokeWidth="2" fill="none" strokeLinecap="round" />
          <circle cx="9" cy="7" r="3" fill="#AEC854" />
          <circle cx="23" cy="7" r="3" fill="#AEC854" />
          <circle cx="16" cy="4" r="3" fill="#AEC854" />
          <circle cx="11" cy="4" r="2.5" fill="#6E8A28" />
          <circle cx="21" cy="4" r="2.5" fill="#6E8A28" />
        </svg>
      </div>
    );
  }
  if (d.kind === 'bar') {
    return (
      <div onMouseDown={onMouseDown} style={{ ...baseStyle, width: d.w, height: d.h, background: 'var(--mc-ink)', color: 'var(--mc-bg)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: '.2em', textTransform: 'uppercase' }}>
        {d.label || 'BAR'}
      </div>
    );
  }
  if (d.kind === 'kitchen' || d.kind === 'restroom') {
    return (
      <div onMouseDown={onMouseDown} style={{ ...baseStyle, width: d.w, height: d.h, background: 'var(--mc-rule)', color: 'var(--mc-ink-muted)', border: '1px solid var(--mc-rule-strong)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: '.2em', textTransform: 'uppercase' }}>
        {d.label}
      </div>
    );
  }
  return null;
}

// ─── SOURCE ICON ────────────────────────────────────────────────────────────
function SourceIcon({ source }) {
  const map = {
    'Telefon':              { icon: 'phone', color: 'var(--mc-ink-muted)' },
    'Website':              { icon: 'eye',   color: 'var(--mc-leaf-700)' },
    'Google':               { icon: 'google',color: '#34A853' },
    'Google Reservations':  { icon: 'calendar', color: '#1A73E8' },
    'Manuell':              { icon: 'edit',  color: 'var(--mc-ink-muted)' },
  };
  const c = map[source] || map['Manuell'];
  return (
    <span title={source} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 18, height: 18, color: c.color }}>
      <McIcon2 name={c.icon} size={12} stroke={2} />
    </span>
  );
}

function NewReservationModal({ onClose }) {
  const store = useStore();
  const [name, setName] = React.useState('');
  const [party, setParty] = React.useState(2);
  const [time, setTime] = React.useState('19:30');
  const [note, setNote] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [source, setSource] = React.useState('Manuell');

  const save = async () => {
    const [h, m] = time.split(':').map(Number);
    const at = new Date(); at.setHours(h, m, 0, 0);
    const t = store.tables.find(x => x.status === 'open' && x.seats >= party);
    await mcApi.post('/reservations', {
      name, party, at: at.toISOString(), note, phone,
      tableId: t?.id, source,
    });
    onClose();
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(27,27,23,.5)', zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div onClick={e => e.stopPropagation()} style={{ background: 'var(--mc-surface)', width: 460, padding: 32 }}>
        <div className="mc-eyebrow">Neue Reservierung</div>
        <div style={{ fontSize: 24, fontWeight: 500, marginTop: 6, marginBottom: 20 }}>Anlegen</div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <label><div className="mc-eyebrow" style={{ marginBottom: 6 }}>Name</div>
            <input className="mc-input" value={name} onChange={e => setName(e.target.value)} placeholder="Familie Müller" /></label>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label><div className="mc-eyebrow" style={{ marginBottom: 6 }}>Gäste</div>
              <input type="number" className="mc-input" value={party} onChange={e => setParty(+e.target.value)} /></label>
            <label><div className="mc-eyebrow" style={{ marginBottom: 6 }}>Zeit</div>
              <input type="time" className="mc-input" value={time} onChange={e => setTime(e.target.value)} /></label>
          </div>
          <label><div className="mc-eyebrow" style={{ marginBottom: 6 }}>Telefon</div>
            <input className="mc-input" value={phone} onChange={e => setPhone(e.target.value)} placeholder="+49 …" /></label>
          <label><div className="mc-eyebrow" style={{ marginBottom: 6 }}>Quelle</div>
            <select className="mc-input" value={source} onChange={e => setSource(e.target.value)}>
              <option>Manuell</option>
              <option>Telefon</option>
              <option>Website</option>
              <option>Google</option>
              <option>Google Reservations</option>
            </select></label>
          <label><div className="mc-eyebrow" style={{ marginBottom: 6 }}>Notiz</div>
            <input className="mc-input" value={note} onChange={e => setNote(e.target.value)} placeholder="Geburtstag, Allergien…" /></label>
        </div>

        <div style={{ display: 'flex', gap: 10, marginTop: 24, justifyContent: 'flex-end' }}>
          <button className="mc-btn ghost" onClick={onClose}>Abbrechen</button>
          <button className="mc-btn leaf" onClick={save} disabled={!name}>Anlegen</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ReservationsScreen, DecorElement, SourceIcon });
