/* Additional views: List, Month  (Floor lives in components-floor.jsx) */
const { fmtTime: fmtT3, durationLabel: durL3 } = window.SEATIQ_HELPERS;

// ---------- Floor plan (old, kept for safety but unused) ----------
function _FloorViewOld({ tables, reservations, now, selectedId, onSelect }) {
  const nowMin = now.getHours() * 60 + now.getMinutes();
  // Determine current state of each table
  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 };
  };

  return (
    <div className="floor">
      <div className="floor-canvas">
        {/* Room labels */}
        <div className="floor-room-label" style={{top: 80, left: 30}}>STUEN</div>
        <div className="floor-room-label" style={{top: 80, left: 615}}>BAR</div>
        <div className="floor-room-label" style={{top: 80, left: 790}}>KAMMER · PRIVAT</div>
        <div className="floor-divider" style={{top: 100, bottom: 30, left: 590, width: 1}}/>
        <div className="floor-divider" style={{top: 100, bottom: 30, left: 760, width: 1}}/>

        {/* "Entrance" hint */}
        <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 cls = ['floor-table', t.shape, state, selectedId === res?.id ? 'selected' : ''].filter(Boolean).join(' ');
          return (
            <div key={t.id} className={cls}
              style={{ left: t.x, top: t.y, width: t.w, height: t.h, position: 'absolute' }}
              onClick={() => res && onSelect(res.id)}>
              {t.name.replace('Bord ', '')}
              {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>
          );
        })}

        <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>
  );
}

// ---------- List view ----------
function ListView({ reservations, tables, selectedId, onSelect }) {
  const tableById = Object.fromEntries(tables.map(t => [t.id, t]));
  const sorted = [...reservations].sort((a, b) => a.start - b.start);
  return (
    <div className="list-view">
      <table className="list-table">
        <thead>
          <tr>
            <th>Tid</th>
            <th>Gæst</th>
            <th>Pers</th>
            <th>Bord</th>
            <th>Status</th>
            <th>Telefon</th>
            <th>Noter</th>
            <th>Tags</th>
          </tr>
        </thead>
        <tbody>
          {sorted.map(r => (
            <tr key={r.id}
              className={selectedId === r.id ? 'selected' : ''}
              onClick={() => onSelect(r.id)}
              style={{cursor: 'pointer'}}>
              <td style={{fontFamily: 'var(--mono)', fontVariantNumeric: 'tabular-nums', fontWeight: 600}}>
                {fmtT3(r.start)} <span style={{color: 'var(--muted)'}}>– {fmtT3(r.end)}</span>
              </td>
              <td className="name-cell">{r.name}</td>
              <td><strong>{r.pax}</strong></td>
              <td><span style={{padding: '3px 8px', background: 'var(--surface-2)', borderRadius: 6, fontSize: 12}}>{tableById[r.table]?.name}</span></td>
              <td><span className={`status-chip ${r.status}`}>{window.SEATIQ_HELPERS.STATUS_LABEL[r.status]}</span></td>
              <td style={{color: 'var(--muted)'}}>{r.phone}</td>
              <td style={{color: 'var(--ink-2)', maxWidth: 240, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>
                {r.allergies?.length > 0 && <span style={{color: 'var(--danger)', fontWeight: 700, marginRight: 6}}>⚠ {r.allergies.join(', ')}</span>}
                {r.notes}
              </td>
              <td>{r.tags?.map(t => <span key={t} className="tag-pill" style={{marginRight: 4, marginBottom: 0}}>{t}</span>)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ---------- Month view ----------
function MonthView({ date, onPickDay }) {
  // Build a month grid for May 2026
  const year = date.getFullYear();
  const month = date.getMonth();
  const first = new Date(year, month, 1);
  // Monday = 0
  const dayOffset = (first.getDay() + 6) % 7;
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < dayOffset; i++) {
    cells.push({ off: true, date: new Date(year, month, -dayOffset + i + 1) });
  }
  for (let d = 1; d <= daysInMonth; d++) {
    const dt = new Date(year, month, d);
    // Deterministic pseudo-data based on weekday
    const wd = dt.getDay();
    let covers = 0, capacity = 60;
    if (wd === 1) covers = 28;
    else if (wd === 2) covers = 34;
    else if (wd === 3) covers = 42;
    else if (wd === 4) covers = 50;
    else if (wd === 5) covers = 58;
    else if (wd === 6) covers = 60;
    else covers = 20;
    // some variability
    covers += (d * 3) % 7 - 3;
    covers = Math.max(0, Math.min(60, covers));
    cells.push({ date: dt, covers, capacity, today: d === 18 });
  }
  const monthName = new Intl.DateTimeFormat('da-DK', { month: 'long', year: 'numeric' }).format(date);

  return (
    <div className="month-view">
      <div style={{display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14}}>
        <div>
          <div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 700}}>Måned</div>
          <div style={{fontFamily: 'var(--display)', fontWeight: 800, fontSize: 36, letterSpacing: '-0.03em', textTransform: 'capitalize'}}>{monthName}</div>
        </div>
        <div style={{display: 'flex', gap: 24}}>
          <Stat label="Reservationer" value="287" />
          <Stat label="Covers" value="1.142" />
          <Stat label="Belægning" value="73%" />
          <Stat label="Omsætning" value="782k" />
        </div>
      </div>

      <div className="month-headers">
        {['Man','Tir','Ons','Tor','Fre','Lør','Søn'].map(d => <div key={d}>{d}</div>)}
      </div>
      <div className="month-grid">
        {cells.map((c, i) => (
          <div key={i}
            className={`month-cell ${c.off ? 'off' : ''} ${c.today ? 'today' : ''}`}
            onClick={() => !c.off && onPickDay(c.date)}>
            <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'baseline'}}>
              <span className="mday">{c.date.getDate()}</span>
              {c.today && <span style={{fontSize: 10, fontWeight: 800, letterSpacing: '0.08em', color: 'var(--danger)'}}>I DAG</span>}
            </div>
            {!c.off && (
              <>
                <div className="mcovers">
                  <span className="num">{c.covers}</span>
                  <span className="lbl">covers</span>
                </div>
                <div className="bar"><div style={{width: `${(c.covers/c.capacity)*100}%`}}/></div>
              </>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

function Stat({ label, value }) {
  return (
    <div>
      <div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 700}}>{label}</div>
      <div style={{fontFamily: 'var(--display)', fontWeight: 800, fontSize: 26, letterSpacing: '-0.02em'}}>{value}</div>
    </div>
  );
}

Object.assign(window, { ListView, MonthView });
