// ─────────────────────────────────────────────────────────────────────────────
// Apartment sales-status — single front-end source of truth.
//
// Baseline below = the "Preisliste Kaisten Eigenmatt, Stand April 2026" (PDF from
// RE/MAX). At runtime it is overlaid with whatever the broker has set through the
// dashboard (GET /api/status, backed by Vercel KV). If the API is unreachable the
// site falls back to this baseline, so the public page never breaks.
//
// Colour code (per Bäumlin+John): grün = verfügbar, orange = reserviert, rot = verkauft.
// Loaded before pages.jsx / wohnungen-detail.jsx; these globals are shared across files
// exactly like THEMES / useTheme / WOHNUNG_DETAILS.
// ─────────────────────────────────────────────────────────────────────────────

const WOHNUNG_STATUS_DEFAULT = {
  // Haus B — komplett reserviert
  'B.0.1': 'reserviert', 'B.0.2': 'reserviert',
  'B.1.1': 'reserviert', 'B.1.2': 'reserviert',
  'B.2.1': 'reserviert',
  // Haus C — reserviert (C.0.3, C.2.1, C.2.2 bleiben verfügbar)
  'C.0.1': 'reserviert', 'C.0.2': 'reserviert',
  'C.1.1': 'reserviert', 'C.1.2': 'reserviert', 'C.1.3': 'reserviert',
  // Haus D — reserviert
  'D.0.3': 'reserviert', 'D.1.3': 'reserviert',
  // Zusätzliche Räume (Hobbyräume)
  'HR.B': 'reserviert', 'HR.D': 'reserviert',
  // Alles Übrige gilt als 'frei' (Default in statusOf()).
};

// status-key → Darstellung. Reihenfolge = Anzeige-Reihenfolge (Legende, Dashboard).
const STATUS_CONFIG = {
  frei:       { label: 'verfügbar',  dot: '#6BAE5A', text: '#4E8A3E' },
  reserviert: { label: 'reserviert', dot: '#E08A3C', text: '#B5651D' },
  verkauft:   { label: 'verkauft',   dot: '#C0392B', text: '#C0392B' },
};
const STATUS_ORDER = ['frei', 'reserviert', 'verkauft'];

function statusOf(map, id) {
  return (map && map[id]) || 'frei';
}

// ── Fetch once per page load, share the result across all components ──────────
let __statusCache = null;
let __statusPromise = null;

function fetchWohnungStatus() {
  if (__statusPromise) return __statusPromise;
  __statusPromise = fetch('/api/status')
    .then(r => (r.ok ? r.json() : null))
    .then(d => {
      const map = d && d.status ? d.status : null;
      __statusCache = { ...WOHNUNG_STATUS_DEFAULT, ...(map || {}) };
      return __statusCache;
    })
    .catch(() => {
      // API nicht erreichbar (z. B. lokale Vorschau ohne Backend) → Baseline zeigen.
      __statusCache = { ...WOHNUNG_STATUS_DEFAULT };
      return __statusCache;
    });
  return __statusPromise;
}

function useWohnungStatus() {
  const [map, setMap] = React.useState(__statusCache || WOHNUNG_STATUS_DEFAULT);
  React.useEffect(() => {
    let alive = true;
    fetchWohnungStatus().then(m => { if (alive) setMap(m); });
    return () => { alive = false; };
  }, []);
  return map;
}

// ── Reusable status pill (used in the overview table and on detail pages) ─────
function StatusBadge({ status, compact }) {
  const cfg = STATUS_CONFIG[status] || STATUS_CONFIG.frei;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: compact ? '6px' : '8px',
      whiteSpace: 'nowrap',
      ...(compact ? {} : {
        padding: '4px 12px 4px 10px', borderRadius: '999px',
        background: cfg.dot + '1F',
      }),
    }}>
      <span style={{
        width: compact ? '9px' : '8px', height: compact ? '9px' : '8px',
        borderRadius: '50%', background: cfg.dot, flexShrink: 0,
      }} />
      <span style={{
        fontFamily: "'Plus Jakarta Sans', system-ui, sans-serif",
        fontSize: compact ? '0.8em' : '0.72rem', fontWeight: 600,
        letterSpacing: compact ? '0' : '0.04em',
        color: cfg.text,
        textTransform: compact ? 'none' : 'uppercase',
      }}>{cfg.label}</span>
    </span>
  );
}

Object.assign(window, {
  WOHNUNG_STATUS_DEFAULT, STATUS_CONFIG, STATUS_ORDER,
  statusOf, useWohnungStatus, StatusBadge,
});
