// ╔══════════════════════════════════════════════════════════════╗
// ║  SMART HOME DEMO — Hi-Fi Dashboard Mockup                    ║
// ║  Modelliert nach Home Assistant, dark/cyan-Brand-Adaption     ║
// ╚══════════════════════════════════════════════════════════════╝

const SMD_PALETTE = {
  bgDeep: "#071520",
  bgCard: "#0D2030",
  bgCard2: "#11283C",
  accent: "#3ABDD0",
  soft: "#8DDBEA",
  text: "#ffffff",
  textDim: "rgba(255,255,255,0.55)",
  border: "rgba(141,219,234,0.12)",
  borderHi: "rgba(58,189,208,0.45)",
  // chart accents
  pv: "#F2A65A",         // PV warm orange
  battery: "#5DD3B0",    // battery teal-green
  grid: "#7B9BD3",       // grid blue
  water: "#5BBFD6",      // water cyan
  consumption: "#C28BD9",// purple consumption
  warm: "#E8A5B5",       // warm pink (waschmaschine)
};

// ── Mini sparkline ─────────────────────────────────────────────
function Sparkline({ data, color = SMD_PALETTE.accent, w = 72, h = 22 }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / range) * h;
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(" ");
  return (
    <svg width={w} height={h} style={{ display: "block" }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.4" strokeLinecap="round"/>
    </svg>
  );
}

// ── Inline Material-style icons (very small, white-line) ───────
const SMDIcons = {
  light: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18h6M10 22h4M12 2a7 7 0 0 1 4 12.7c-.6.5-1 1.2-1 2v.3H9v-.3c0-.8-.4-1.5-1-2A7 7 0 0 1 12 2z"/></svg>,
  thermo: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><path d="M14 14.8V5a2 2 0 1 0-4 0v9.8a4 4 0 1 0 4 0z"/></svg>,
  bed: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 18v-6a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v6M3 18h18M3 18v2M21 18v2M7 12h2"/></svg>,
  kitchen: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="3" width="16" height="18" rx="2"/><path d="M4 11h16M9 7h.01M9 15h.01"/></svg>,
  shower: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 4h6a4 4 0 0 1 4 4v2M19 10H7M9 14v.01M11 17v.01M13 14v.01M15 17v.01M9 20v.01M13 20v.01"/></svg>,
  sofa: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 14a3 3 0 0 1 3-3v0a3 3 0 0 1 3 3v3M21 14a3 3 0 0 0-3-3v0a3 3 0 0 0-3 3v3M9 14h6M3 17h18M5 17v3M19 17v3"/></svg>,
  desk: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><rect x="3" y="6" width="18" height="3" rx="1"/><path d="M5 9v10M19 9v10M5 14h6"/></svg>,
  toilet: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 4h14v8a4 4 0 0 1-4 4H9a4 4 0 0 1-4-4V4zM7 20l1-4M17 20l-1-4"/></svg>,
  garage: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11l9-7 9 7v9H3z"/><rect x="7" y="13" width="10" height="6"/></svg>,
  garden: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 21V10M8 14a4 4 0 0 1 4-4 4 4 0 0 1 4 4M5 18l2-3M19 18l-2-3"/></svg>,
  attic: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12L12 4l9 8M5 12v9h14v-9"/></svg>,
  server: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><rect x="3" y="4" width="18" height="6" rx="1"/><rect x="3" y="14" width="18" height="6" rx="1"/><circle cx="7" cy="7" r="0.6" fill={c}/><circle cx="7" cy="17" r="0.6" fill={c}/></svg>,
  device: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><rect x="4" y="6" width="16" height="12" rx="2"/><path d="M8 10h.01M12 10h.01M8 14h8"/></svg>,
  shield: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3l8 3v6c0 5-3.5 8.5-8 9.5C7.5 20.5 4 17 4 12V6l8-3z"/></svg>,
  media: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="12" rx="2"/><path d="M9 21h6M12 17v4"/></svg>,
  weather: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.4 1.4M17.6 17.6L19 19M5 19l1.4-1.4M17.6 6.4L19 5"/></svg>,
  bolt: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M13 2L4 14h7l-1 8 9-12h-7z"/></svg>,
  scenes: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><circle cx="13.5" cy="6.5" r="2.5"/><circle cx="17.5" cy="13.5" r="2.5"/><circle cx="6.5" cy="17.5" r="2.5"/><path d="M12 22a10 10 0 1 1 10-10c0 .8-.7 1.5-1.5 1.5h-2"/></svg>,
  presence: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="3"/><path d="M5 21v-1a7 7 0 0 1 14 0v1"/></svg>,
  valve: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><circle cx="12" cy="12" r="3"/><path d="M12 9V4M12 20v-5M9 12H4M20 12h-5"/></svg>,
  search: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><circle cx="11" cy="11" r="6"/><path d="M16 16l4 4"/></svg>,
  plus: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>,
  menu: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>,
  edit: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M14 4l6 6L10 20H4v-6L14 4z"/></svg>,
  msg: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a3 3 0 0 1-3 3H8l-5 4V6a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v9z"/></svg>,
  arrowL: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>,
  chevR: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6"/></svg>,
  power: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><path d="M12 3v9M5.6 7.6a9 9 0 1 0 12.8 0"/></svg>,
  // sidebar nav items
  home: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11l9-7 9 7v10H3z"/><path d="M9 21V13h6v8"/></svg>,
  grid: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5"><rect x="4" y="4" width="7" height="7"/><rect x="13" y="4" width="7" height="7"/><rect x="4" y="13" width="7" height="7"/><rect x="13" y="13" width="7" height="7"/></svg>,
  user: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>,
  building: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5"><rect x="4" y="3" width="16" height="18"/><path d="M8 7h.01M12 7h.01M16 7h.01M8 11h.01M12 11h.01M16 11h.01M8 15h.01M16 15h.01M11 21v-4h2v4"/></svg>,
  list: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><path d="M4 6h16M4 12h16M4 18h16"/></svg>,
  chart: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><path d="M4 20V10M10 20V4M16 20v-8M22 20H2"/></svg>,
  cal: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5"><rect x="3" y="5" width="18" height="16" rx="1"/><path d="M3 10h18M8 3v4M16 3v4"/></svg>,
  wrench: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M14.7 6.3a4 4 0 0 0 5 5L21 13l-8 8-4-4 8-8 1.7-2.7z"/></svg>,
  bug: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><rect x="8" y="6" width="8" height="14" rx="4"/><path d="M3 10h5M3 14h5M3 18h5M16 10h5M16 14h5M16 18h5M9 6V4a3 3 0 0 1 6 0v2"/></svg>,
  flow: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5"><circle cx="6" cy="6" r="2"/><circle cx="18" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="18" r="2"/><path d="M8 6h8M8 18h8M6 8v8M18 8v8"/></svg>,
  play: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinejoin="round"><path d="M6 4l14 8-14 8z"/></svg>,
  code: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M8 6l-6 6 6 6M16 6l6 6-6 6M14 4l-4 16"/></svg>,
  link: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><path d="M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66L11 7M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66L13 17"/></svg>,
  drop: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinejoin="round"><path d="M12 3l5 7a6 6 0 1 1-10 0z"/></svg>,
  cast: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><path d="M3 17a4 4 0 0 1 4 4M3 13a8 8 0 0 1 8 8M3 9a12 12 0 0 1 12 12M3 5h18v10"/></svg>,
  fire: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22c4 0 7-3 7-7 0-3-2-5-3-6-1 2-3 2-3 0 0-2 1-4 1-6-3 1-7 4-7 9 0 5 3 10 5 10z"/></svg>,
  car: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 17V11l2-5h10l2 5v6M5 17h14M5 17v2M19 17v2"/><circle cx="8" cy="14" r="1.2"/><circle cx="16" cy="14" r="1.2"/></svg>,
  factory: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinejoin="round"><path d="M3 21V11l5 3V11l5 3V11l5 3v7zM6 8V3M10 7V3"/></svg>,
  lock: (c) => <svg viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.5" strokeLinecap="round"><rect x="5" y="11" width="14" height="10" rx="1"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>,
};

// ── Path-aware data ────────────────────────────────────────────
const SMD_DATA = {
  altbau: {
    welcome: "Familie Bauer",
    favorites: [
      { id: "f1", name: "Wohnzimmer", state: "21,4 °C", icon: "thermo", on: true, color: SMD_PALETTE.pv },
      { id: "f2", name: "Garage", state: "Geschlossen", icon: "garage", on: false },
      { id: "f3", name: "Außenlicht", state: "Auto", icon: "light", on: true, color: SMD_PALETTE.pv },
      { id: "f4", name: "Heizung", state: "Heizmodus", icon: "fire", on: true, color: SMD_PALETTE.warm },
      { id: "f5", name: "Hauptschalter", state: "Tag", icon: "scenes", on: true },
      { id: "f6", name: "Anwesenheit", state: "Zuhause", icon: "presence", on: true, color: SMD_PALETTE.battery },
    ],
    floors: [
      { name: "EG", icon: "home", rooms: [
        { id: "wohnzimmer", name: "Wohnzimmer", state: "21,4 °C", icon: "sofa" },
        { id: "kueche", name: "Küche", state: "20,1 °C", icon: "kitchen" },
        { id: "esszimmer", name: "Esszimmer", state: "20,8 °C", icon: "kitchen" },
        { id: "bad", name: "Badezimmer", state: "23,2 °C", icon: "shower" },
        { id: "wc", name: "WC", state: "—", icon: "toilet" },
        { id: "gang", name: "Gang", state: "19,8 °C", icon: "home" },
      ]},
      { name: "OG", icon: "home", rooms: [
        { id: "schlafzimmer", name: "Schlafzimmer", state: "19,5 °C", icon: "bed" },
        { id: "kinderzimmer", name: "Kinderzimmer", state: "20,3 °C", icon: "bed" },
        { id: "buero", name: "Büro", state: "19,3 °C", icon: "desk" },
      ]},
      { name: "Außen", icon: "garden", rooms: [
        { id: "garage", name: "Garage", state: "—", icon: "garage" },
        { id: "garten", name: "Garten", state: "—", icon: "garden" },
        { id: "geraete", name: "Geräte", state: "32 aktiv", icon: "device" },
      ]},
    ],
    summaries: [
      { name: "Entdeckte Geräte", value: "1 Gerät zum Hinzufügen", icon: "device", color: SMD_PALETTE.accent },
      { name: "Beleuchtung", value: "1 ein", icon: "light", color: SMD_PALETTE.pv },
      { name: "Raumklima", value: "20,3 °", icon: "thermo", color: SMD_PALETTE.pv },
      { name: "Sicherheit", value: "Aufgeschlossen", icon: "shield", color: SMD_PALETTE.warm },
      { name: "Mediaplayer", value: "Keine Wiedergabe", icon: "media", color: SMD_PALETTE.consumption },
      { name: "Wetter", value: "8,6 °C · Sonnig", icon: "weather", color: SMD_PALETTE.pv },
      { name: "Heutige Energie", value: "7,5 kWh", icon: "bolt", color: SMD_PALETTE.accent },
    ],
    energy: {
      pv: 24.34, battery: 3.6, grid: -13.25, gridCost: -1.19,
      home: 7.5, water: 365.4, autarkie: 100, eigenverbrauch: 27, einspeisung: 13.25,
    },
  },
  neubau: {
    welcome: "Familie Hofer",
    favorites: [
      { id: "f1", name: "Beschattung", state: "Auto · 60%", icon: "grid", on: true, color: SMD_PALETTE.pv },
      { id: "f2", name: "FBH Vorlauf", state: "32,4 °C", icon: "thermo", on: true, color: SMD_PALETTE.warm },
      { id: "f3", name: "Lüftung KWL", state: "Stufe 2", icon: "weather", on: true, color: SMD_PALETTE.water },
      { id: "f4", name: "Wallbox", state: "Lädt 11 kW", icon: "car", on: true, color: SMD_PALETTE.battery },
      { id: "f5", name: "Alarm", state: "Tag-Modus", icon: "shield", on: true },
      { id: "f6", name: "Szene Heim", state: "Aktiv", icon: "scenes", on: true, color: SMD_PALETTE.accent },
    ],
    floors: [
      { name: "EG", icon: "home", rooms: [
        { id: "wohnen", name: "Wohnen/Essen", state: "22,1 °C", icon: "sofa" },
        { id: "kueche", name: "Küche", state: "21,8 °C", icon: "kitchen" },
        { id: "buero", name: "Homeoffice", state: "21,5 °C", icon: "desk" },
        { id: "bad-eg", name: "Bad EG", state: "—", icon: "shower" },
        { id: "garderobe", name: "Garderobe", state: "20,9 °C", icon: "home" },
      ]},
      { name: "OG", icon: "home", rooms: [
        { id: "schlafen", name: "Schlafen", state: "19,2 °C", icon: "bed" },
        { id: "kind1", name: "Kind 1", state: "20,1 °C", icon: "bed" },
        { id: "kind2", name: "Kind 2", state: "20,4 °C", icon: "bed" },
        { id: "bad-og", name: "Bad OG", state: "23,5 °C", icon: "shower" },
      ]},
      { name: "Technik & Außen", icon: "wrench", rooms: [
        { id: "technik", name: "Technikraum", state: "KNX online", icon: "server" },
        { id: "carport", name: "Carport", state: "Wallbox aktiv", icon: "car" },
        { id: "garten", name: "Garten", state: "Bewässerung aus", icon: "garden" },
      ]},
    ],
    summaries: [
      { name: "KNX-Geräte", value: "84 online · 0 Fehler", icon: "flow", color: SMD_PALETTE.accent },
      { name: "Beleuchtung", value: "DALI · 6 ein", icon: "light", color: SMD_PALETTE.pv },
      { name: "Raumklima FBH", value: "21,3 °", icon: "thermo", color: SMD_PALETTE.warm },
      { name: "KWL", value: "Stufe 2 · 84% Eff.", icon: "weather", color: SMD_PALETTE.water },
      { name: "Sicherheit", value: "Tag-Modus aktiv", icon: "shield", color: SMD_PALETTE.battery },
      { name: "Wallbox", value: "Lädt · PV-Überschuss", icon: "car", color: SMD_PALETTE.pv },
      { name: "Heutige Energie", value: "12,3 kWh", icon: "bolt", color: SMD_PALETTE.accent },
    ],
    energy: {
      pv: 38.2, battery: 8.4, grid: -18.6, gridCost: -1.74,
      home: 12.3, water: 142.8, autarkie: 96, eigenverbrauch: 42, einspeisung: 18.6,
    },
  },
  gewerbe: {
    welcome: "Standort Lambach",
    favorites: [
      { id: "f1", name: "Lastspitze", state: "32,4 kW", icon: "bolt", on: true, color: SMD_PALETTE.pv },
      { id: "f2", name: "Tagesumsatz", state: "€ 24.860", icon: "chart", on: true, color: SMD_PALETTE.battery },
      { id: "f3", name: "KUKA Roboter 1", state: "Bereit", icon: "factory", on: true, color: SMD_PALETTE.accent },
      { id: "f4", name: "Zutritt Tor 1", state: "Geschlossen", icon: "lock", on: false },
      { id: "f5", name: "Anwesenheit", state: "17 Mitarbeiter", icon: "presence", on: true, color: SMD_PALETTE.accent },
      { id: "f6", name: "PV-Feld", state: "24,6 kW Live", icon: "grid", on: true, color: SMD_PALETTE.pv },
    ],
    floors: [
      { name: "Halle", icon: "factory", rooms: [
        { id: "produktion", name: "Produktion", state: "12 MA · Linie läuft", icon: "factory" },
        { id: "werkstatt", name: "Werkstatt", state: "5 MA · KUKA bereit", icon: "wrench" },
        { id: "lager", name: "Lager", state: "Tor zu · 2 offen", icon: "garage" },
        { id: "ausgabe", name: "Ausgabe", state: "3 Abholungen", icon: "garage" },
      ]},
      { name: "Büro", icon: "building", rooms: [
        { id: "buero", name: "Großraum", state: "22,1 °C", icon: "desk" },
        { id: "besprech", name: "Besprechung", state: "Belegt 14:00", icon: "user" },
        { id: "empfang", name: "Empfang", state: "—", icon: "user" },
        { id: "kueche-bz", name: "Sozialraum", state: "20,8 °C", icon: "kitchen" },
      ]},
      { name: "Energie & Zutritt", icon: "bolt", rooms: [
        { id: "pv", name: "PV-Feld 24 kWp", state: "24,6 kW", icon: "grid" },
        { id: "speicher", name: "Speicher 60 kWh", state: "68%", icon: "bolt" },
        { id: "wallbox", name: "Wallbox-Park", state: "3/6 lädt", icon: "car" },
        { id: "zutritt", name: "Zutrittssystem", state: "12 aktiv", icon: "lock" },
      ]},
    ],
    summaries: [
      { name: "Anlagen-Status", value: "Alles betriebsbereit", icon: "shield", color: SMD_PALETTE.battery },
      { name: "Tagesumsatz", value: "€ 24.860 · +8%", icon: "chart", color: SMD_PALETTE.battery },
      { name: "Anwesenheit", value: "17 Mitarbeiter", icon: "presence", color: SMD_PALETTE.accent },
      { name: "Werkstatt", value: "KUKA 1 bereit", icon: "factory", color: SMD_PALETTE.accent },
      { name: "Leistungsabnahme", value: "32,4 kW · stabil", icon: "bolt", color: SMD_PALETTE.pv },
      { name: "Zutritt", value: "Tor 1, 2 zu · Tor 3 offen", icon: "lock", color: SMD_PALETTE.warm },
      { name: "PV-Eigenverbrauch", value: "73% heute", icon: "grid", color: SMD_PALETTE.pv },
    ],
    energy: {
      pv: 184.2, battery: 22.4, grid: -41.6, gridCost: -3.86,
      home: 132.6, water: 0, autarkie: 78, eigenverbrauch: 73, einspeisung: 41.6,
    },
  },
};

// ── Tile component (favorites + room) ──────────────────────────
function SMDTile({ icon, name, state, on, color, accent, large, onClick }) {
  const Icon = SMDIcons[icon];
  const iconColor = on ? (color || SMD_PALETTE.accent) : SMD_PALETTE.textDim;
  const iconBg = on ? `${(color || SMD_PALETTE.accent)}22` : "rgba(255,255,255,0.04)";
  return (
    <button onClick={onClick} className="smd-tile" style={{
      background: SMD_PALETTE.bgCard,
      border: `1px solid ${SMD_PALETTE.border}`,
      borderRadius: 12,
      padding: large ? "14px 14px 12px" : "12px",
      display: "flex", flexDirection: "column", gap: 8,
      cursor: "pointer", transition: "all 0.15s ease",
      textAlign: "left", color: "inherit", font: "inherit",
      minHeight: large ? 88 : 78,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 8, background: iconBg,
        display: "flex", alignItems: "center", justifyContent: "center",
        color: iconColor,
      }}>
        <span style={{ display: "block", width: 18, height: 18 }}>
          {Icon && Icon(iconColor)}
        </span>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 1, marginTop: 2 }}>
        <div style={{
          fontSize: 13, fontWeight: 500, color: SMD_PALETTE.text,
          fontFamily: "Inter, sans-serif",
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
        }}>{name}</div>
        {state && <div style={{
          fontSize: 11, color: SMD_PALETTE.textDim,
          fontFamily: "Inter, sans-serif",
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
        }}>{state}</div>}
      </div>
    </button>
  );
}

// ── Summary list-row (right rail) ──────────────────────────────
function SMDSummaryRow({ icon, name, value, color }) {
  const Icon = SMDIcons[icon];
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 12,
      background: SMD_PALETTE.bgCard,
      border: `1px solid ${SMD_PALETTE.border}`,
      borderRadius: 12, padding: "12px 14px", minHeight: 56,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 8, background: `${color}22`,
        display: "flex", alignItems: "center", justifyContent: "center", color: color, flexShrink: 0,
      }}>
        <span style={{ display: "block", width: 18, height: 18 }}>{Icon && Icon(color)}</span>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: SMD_PALETTE.text, fontFamily: "Inter, sans-serif" }}>{name}</div>
        <div style={{ fontSize: 11, color: SMD_PALETTE.textDim, fontFamily: "Inter, sans-serif", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{value}</div>
      </div>
    </div>
  );
}

// ── Sidebar ────────────────────────────────────────────────────
function SMDSidebar({ activeView, onNav, tourActive, tourStep }) {
  const items = [
    { k: "uebersicht", icon: "home", label: "Übersicht" },
    { k: "energie", icon: "bolt", label: "Energie" },
    { k: "kal", icon: "cal", label: "Kalender" },
  ];
  // Map of view→index (for cursor highlight during tour)
  const tourIdx = tourActive ? Math.min(tourStep, items.length - 1) : -1;

  return (
    <aside style={{
      width: 56, background: SMD_PALETTE.bgCard,
      borderRight: `1px solid ${SMD_PALETTE.border}`,
      display: "flex", flexDirection: "column", alignItems: "center",
      padding: "14px 0", gap: 4, flexShrink: 0,
      position: "relative",
    }}>
      <div style={{
        width: 36, height: 36, display: "flex", alignItems: "center", justifyContent: "center",
        color: SMD_PALETTE.textDim, marginBottom: 6,
      }}>
        <span style={{ display: "block", width: 22, height: 22 }}>{SMDIcons.menu(SMD_PALETTE.textDim)}</span>
      </div>
      {items.map((it, idx) => {
        const active = (it.k === "uebersicht" && activeView === "uebersicht") ||
                       (it.k === "energie" && activeView === "energie") ||
                       (it.k === "raum" && activeView === "raum") ||
                       (it.k === "kal" && activeView === "kal");
        const tourPulse = tourActive && idx === tourIdx;
        return (
          <button key={it.k} onClick={() => onNav && onNav(it.k)} title={it.label} style={{
            width: 40, height: 40, borderRadius: 10, border: 0, cursor: "pointer",
            background: active ? `${SMD_PALETTE.accent}1F` : "transparent",
            color: active ? SMD_PALETTE.accent : SMD_PALETTE.textDim,
            display: "flex", alignItems: "center", justifyContent: "center", padding: 0,
            transition: "all 0.15s",
            position: "relative",
            boxShadow: tourPulse ? `0 0 0 3px ${SMD_PALETTE.accent}55, 0 0 24px ${SMD_PALETTE.accent}88` : "none",
            transform: tourPulse ? "scale(1.08)" : "scale(1)",
          }}>
            {active && <span style={{
              position: "absolute", left: -10, top: 8, bottom: 8, width: 2,
              background: SMD_PALETTE.accent, borderRadius: 2,
            }}/>}
            <span style={{ display: "block", width: 20, height: 20 }}>
              {SMDIcons[it.icon] && SMDIcons[it.icon](active ? SMD_PALETTE.accent : SMD_PALETTE.textDim)}
            </span>
          </button>
        );
      })}

      {/* Tour cursor — visual hint that something is being clicked */}
      {tourActive && tourIdx >= 0 && (
        <div style={{
          position: "absolute",
          left: 32,
          top: 14 + 36 + 6 + tourIdx * 44 + 28,
          width: 18, height: 18,
          pointerEvents: "none",
          transition: "top 0.6s cubic-bezier(0.4, 0, 0.2, 1)",
          zIndex: 5,
        }}>
          <svg viewBox="0 0 24 24" width="18" height="18">
            <path d="M5 3 L5 19 L9 15 L11.5 21 L14 20 L11.5 14 L17 14 Z"
                  fill={SMD_PALETTE.accent} stroke={SMD_PALETTE.bgDeep} strokeWidth="1.2"
                  style={{ filter: `drop-shadow(0 2px 6px ${SMD_PALETTE.accent}88)` }}/>
          </svg>
        </div>
      )}
    </aside>
  );
}

// ── Top action bar ─────────────────────────────────────────────
function SMDTopBar({ title, back, onBack, tabs, activeTab, onTab }) {
  return (
    <div className="smd-topbar" style={{
      display: "flex", alignItems: "center",
      borderBottom: `1px solid ${SMD_PALETTE.border}`,
      padding: "0 24px", height: 52, gap: 16, flexShrink: 0,
      background: SMD_PALETTE.bgDeep,
    }}>
      {back && (
        <button onClick={onBack} style={{
          width: 32, height: 32, borderRadius: 8, border: 0, background: "transparent",
          color: SMD_PALETTE.text, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <span style={{ display: "block", width: 20, height: 20 }}>{SMDIcons.arrowL(SMD_PALETTE.text)}</span>
        </button>
      )}
      {!tabs && (
        <div style={{ fontSize: 17, fontWeight: 500, color: SMD_PALETTE.text, fontFamily: "Inter, sans-serif" }}>
          {title}
        </div>
      )}
      {tabs && (
        <div className="smd-tabs" style={{ display: "flex", gap: 0, alignItems: "stretch", height: "100%" }}>
          {tabs.map((t) => (
            <button key={t} onClick={() => onTab(t)} style={{
              padding: "0 16px", border: 0, background: "transparent",
              color: activeTab === t ? SMD_PALETTE.text : SMD_PALETTE.textDim,
              fontSize: 13, fontWeight: 500, fontFamily: "Inter, sans-serif",
              cursor: "pointer", borderBottom: `2px solid ${activeTab === t ? SMD_PALETTE.accent : "transparent"}`,
              marginBottom: -1,
            }}>{t}</button>
          ))}
        </div>
      )}
      <div style={{ flex: 1 }}/>
      <div className="smd-topbar-actions" style={{ display: "flex", gap: 4, color: SMD_PALETTE.textDim }}>
        {["plus", "search", "msg", "edit"].map((k) => (
          <button key={k} style={{
            width: 32, height: 32, borderRadius: 8, border: 0, background: "transparent",
            color: SMD_PALETTE.textDim, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <span style={{ display: "block", width: 18, height: 18 }}>{SMDIcons[k] && SMDIcons[k](SMD_PALETTE.textDim)}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

// ── Übersicht View ─────────────────────────────────────────────
function SMDOverview({ data, onRoom }) {
  return (
    <div style={{ padding: "28px 32px 60px", overflowY: "auto", flex: 1 }}>
      <h2 style={{
        fontSize: 22, fontWeight: 500, margin: "0 0 24px", color: SMD_PALETTE.text,
        fontFamily: "Outfit, sans-serif", letterSpacing: "-0.01em",
      }}>Willkommen {data.welcome}</h2>

      <div className="smd-ov" style={{ display: "grid", gridTemplateColumns: "1fr 280px", gap: 32 }}>
        {/* Left column */}
        <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
          {/* Favoriten */}
          <div>
            <h3 style={{
              fontSize: 12, textTransform: "uppercase", letterSpacing: "0.12em",
              color: SMD_PALETTE.textDim, fontWeight: 500, margin: "0 0 12px",
              fontFamily: "JetBrains Mono, monospace",
            }}>Favoriten</h3>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(140px, 1fr))", gap: 10 }}>
              {data.favorites.map((f) => (
                <SMDTile key={f.id} {...f}/>
              ))}
            </div>
          </div>

          {/* Floors */}
          {data.floors.map((floor) => (
            <div key={floor.name}>
              <h3 style={{
                fontSize: 12, textTransform: "uppercase", letterSpacing: "0.12em",
                color: SMD_PALETTE.textDim, fontWeight: 500, margin: "0 0 12px",
                fontFamily: "JetBrains Mono, monospace",
                display: "flex", alignItems: "center", gap: 8,
              }}>
                <span style={{ display: "block", width: 14, height: 14, color: SMD_PALETTE.textDim }}>
                  {SMDIcons[floor.icon] && SMDIcons[floor.icon](SMD_PALETTE.textDim)}
                </span>
                {floor.name}
              </h3>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(130px, 1fr))", gap: 10 }}>
                {floor.rooms.map((r) => (
                  <SMDTile key={r.id} icon={r.icon} name={r.name} state={r.state}
                           on={true} color={SMD_PALETTE.soft}
                           onClick={() => onRoom && onRoom(r)}/>
                ))}
              </div>
            </div>
          ))}
        </div>

        {/* Right rail */}
        <div>
          <h3 style={{
            fontSize: 12, textTransform: "uppercase", letterSpacing: "0.12em",
            color: SMD_PALETTE.textDim, fontWeight: 500, margin: "0 0 12px",
            fontFamily: "JetBrains Mono, monospace",
          }}>Zusammenfassungen</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {data.summaries.map((s, i) => <SMDSummaryRow key={i} {...s}/>)}
          </div>
        </div>
      </div>
    </div>
  );
}

const SMD_COMMERCIAL_ROOM_DETAILS = {
  werkstatt: {
    pill: { icon: "wrench", text: "5 Mitarbeiter · KUKA Roboter 1 bereit", color: SMD_PALETTE.accent },
    stats: [
      { icon: "chart", name: "Tagesumsatz", state: "€ 8.420", color: SMD_PALETTE.battery },
      { icon: "presence", name: "Anwesenheit", state: "5 / 6 Mitarbeiter", color: SMD_PALETTE.accent },
      { icon: "factory", name: "KUKA Roboter 1", state: "Bereit · Auto", color: SMD_PALETTE.pv },
    ],
    panels: [
      { title: "Maschinen & Anlagen", tiles: [
        { icon: "factory", name: "KUKA Roboter 1", state: "Auto · Zyklus 42 s", color: SMD_PALETTE.pv },
        { icon: "wrench", name: "CNC Fräse", state: "Standby", color: SMD_PALETTE.soft },
        { icon: "bolt", name: "Druckluft", state: "7,8 bar · OK", color: SMD_PALETTE.battery },
      ]},
      { title: "Personal & Aufträge", tiles: [
        { icon: "presence", name: "Mitarbeiter", state: "5 anwesend", color: SMD_PALETTE.accent },
        { icon: "list", name: "Auftrag SM-2418", state: "76% fertig", color: SMD_PALETTE.battery },
        { icon: "chart", name: "Heute fakturierbar", state: "€ 8.420", color: SMD_PALETTE.pv },
      ]},
      { title: "Energie & Sicherheit", tiles: [
        { icon: "bolt", name: "Werkstatt-Leistung", state: "4,8 kW", color: SMD_PALETTE.pv },
        { icon: "shield", name: "Roboterzelle", state: "Tür verriegelt", color: SMD_PALETTE.battery },
        { icon: "weather", name: "Absaugung", state: "Läuft · Filter OK", color: SMD_PALETTE.water },
      ]},
    ],
    scenes: [
      { id: "start", name: "Werkstatt Start", state: "Licht, Druckluft, Absaugung" },
      { id: "pause", name: "Pause", state: "Roboter safe, Druckluft reduziert" },
      { id: "schluss", name: "Feierabend", state: "Alles aus, Alarm scharf" },
    ],
    automations: [
      { icon: "flow", name: "KUKA Störung", state: "Push + Licht rot", color: SMD_PALETTE.warm },
      { icon: "flow", name: "Druckluft Nacht", state: "Leckage-Warnung aktiv", color: SMD_PALETTE.battery },
      { icon: "flow", name: "Tagesumsatz Snapshot", state: "17:00 Report", color: SMD_PALETTE.accent },
    ],
  },
  produktion: {
    pill: { icon: "factory", text: "12 Mitarbeiter · Linie läuft", color: SMD_PALETTE.pv },
    stats: [
      { icon: "chart", name: "Tagesumsatz", state: "€ 16.440", color: SMD_PALETTE.battery },
      { icon: "presence", name: "Anwesenheit", state: "12 / 14 Mitarbeiter", color: SMD_PALETTE.accent },
      { icon: "bolt", name: "Leistung jetzt", state: "18,6 kW", color: SMD_PALETTE.pv },
    ],
    panels: [
      { title: "Linie & Maschinen", tiles: [
        { icon: "factory", name: "Linie 1", state: "Produktion", color: SMD_PALETTE.battery },
        { icon: "factory", name: "KUKA Roboter 2", state: "Auto · 97%", color: SMD_PALETTE.pv },
        { icon: "wrench", name: "Kompressor", state: "OK · 7,9 bar", color: SMD_PALETTE.water },
      ]},
      { title: "Schicht & Leistung", tiles: [
        { icon: "presence", name: "Schicht A", state: "12 anwesend", color: SMD_PALETTE.accent },
        { icon: "list", name: "Stückzahl heute", state: "842 Teile", color: SMD_PALETTE.battery },
        { icon: "chart", name: "OEE", state: "86%", color: SMD_PALETTE.pv },
      ]},
      { title: "Umgebung", tiles: [
        { icon: "thermo", name: "Hallentemperatur", state: "20,8 °C", color: SMD_PALETTE.warm },
        { icon: "weather", name: "Luftqualität", state: "CO₂ 612 ppm", color: SMD_PALETTE.water },
        { icon: "shield", name: "Sicherheitskreis", state: "Geschlossen", color: SMD_PALETTE.battery },
      ]},
    ],
    scenes: [
      { id: "schichtstart", name: "Schichtstart", state: "Linie freigeben" },
      { id: "störung", name: "Störung", state: "Warnlicht + Eskalation" },
      { id: "reinigung", name: "Reinigung", state: "Maschinen safe" },
    ],
    automations: [
      { icon: "flow", name: "Lastspitze Produktion", state: "Aktiv", color: SMD_PALETTE.pv },
      { icon: "flow", name: "Störung Linie 1", state: "Eskalation aktiv", color: SMD_PALETTE.warm },
      { icon: "flow", name: "Schichtreport", state: "15:00 / 23:00", color: SMD_PALETTE.accent },
    ],
  },
  lager: {
    pill: { icon: "garage", text: "2 Mitarbeiter · Tore überwacht", color: SMD_PALETTE.soft },
    stats: [
      { icon: "chart", name: "Warenausgang", state: "€ 6.120", color: SMD_PALETTE.battery },
      { icon: "presence", name: "Anwesenheit", state: "2 Mitarbeiter", color: SMD_PALETTE.accent },
      { icon: "garage", name: "Tore", state: "Tor 1 zu · Tor 2 offen", color: SMD_PALETTE.warm },
    ],
    panels: [
      { title: "Logistik", tiles: [
        { icon: "garage", name: "Tor 1", state: "Geschlossen", color: SMD_PALETTE.battery },
        { icon: "garage", name: "Tor 2", state: "Offen seit 6 min", color: SMD_PALETTE.warm },
        { icon: "list", name: "Kommissionierung", state: "14 / 21 erledigt", color: SMD_PALETTE.accent },
      ]},
      { title: "Bestand & Klima", tiles: [
        { icon: "thermo", name: "Lagertemperatur", state: "18,4 °C", color: SMD_PALETTE.warm },
        { icon: "weather", name: "Luftfeuchte", state: "46%", color: SMD_PALETTE.water },
        { icon: "shield", name: "Nachtmodus", state: "Automatisch", color: SMD_PALETTE.battery },
      ]},
      { title: "Energie", tiles: [
        { icon: "bolt", name: "Lager Verbrauch", state: "1,9 kW", color: SMD_PALETTE.pv },
        { icon: "light", name: "Licht Gänge", state: "Präsenzgeführt", color: SMD_PALETTE.pv },
        { icon: "flow", name: "Tor-Heizung", state: "Aus", color: SMD_PALETTE.soft },
      ]},
    ],
    scenes: [
      { id: "warenannahme", name: "Warenannahme", state: "Tor + Licht" },
      { id: "kommission", name: "Kommissionierung", state: "Zonenlicht aktiv" },
      { id: "lager-nacht", name: "Lager Nacht", state: "Tore prüfen" },
    ],
    automations: [
      { icon: "flow", name: "Tor offen > 10 min", state: "Warnung aktiv", color: SMD_PALETTE.warm },
      { icon: "flow", name: "Lagerlicht Präsenz", state: "Aktiv", color: SMD_PALETTE.battery },
      { icon: "flow", name: "Warenausgang Report", state: "17:30", color: SMD_PALETTE.accent },
    ],
  },
  buero: {
    pill: { icon: "desk", text: "8 Mitarbeiter · Raumklima OK", color: SMD_PALETTE.accent },
    stats: [
      { icon: "chart", name: "Tagesumsatz", state: "€ 9.310", color: SMD_PALETTE.battery },
      { icon: "presence", name: "Anwesenheit", state: "8 / 10 Mitarbeiter", color: SMD_PALETTE.accent },
      { icon: "thermo", name: "Klima Büros", state: "21,8 °C", color: SMD_PALETTE.warm },
    ],
    panels: [
      { title: "Bürokomfort", tiles: [
        { icon: "light", name: "Arbeitslicht", state: "Automatik", color: SMD_PALETTE.pv },
        { icon: "thermo", name: "Heizung/Kühlung", state: "21,8 °C", color: SMD_PALETTE.warm },
        { icon: "weather", name: "CO₂", state: "684 ppm", color: SMD_PALETTE.water },
      ]},
      { title: "Team & Zutritt", tiles: [
        { icon: "presence", name: "Mitarbeiter", state: "8 anwesend", color: SMD_PALETTE.accent },
        { icon: "lock", name: "Büro-Zutritt", state: "Offen bis 18:00", color: SMD_PALETTE.battery },
        { icon: "cal", name: "Besprechung", state: "14:00 belegt", color: SMD_PALETTE.soft },
      ]},
      { title: "Betrieb", tiles: [
        { icon: "bolt", name: "Büro-Verbrauch", state: "2,1 kW", color: SMD_PALETTE.pv },
        { icon: "server", name: "UniFi Netzwerk", state: "Online", color: SMD_PALETTE.battery },
        { icon: "chart", name: "Anfragen heute", state: "18", color: SMD_PALETTE.accent },
      ]},
    ],
    scenes: [
      { id: "arbeit", name: "Arbeitszeit", state: "Licht + Klima" },
      { id: "meeting", name: "Meeting", state: "Beschattung + Display" },
      { id: "büro-aus", name: "Feierabend", state: "Standby + Zutritt" },
    ],
    automations: [
      { icon: "flow", name: "CO₂ Meetingraum", state: "Aktiv", color: SMD_PALETTE.water },
      { icon: "flow", name: "Büro Feierabend", state: "18:15", color: SMD_PALETTE.battery },
      { icon: "flow", name: "Umsatz-Snapshot", state: "16:00", color: SMD_PALETTE.accent },
    ],
  },
};

function getSMDCommercialProfile(room) {
  const id = room?.id || "";
  if (SMD_COMMERCIAL_ROOM_DETAILS[id]) return SMD_COMMERCIAL_ROOM_DETAILS[id];
  if (/buero|besprech|empfang|kueche/.test(id)) return SMD_COMMERCIAL_ROOM_DETAILS.buero;
  if (/lager|ausgabe/.test(id)) return SMD_COMMERCIAL_ROOM_DETAILS.lager;
  if (/produktion/.test(id)) return SMD_COMMERCIAL_ROOM_DETAILS.produktion;
  return SMD_COMMERCIAL_ROOM_DETAILS.werkstatt;
}

function SMDCommercialRoomDetail({ room }) {
  const profile = getSMDCommercialProfile(room);
  const [scene, setScene] = React.useState(profile.scenes[0]?.id || "start");
  React.useEffect(() => {
    setScene(profile.scenes[0]?.id || "start");
  }, [room?.id]);

  const Section = ({ title, children }) => (
    <div style={{ marginBottom: 22 }}>
      <h3 style={{
        fontSize: 13, fontWeight: 500, color: SMD_PALETTE.text, margin: "0 0 10px",
        fontFamily: "Inter, sans-serif", display: "flex", alignItems: "center", gap: 8,
      }}>
        {title}
        <span style={{ display: "block", width: 14, height: 14, color: SMD_PALETTE.textDim }}>{SMDIcons.chevR(SMD_PALETTE.textDim)}</span>
      </h3>
      {children}
    </div>
  );

  const PillIcon = SMDIcons[profile.pill.icon] || SMDIcons.factory;

  return (
    <div style={{ padding: "28px 32px 60px", overflowY: "auto", flex: 1 }}>
      <div style={{ display: "flex", justifyContent: "center", marginBottom: 24 }}>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          padding: "8px 16px", borderRadius: 100,
          background: SMD_PALETTE.bgCard,
          border: `1px solid ${SMD_PALETTE.border}`,
          fontSize: 13, color: SMD_PALETTE.text, fontFamily: "Inter, sans-serif",
        }}>
          <span style={{ display: "block", width: 14, height: 14, color: profile.pill.color }}>{PillIcon(profile.pill.color)}</span>
          <span>{profile.pill.text}</span>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: 10, marginBottom: 28 }}>
        {profile.stats.map((s) => (
          <SMDTile key={s.name} icon={s.icon} name={s.name} state={s.state} on={true} color={s.color} large />
        ))}
      </div>

      <div className="smd-g3" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 24, marginBottom: 26 }}>
        {profile.panels.map((panel) => (
          <Section key={panel.title} title={panel.title}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 8 }}>
              {panel.tiles.map((t) => (
                <SMDTile key={t.name} icon={t.icon} name={t.name} state={t.state} on={true} color={t.color} />
              ))}
            </div>
          </Section>
        ))}
      </div>

      <Section title="Szenen">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))", gap: 10 }}>
          {profile.scenes.map((s) => {
            const active = scene === s.id;
            return (
              <button key={s.id} onClick={() => setScene(s.id)} style={{
                background: active ? `${SMD_PALETTE.accent}14` : SMD_PALETTE.bgCard,
                border: `1px solid ${active ? SMD_PALETTE.borderHi : SMD_PALETTE.border}`,
                borderRadius: 10, padding: "10px 12px", display: "flex", alignItems: "center", gap: 10,
                cursor: "pointer", textAlign: "left", color: "inherit",
                transition: "all 0.15s",
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 6,
                  background: active ? `${SMD_PALETTE.accent}33` : "rgba(255,255,255,0.04)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  <span style={{ display: "block", width: 14, height: 14 }}>{SMDIcons.scenes(active ? SMD_PALETTE.accent : SMD_PALETTE.soft)}</span>
                </div>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 500, fontFamily: "Inter, sans-serif" }}>{s.name}</div>
                  <div style={{ fontSize: 10, color: SMD_PALETTE.textDim, fontFamily: "Inter, sans-serif" }}>{s.state}</div>
                </div>
              </button>
            );
          })}
        </div>
      </Section>

      <Section title="Automationen">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(160px, 1fr))", gap: 8 }}>
          {profile.automations.map((a) => (
            <SMDTile key={a.name} icon={a.icon} name={a.name} state={a.state} on={true} color={a.color} />
          ))}
        </div>
      </Section>
    </div>
  );
}

// ── Room Detail (Büro) ─────────────────────────────────────────
function SMDRoomDetail({ room, onBack }) {
  // Static deep-detail for "Büro" — works for all paths as a sample room
  const [scene, setScene] = React.useState("buero-hell");
  const [dim, setDim] = React.useState(5);
  const [temp, setTemp] = React.useState(5.0);

  const Section = ({ title, action, children }) => (
    <div style={{ marginBottom: 22 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
        <h3 style={{ fontSize: 13, fontWeight: 500, color: SMD_PALETTE.text, margin: 0, fontFamily: "Inter, sans-serif", display: "flex", alignItems: "center", gap: 8 }}>
          {title}
          <span style={{ display: "block", width: 14, height: 14, color: SMD_PALETTE.textDim }}>{SMDIcons.chevR(SMD_PALETTE.textDim)}</span>
        </h3>
        {action}
      </div>
      {children}
    </div>
  );

  return (
    <div style={{ padding: "28px 32px 60px", overflowY: "auto", flex: 1 }}>
      {/* temperature pill (centered) */}
      <div style={{ display: "flex", justifyContent: "center", marginBottom: 28 }}>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          padding: "8px 16px", borderRadius: 100,
          background: SMD_PALETTE.bgCard,
          border: `1px solid ${SMD_PALETTE.border}`,
          fontSize: 13, color: SMD_PALETTE.text, fontFamily: "Inter, sans-serif",
        }}>
          <span style={{ display: "block", width: 14, height: 14, color: SMD_PALETTE.warm }}>{SMDIcons.thermo(SMD_PALETTE.warm)}</span>
          <span>19,3 °C</span>
        </div>
      </div>

      <div className="smd-g3" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 24, marginBottom: 28 }}>
        {/* Beleuchtung */}
        <Section title="Beleuchtung" action={
          <span style={{
            fontSize: 11, padding: "3px 10px", borderRadius: 100,
            background: `${SMD_PALETTE.pv}22`, color: SMD_PALETTE.pv,
            display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "Inter, sans-serif", fontWeight: 500,
          }}>
            <span style={{ display: "block", width: 11, height: 11 }}>{SMDIcons.power(SMD_PALETTE.pv)}</span>
            Ein
          </span>
        }>
          <div style={{
            background: SMD_PALETTE.bgCard, border: `1px solid ${SMD_PALETTE.border}`,
            borderRadius: 12, padding: 14,
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <div style={{
                width: 30, height: 30, borderRadius: 999, background: `${SMD_PALETTE.pv}22`,
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                <span style={{ display: "block", width: 16, height: 16 }}>{SMDIcons.light(SMD_PALETTE.pv)}</span>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500, fontFamily: "Inter, sans-serif" }}>Decke Büro</div>
                <div style={{ fontSize: 11, color: SMD_PALETTE.textDim, fontFamily: "Inter, sans-serif" }}>{dim} %</div>
              </div>
            </div>
            <input type="range" min="0" max="100" value={dim} onChange={(e) => setDim(parseInt(e.target.value))} style={{
              width: "100%", height: 6, accentColor: SMD_PALETTE.pv, cursor: "pointer",
            }}/>
          </div>
        </Section>

        {/* Raumklima */}
        <Section title="Raumklima">
          <div style={{
            background: SMD_PALETTE.bgCard, border: `1px solid ${SMD_PALETTE.border}`,
            borderRadius: 12, padding: 14,
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
              <div style={{
                width: 30, height: 30, borderRadius: 999, background: `${SMD_PALETTE.warm}22`,
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                <span style={{ display: "block", width: 16, height: 16 }}>{SMDIcons.fire(SMD_PALETTE.warm)}</span>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500, fontFamily: "Inter, sans-serif" }}>Thermostat</div>
                <div style={{ fontSize: 11, color: SMD_PALETTE.textDim, fontFamily: "Inter, sans-serif" }}>Heizbetrieb</div>
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
              <button onClick={() => setTemp(Math.max(0, temp - 0.5))} style={{
                width: 32, height: 32, borderRadius: 8, border: `1px solid ${SMD_PALETTE.border}`,
                background: SMD_PALETTE.bgDeep, color: SMD_PALETTE.text, cursor: "pointer", fontSize: 16,
              }}>−</button>
              <div style={{ fontSize: 16, fontWeight: 500, fontFamily: "Inter, sans-serif" }}>{temp.toFixed(1)} °C</div>
              <button onClick={() => setTemp(temp + 0.5)} style={{
                width: 32, height: 32, borderRadius: 8, border: `1px solid ${SMD_PALETTE.border}`,
                background: SMD_PALETTE.bgDeep, color: SMD_PALETTE.text, cursor: "pointer", fontSize: 16,
              }}>+</button>
            </div>
          </div>
        </Section>

        {/* Mediaplayer */}
        <Section title="Mediaplayer">
          <div style={{
            background: SMD_PALETTE.bgCard, border: `1px solid ${SMD_PALETTE.border}`,
            borderRadius: 12, padding: 14, display: "flex", alignItems: "center", gap: 10,
          }}>
            <div style={{
              width: 30, height: 30, borderRadius: 8, background: `${SMD_PALETTE.accent}22`,
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              <span style={{ display: "block", width: 16, height: 16 }}>{SMDIcons.cast(SMD_PALETTE.accent)}</span>
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, fontFamily: "Inter, sans-serif" }}>Alexa Büro</div>
              <div style={{ fontSize: 11, color: SMD_PALETTE.textDim, fontFamily: "Inter, sans-serif" }}>Pausiert</div>
            </div>
          </div>
        </Section>
      </div>

      {/* Szenen */}
      <Section title="Szenen">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))", gap: 10 }}>
          {[
            { id: "nacht", name: "Nachtlicht", state: "Vor 3 Jahren" },
            { id: "buero-hell", name: "Büro Hell", state: "Vor 3 Jahren" },
            { id: "gedimmt", name: "Gedimmt", state: "Unbekannt" },
            { id: "fokus", name: "Fokus", state: "Letzte Woche" },
          ].map((s) => {
            const active = scene === s.id;
            return (
              <button key={s.id} onClick={() => setScene(s.id)} style={{
                background: active ? `${SMD_PALETTE.accent}14` : SMD_PALETTE.bgCard,
                border: `1px solid ${active ? SMD_PALETTE.borderHi : SMD_PALETTE.border}`,
                borderRadius: 10, padding: "10px 12px", display: "flex", alignItems: "center", gap: 10,
                cursor: "pointer", textAlign: "left", color: "inherit",
                transition: "all 0.15s",
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 6,
                  background: active ? `${SMD_PALETTE.accent}33` : "rgba(255,255,255,0.04)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  <span style={{ display: "block", width: 14, height: 14 }}>{SMDIcons.scenes(active ? SMD_PALETTE.accent : SMD_PALETTE.soft)}</span>
                </div>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 500, fontFamily: "Inter, sans-serif" }}>{s.name}</div>
                  <div style={{ fontSize: 10, color: SMD_PALETTE.textDim, fontFamily: "Inter, sans-serif" }}>{s.state}</div>
                </div>
              </button>
            );
          })}
        </div>
      </Section>

      {/* Hardware groups */}
      <div className="smd-g3" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 24, marginTop: 12 }}>
        <div>
          <h4 style={{ fontSize: 12, color: SMD_PALETTE.text, fontWeight: 500, margin: "0 0 8px", fontFamily: "Inter, sans-serif" }}>Hauptschalter Büro</h4>
          <div style={{ display: "flex", gap: 8 }}>
            <SMDTile icon="bolt" name="Verbrauch" state="780 W" on={true} color={SMD_PALETTE.consumption}/>
            <SMDTile icon="light" name="Switch 0" state="Ein" on={true} color={SMD_PALETTE.pv}/>
          </div>
        </div>
        <div>
          <h4 style={{ fontSize: 12, color: SMD_PALETTE.text, fontWeight: 500, margin: "0 0 8px", fontFamily: "Inter, sans-serif" }}>Thermostat — Detail</h4>
          <div style={{ display: "flex", gap: 8 }}>
            <SMDTile icon="valve" name="Ventil-Öffnung" state="0,0 %" on={true} color={SMD_PALETTE.water}/>
            <SMDTile icon="thermo" name="Temperatur" state="19,3 °C" on={true} color={SMD_PALETTE.warm}/>
          </div>
        </div>
        <div>
          <h4 style={{ fontSize: 12, color: SMD_PALETTE.text, fontWeight: 500, margin: "0 0 8px", fontFamily: "Inter, sans-serif" }}>Präsenz Büro</h4>
          <div style={{ display: "flex", gap: 8 }}>
            <SMDTile icon="presence" name="Anwesenheit" state="Zuhause" on={true} color={SMD_PALETTE.battery}/>
            <SMDTile icon="weather" name="Beleuchtung" state="153,9 lx" on={true} color={SMD_PALETTE.pv}/>
          </div>
        </div>
      </div>

      {/* Automation */}
      <div style={{ marginTop: 22 }}>
        <h4 style={{ fontSize: 12, color: SMD_PALETTE.text, fontWeight: 500, margin: "0 0 8px", fontFamily: "Inter, sans-serif", display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ display: "block", width: 14, height: 14, color: SMD_PALETTE.textDim }}>{SMDIcons.flow(SMD_PALETTE.textDim)}</span>
          Automationen
        </h4>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(140px, 1fr))", gap: 8 }}>
          <SMDTile icon="flow" name="Licht Büro" state="Aktiv" on={true} color={SMD_PALETTE.battery}/>
          <SMDTile icon="flow" name="Heizung Büro" state="Aktiv" on={true} color={SMD_PALETTE.battery}/>
          <SMDTile icon="flow" name="Anwesenheit" state="Aktiv" on={true} color={SMD_PALETTE.battery}/>
        </div>
      </div>
    </div>
  );
}

// ── Energy distribution diagram ────────────────────────────────
function SMDEnergyDist({ e }) {
  // 4 nodes around center "Home" — PV top, Water right, Battery bottom, Grid left
  const cx = 220, cy = 200;
  const nodeR = 38;
  const dist = 130;
  const nodes = {
    pv: { x: cx, y: cy - dist, label: "PV", value: `${e.pv.toFixed(1)} kWh`, color: SMD_PALETTE.pv, icon: "bolt" },
    water: { x: cx + dist, y: cy, label: "Wasser", value: `${e.water.toFixed(0)} L`, color: SMD_PALETTE.water, icon: "drop" },
    battery: { x: cx, y: cy + dist, label: "Batterie", value: `${e.battery > 0 ? '↓' : '↑'} ${Math.abs(e.battery).toFixed(2)} kWh`, color: SMD_PALETTE.warm, icon: "bolt" },
    grid: { x: cx - dist, y: cy, label: "Netz", value: `${e.grid > 0 ? '→' : '←'} ${Math.abs(e.grid).toFixed(2)} kWh`, color: SMD_PALETTE.grid, icon: "factory" },
    home: { x: cx, y: cy, label: "Home", value: `${e.home.toFixed(1)} kWh`, color: SMD_PALETTE.accent, icon: "home" },
  };

  const Node = ({ n, big }) => {
    const r = big ? nodeR : nodeR;
    const Icon = SMDIcons[n.icon];
    return (
      <g>
        <circle cx={n.x} cy={n.y} r={r} fill="none" stroke={n.color} strokeWidth="2"/>
        <circle cx={n.x} cy={n.y} r={r-2} fill={SMD_PALETTE.bgDeep}/>
        <foreignObject x={n.x - r + 4} y={n.y - 18} width={r*2 - 8} height={36} style={{ pointerEvents: "none" }}>
          <div style={{
            width: "100%", height: "100%", display: "flex", flexDirection: "column",
            alignItems: "center", justifyContent: "center", textAlign: "center",
            fontFamily: "Inter, sans-serif", color: n.color,
          }}>
            <span style={{ display: "block", width: 14, height: 14, marginBottom: 1 }}>{Icon && Icon(n.color)}</span>
            <div style={{ fontSize: 10, fontWeight: 600, color: n.color, lineHeight: 1.1 }}>{n.value}</div>
          </div>
        </foreignObject>
        <text x={n.x} y={n.y + r + 16} fill={SMD_PALETTE.textDim} fontSize="11" textAnchor="middle" fontFamily="Inter, sans-serif">{n.label}</text>
      </g>
    );
  };

  // curved paths between nodes (PV→Home, Battery→Home, Grid→Home, Water→Home)
  const Path = ({ from, to, color, dashed }) => {
    const fx = from.x, fy = from.y, tx = to.x, ty = to.y;
    // simple quadratic curve toward center
    const mx = (fx + tx) / 2, my = (fy + ty) / 2;
    return (
      <path d={`M${fx},${fy} Q${mx},${my} ${tx},${ty}`}
            stroke={color} strokeWidth="1.8" fill="none"
            strokeDasharray={dashed ? "4 4" : "none"}
            opacity="0.5"/>
    );
  };

  // animated dots along path (approx via small circles + animateMotion)
  const FlowDot = ({ from, to, color, dur = 3 }) => (
    <circle r="3" fill={color}>
      <animateMotion dur={`${dur}s`} repeatCount="indefinite"
                     path={`M${from.x - to.x},${from.y - to.y} Q${(from.x - to.x)/2},${(from.y - to.y)/2} 0,0`}/>
      <animate attributeName="cx" from={from.x} to={to.x} dur={`${dur}s`} repeatCount="indefinite"/>
      <animate attributeName="cy" from={from.y} to={to.y} dur={`${dur}s`} repeatCount="indefinite"/>
    </circle>
  );

  return (
    <svg viewBox="0 0 440 400" width="100%" height="100%" preserveAspectRatio="xMidYMid meet">
      <Path from={nodes.pv} to={nodes.home} color={SMD_PALETTE.pv}/>
      <Path from={nodes.battery} to={nodes.home} color={SMD_PALETTE.warm}/>
      <Path from={nodes.grid} to={nodes.home} color={SMD_PALETTE.grid}/>
      <Path from={nodes.water} to={nodes.home} color={SMD_PALETTE.water} dashed/>

      <FlowDot from={nodes.pv} to={nodes.home} color={SMD_PALETTE.pv} dur={2.4}/>
      <FlowDot from={nodes.home} to={nodes.grid} color={SMD_PALETTE.grid} dur={3.0}/>
      <FlowDot from={nodes.battery} to={nodes.home} color={SMD_PALETTE.warm} dur={3.8}/>

      <Node n={nodes.pv}/>
      <Node n={nodes.water}/>
      <Node n={nodes.battery}/>
      <Node n={nodes.grid}/>
      <Node n={nodes.home} big/>
    </svg>
  );
}

// ── Bar chart (stacked-ish) ────────────────────────────────────
function SMDBarChart({ values, colors, height = 180, max, min = 0, suffix = "kW", label }) {
  // values: array of {pos: [up bars], neg: [down bars]} per timestep
  const w = 520, h = height;
  const padL = 36, padR = 12, padT = 12, padB = 22;
  const innerH = h - padT - padB;
  const innerW = w - padL - padR;
  const range = max - min;
  const zeroY = padT + (max / range) * innerH;
  const barW = innerW / values.length * 0.6;
  const slot = innerW / values.length;

  const yTicks = [];
  const tickStep = (max - min) / 4;
  for (let i = 0; i <= 4; i++) {
    const v = max - tickStep * i;
    yTicks.push({ v: Number(v.toFixed(1)), y: padT + (i / 4) * innerH });
  }

  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" style={{ display: "block" }}>
      {/* y-axis ticks + grid */}
      {yTicks.map((t, i) => (
        <g key={i}>
          <line x1={padL} y1={t.y} x2={w - padR} y2={t.y} stroke={SMD_PALETTE.border} strokeWidth="0.8"/>
          <text x={padL - 6} y={t.y + 3} fill={SMD_PALETTE.textDim} fontSize="9" textAnchor="end" fontFamily="Inter, sans-serif">{t.v}</text>
        </g>
      ))}
      {/* unit */}
      <text x={padL - 24} y={padT - 2} fill={SMD_PALETTE.textDim} fontSize="9" fontFamily="Inter, sans-serif">{suffix}</text>

      {/* bars */}
      {values.map((step, i) => {
        const x = padL + slot * i + (slot - barW) / 2;
        let yPos = zeroY;
        let yNeg = zeroY;
        return (
          <g key={i}>
            {step.pos && step.pos.map((seg, j) => {
              const segH = (seg / range) * innerH;
              yPos -= segH;
              return <rect key={"p"+j} x={x} y={yPos} width={barW} height={segH} fill={colors[j]} opacity="0.85"/>;
            })}
            {step.neg && step.neg.map((seg, j) => {
              const segH = (Math.abs(seg) / range) * innerH;
              const r = <rect key={"n"+j} x={x} y={yNeg} width={barW} height={segH} fill={colors[j + (step.pos ? step.pos.length : 0)] || SMD_PALETTE.consumption} opacity="0.85"/>;
              yNeg += segH;
              return r;
            })}
          </g>
        );
      })}

      {/* x labels (every 4th) */}
      {values.map((_, i) => i % 4 === 0 && (
        <text key={"x"+i} x={padL + slot * i + slot / 2} y={h - 6}
              fill={SMD_PALETTE.textDim} fontSize="9" textAnchor="middle" fontFamily="Inter, sans-serif">
          {`${i}:00`}
        </text>
      ))}
    </svg>
  );
}

// ── Area chart (PV vs grid) ────────────────────────────────────
function SMDAreaChart({ height = 180 }) {
  const w = 520, h = height;
  const padL = 36, padR = 12, padT = 12, padB = 22;
  const innerH = h - padT - padB;
  const innerW = w - padL - padR;

  // Bell curve PV + smaller grid line
  const N = 24;
  const pv = Array.from({length: N}, (_, i) => {
    const x = (i - 12) / 5;
    return Math.max(0, 12 * Math.exp(-x*x) + (Math.random() - 0.5) * 1.2);
  });
  pv[0] = 0; pv[N-1] = 0; pv[3] = 0; pv[4] = 0.4; pv[5] = 1.2;
  const grid = pv.map((v, i) => i > 6 && i < 14 ? Math.max(0, v - 4 - Math.random()) : v * 0.3);

  const max = 14;
  const toX = (i) => padL + (i / (N-1)) * innerW;
  const toY = (v) => padT + innerH - (v / max) * innerH;

  const pvPath = pv.map((v, i) => `${i === 0 ? 'M' : 'L'}${toX(i)},${toY(v)}`).join(" ") +
                 ` L${toX(N-1)},${toY(0)} L${toX(0)},${toY(0)} Z`;
  const gridPath = grid.map((v, i) => `${i === 0 ? 'M' : 'L'}${toX(i)},${toY(v)}`).join(" ") +
                   ` L${toX(N-1)},${toY(0)} L${toX(0)},${toY(0)} Z`;

  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" style={{ display: "block" }}>
      {[0, 4, 8, 12, 14].map((v, i) => {
        const y = toY(v);
        return (
          <g key={i}>
            <line x1={padL} y1={y} x2={w - padR} y2={y} stroke={SMD_PALETTE.border} strokeWidth="0.8"/>
            <text x={padL - 6} y={y + 3} fill={SMD_PALETTE.textDim} fontSize="9" textAnchor="end" fontFamily="Inter, sans-serif">{v}</text>
          </g>
        );
      })}
      <text x={padL - 24} y={padT - 2} fill={SMD_PALETTE.textDim} fontSize="9" fontFamily="Inter, sans-serif">kW</text>

      <path d={pvPath} fill={SMD_PALETTE.pv} opacity="0.5"/>
      <path d={gridPath} fill={SMD_PALETTE.grid} opacity="0.4"/>
      <path d={pv.map((v, i) => `${i === 0 ? 'M' : 'L'}${toX(i)},${toY(v)}`).join(" ")}
            fill="none" stroke={SMD_PALETTE.pv} strokeWidth="1.5"/>

      {[0, 4, 8, 12, 16, 20].map((hr, i) => (
        <text key={i} x={padL + (hr / 24) * innerW} y={h - 6}
              fill={SMD_PALETTE.textDim} fontSize="9" textAnchor="middle" fontFamily="Inter, sans-serif">{`${hr}:00`}</text>
      ))}
    </svg>
  );
}

// ── Energy Source row ──────────────────────────────────────────
function SMDQuelle({ color, name, value, cost }) {
  return (
    <div style={{
      display: "grid", gridTemplateColumns: "16px 1fr auto auto", gap: 12,
      alignItems: "center", padding: "10px 4px",
      borderBottom: `1px solid ${SMD_PALETTE.border}`,
      fontFamily: "Inter, sans-serif",
    }}>
      <div style={{ width: 14, height: 14, borderRadius: 3, background: color }}/>
      <div style={{ fontSize: 12, color: SMD_PALETTE.text }}>{name}</div>
      <div style={{ fontSize: 12, color: SMD_PALETTE.text, fontVariantNumeric: "tabular-nums" }}>{value}</div>
      <div style={{ fontSize: 12, color: SMD_PALETTE.textDim, fontVariantNumeric: "tabular-nums", minWidth: 40, textAlign: "right" }}>{cost}</div>
    </div>
  );
}

// ── Energy View ────────────────────────────────────────────────
function SMDEnergyView({ data }) {
  const e = data.energy;

  // build mock bar data
  const N = 24;
  const usage = Array.from({length: N}, (_, i) => {
    const isDay = i > 6 && i < 18;
    return {
      pos: isDay ? [Math.max(0, (Math.random()-0.5) * 2 + 1.2)] : [0],
      neg: !isDay ? [-Math.random() * 1.2 - 0.3] : [],
    };
  });

  return (
    <div style={{ padding: "20px 24px 60px", overflowY: "auto", flex: 1 }}>
      <div className="smd-g2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
        {/* Energieverteilung */}
        <div style={{
          background: SMD_PALETTE.bgCard, border: `1px solid ${SMD_PALETTE.border}`,
          borderRadius: 12, padding: 16,
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
            <h3 style={{ fontSize: 13, fontWeight: 500, margin: 0, fontFamily: "Inter, sans-serif" }}>Energieverteilung</h3>
            <span style={{ display: "block", width: 13, height: 13, color: SMD_PALETTE.textDim }}>{SMDIcons.chevR(SMD_PALETTE.textDim)}</span>
          </div>
          <div style={{ height: 360 }}>
            <SMDEnergyDist e={e}/>
          </div>
        </div>

        {/* Quellen-Tabelle + KPIs */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{
            background: SMD_PALETTE.bgCard, border: `1px solid ${SMD_PALETTE.border}`,
            borderRadius: 12, padding: 16,
          }}>
            <h3 style={{ fontSize: 13, fontWeight: 500, margin: "0 0 8px", fontFamily: "Inter, sans-serif" }}>Quellen</h3>
            <div style={{
              display: "grid", gridTemplateColumns: "16px 1fr auto auto", gap: 12,
              fontSize: 10, color: SMD_PALETTE.textDim, fontFamily: "Inter, sans-serif",
              padding: "0 4px 6px", borderBottom: `1px solid ${SMD_PALETTE.border}`,
              textTransform: "uppercase", letterSpacing: "0.08em",
            }}>
              <div/><div>Quelle</div><div style={{ textAlign: "right" }}>Verbrauch</div><div style={{ textAlign: "right" }}>Kosten</div>
            </div>
            <SMDQuelle color={SMD_PALETTE.pv} name="PV gesamt" value={`${e.pv.toFixed(2)} kWh`} cost=""/>
            <SMDQuelle color={SMD_PALETTE.battery} name="Batterie gesamt" value={`${e.battery > 0 ? '−' : ''}${Math.abs(e.battery).toFixed(2)} kWh`} cost=""/>
            <SMDQuelle color={SMD_PALETTE.grid} name="Netz gesamt" value={`${e.grid.toFixed(2)} kWh`} cost={`${e.gridCost.toFixed(2)} €`}/>
            <SMDQuelle color={SMD_PALETTE.water} name="Wasser gesamt" value={`${e.water.toFixed(1)} L`} cost=""/>
          </div>

          {/* KPI gauges */}
          <div className="smd-g2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <SMDGauge value={e.einspeisung} max={50} label="Netz eingespeist" suffix=" kWh" color={SMD_PALETTE.consumption}/>
            <SMDGauge value={e.eigenverbrauch} max={100} label="PV-Eigenverbrauch" suffix=" %" color={SMD_PALETTE.pv}/>
          </div>
          <SMDGauge value={e.autarkie} max={100} label="Autarkiegrad" suffix=" %" color={SMD_PALETTE.battery} wide/>
        </div>
      </div>

      {/* Charts row */}
      <div className="smd-g2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div style={{
          background: SMD_PALETTE.bgCard, border: `1px solid ${SMD_PALETTE.border}`,
          borderRadius: 12, padding: 16,
        }}>
          <h3 style={{ fontSize: 13, fontWeight: 500, margin: "0 0 12px", fontFamily: "Inter, sans-serif" }}>Stromquellen</h3>
          <SMDAreaChart/>
        </div>
        <div style={{
          background: SMD_PALETTE.bgCard, border: `1px solid ${SMD_PALETTE.border}`,
          borderRadius: 12, padding: 16,
        }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
            <h3 style={{ fontSize: 13, fontWeight: 500, margin: 0, fontFamily: "Inter, sans-serif" }}>Stromnutzung</h3>
            <span style={{
              fontSize: 11, color: SMD_PALETTE.battery, fontFamily: "JetBrains Mono, monospace",
              background: `${SMD_PALETTE.battery}1F`, padding: "3px 8px", borderRadius: 100,
            }}>+{e.home.toFixed(1)} kWh</span>
          </div>
          <SMDBarChart values={usage} max={3} min={-3}
                       colors={[SMD_PALETTE.pv, SMD_PALETTE.consumption, SMD_PALETTE.warm]}
                       suffix="kWh"/>
        </div>
      </div>

      {/* Per-device consumption */}
      <div style={{
        background: SMD_PALETTE.bgCard, border: `1px solid ${SMD_PALETTE.border}`,
        borderRadius: 12, padding: 16, marginTop: 16,
      }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
          <h3 style={{ fontSize: 13, fontWeight: 500, margin: 0, fontFamily: "Inter, sans-serif" }}>Gesamtverbrauch · Einzelgeräte</h3>
          <span style={{
            fontSize: 10, color: SMD_PALETTE.textDim, fontFamily: "JetBrains Mono, monospace",
            letterSpacing: "0.1em", textTransform: "uppercase",
          }}>Heute · pro Gerät</span>
        </div>
        <SMDDeviceList />
      </div>
    </div>
  );
}

const SMD_DEVICES = [
  { name: "Büro EG",              color: "#C8A88A", kwh: 4.3 },
  { name: "Werkstatt",            color: "#E89BB4", kwh: 2.8 },
  { name: "Küche & Esszimmer",    color: "#7AA8E0", kwh: 1.4 },
  { name: "Speisekammer",         color: "#7DBC7D", kwh: 1.2 },
  { name: "Wärmepumpe",           color: "#A0AED9", kwh: 0.7 },
  { name: "Büro OG",              color: "#5DC8A8", kwh: 0.6 },
  { name: "Audio Wohnzimmer",     color: "#E8C76E", kwh: 0.45 },
  { name: "Saugroboter",          color: "#5DC8A8", kwh: 0.4 },
  { name: "Mediawand",            color: "#9DD9C2", kwh: 0.32 },
  { name: "Badezimmer",           color: "#A8D5E8", kwh: 0.22 },
  { name: "Kaffeemaschine",       color: "#E07B6B", kwh: 0.18 },
  { name: "Außenbeleuchtung",     color: "#B89DDB", kwh: 0.12 },
  { name: "Sauna",                color: "#C29DD9", kwh: 0.08 },
  { name: "Waschmaschine",        color: "#E8C76E", kwh: 0.05 },
];

function SMDDeviceList() {
  const max = Math.max(...SMD_DEVICES.map(d => d.kwh));
  const labelW = 168;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      {SMD_DEVICES.map((d, i) => {
        const pct = (d.kwh / max) * 100;
        return (
          <div key={i} style={{
            display: "grid", gridTemplateColumns: `${labelW}px 1fr 56px`,
            alignItems: "center", gap: 12,
          }}>
            <div style={{
              fontSize: 12, color: SMD_PALETTE.text, fontFamily: "Inter, sans-serif",
              textAlign: "right", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
              opacity: 0.92,
            }}>{d.name}</div>
            <div style={{ position: "relative", height: 16, background: "rgba(141,219,234,0.05)", borderRadius: 3 }}>
              <div style={{
                position: "absolute", left: 0, top: 0, bottom: 0,
                width: `${pct}%`, background: d.color,
                borderRadius: 3, transition: "width 0.6s",
                boxShadow: `inset 0 0 0 1px ${d.color}`,
              }}/>
            </div>
            <div style={{
              fontSize: 11, color: SMD_PALETTE.textDim, fontFamily: "JetBrains Mono, monospace",
              textAlign: "right",
            }}>{d.kwh.toFixed(2)} kWh</div>
          </div>
        );
      })}
      <div style={{
        display: "grid", gridTemplateColumns: `${labelW}px 1fr 56px`, gap: 12, marginTop: 4,
        fontFamily: "JetBrains Mono, monospace", fontSize: 9, color: SMD_PALETTE.textDim,
        letterSpacing: "0.08em",
      }}>
        <div/>
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <span>0</span><span>1</span><span>2</span><span>3</span><span>4</span><span>5 kWh</span>
        </div>
        <div/>
      </div>
    </div>
  );
}

// ── Gauge (semi-circle) ────────────────────────────────────────
function SMDGauge({ value, max, label, suffix, color, wide }) {
  const pct = Math.min(1, Math.max(0, value / max));
  const r = 50, cx = 70, cy = 60;
  // Halbkreis von links (180°) nach rechts (0°), oben offen
  const x1 = cx - r;          // 20, 60
  const y1 = cy;              // 60
  const xEnd = cx + r;        // 120, 60
  const yEnd = cy;
  // Länge des kompletten Halbkreis-Pfads = π · r
  const arcLen = Math.PI * r;
  const dashOffset = arcLen * (1 - pct);

  return (
    <div style={{
      background: SMD_PALETTE.bgCard, border: `1px solid ${SMD_PALETTE.border}`,
      borderRadius: 12, padding: "14px 14px 12px",
      display: "flex", flexDirection: "column", alignItems: "center",
    }}>
      <svg viewBox="0 0 140 80" width="100%" style={{ maxHeight: 90, overflow: "visible" }}>
        {/* Hintergrund-Bogen */}
        <path d={`M ${x1} ${y1} A ${r} ${r} 0 0 1 ${xEnd} ${yEnd}`}
              fill="none" stroke={SMD_PALETTE.border} strokeWidth="8" strokeLinecap="round"/>
        {/* Wert-Bogen via dasharray, klippt sauber bei 0% und 100% */}
        <path d={`M ${x1} ${y1} A ${r} ${r} 0 0 1 ${xEnd} ${yEnd}`}
              fill="none" stroke={color} strokeWidth="8" strokeLinecap="round"
              strokeDasharray={arcLen} strokeDashoffset={dashOffset}
              style={{ transition: "stroke-dashoffset 0.6s ease" }}/>
        <text x="70" y="58" fill={SMD_PALETTE.text} fontSize="18" fontWeight="600"
              textAnchor="middle" fontFamily="Inter, sans-serif">
          {value.toFixed(value >= 10 || suffix === " %" ? 0 : 2)}{suffix}
        </text>
      </svg>
      <div style={{ fontSize: 11, color: SMD_PALETTE.textDim, marginTop: 2, fontFamily: "Inter, sans-serif", textAlign: "center", letterSpacing: "0.02em" }}>
        {label}
      </div>
    </div>
  );
}

// ── Main DEMO component ────────────────────────────────────────
function SmartHomeDemo({ pathKey }) {
  const data = SMD_DATA[pathKey] || SMD_DATA.altbau;
  const [view, setView] = React.useState("uebersicht"); // uebersicht | raum | energie
  const [room, setRoom] = React.useState(null);
  const [eTab, setETab] = React.useState("Zusammenfassung");

  const onRoom = (r) => { setRoom(r); setView("raum"); };
  const onBack = () => { setView("uebersicht"); setRoom(null); };
  const onNav = (k) => {
    if (k === "uebersicht" || k === "raum") { setView("uebersicht"); setRoom(null); }
    else if (k === "energie") setView("energie");
  };

  let title, tabs, activeTab, onTab;
  if (view === "energie") {
    tabs = ["Zusammenfassung", "Strom", "Wasser", "Jetzt"];
    activeTab = eTab;
    onTab = setETab;
  } else if (view === "raum") {
    title = room?.name || "Raum";
  } else {
    title = "Übersicht";
  }

  return (
    <div className="smd-dash" style={{
      width: "100%",
      maxWidth: 1280,
      height: 760,
      margin: "0 auto",
      background: SMD_PALETTE.bgDeep,
      border: `1px solid ${SMD_PALETTE.border}`,
      borderRadius: 16,
      overflow: "hidden",
      display: "flex",
      boxShadow: "0 30px 80px rgba(0,0,0,0.5), 0 0 0 1px rgba(58,189,208,0.05)",
    }}>
      <SMDSidebar activeView={view} onNav={onNav}/>
      <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
        <SMDTopBar title={title}
                   back={view === "raum"} onBack={onBack}
                   tabs={tabs} activeTab={activeTab} onTab={onTab}/>
        {view === "uebersicht" && <SMDOverview data={data} onRoom={onRoom}/>}
        {view === "raum" && (pathKey === "gewerbe"
          ? <SMDCommercialRoomDetail room={room} />
          : <SMDRoomDetail room={room} onBack={onBack} />)}
        {view === "energie" && <SMDEnergyView data={data}/>}
      </div>
    </div>
  );
}

// ── Section wrapper for the landing page ───────────────────────
function SmartHomeDemoSection({ pathKey }) {
  const isGewerbe = pathKey === "gewerbe";
  return (
    <section id="demo" style={{
      padding: "100px 40px 120px",
      borderTop: `1px solid ${SMD_PALETTE.border}`,
      position: "relative",
      scrollMarginTop: "80px",
    }}>
      <style>{`
        /* Demo-Dashboard auf dem Handy sauber untereinander stapeln:
           mehrspaltige Bereiche -> 1 Spalte, feste Hoehe raus, kein
           Seitwaerts-Scroll. Tablet/Desktop bleiben unveraendert. */
        @media (max-width: 760px){
          .smd-dash{ height: auto !important; min-width: 0 !important; }
          .smd-dash .smd-ov,
          .smd-dash .smd-g3,
          .smd-dash .smd-g2{ grid-template-columns: 1fr !important; }
          /* Topbar: dekorative Action-Icons weg, Tabs duerfen scrollen */
          .smd-topbar{ padding: 0 14px !important; gap: 10px !important; }
          .smd-topbar-actions{ display: none !important; }
          .smd-tabs{ overflow-x: auto; scrollbar-width: none; }
          .smd-tabs::-webkit-scrollbar{ display: none; }
        }
      `}</style>
      <div style={{ maxWidth: 1280, margin: "0 auto 40px" }}>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 10,
          padding: "7px 14px", background: "rgba(58,189,208,0.08)",
          border: "1px solid rgba(58,189,208,0.25)", borderRadius: 100,
          fontFamily: "JetBrains Mono, monospace", fontSize: 11,
          color: SMD_PALETTE.accent, letterSpacing: "0.15em", marginBottom: 24,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 50, background: SMD_PALETTE.accent,
                         boxShadow: `0 0 0 4px ${SMD_PALETTE.accent}33`, display: "block" }}/>
          LIVE-DEMO
        </div>
        <h2 style={{
          fontFamily: "Outfit, sans-serif", fontSize: "clamp(32px, 4vw, 52px)",
          fontWeight: 500, letterSpacing: "-0.02em", lineHeight: 1.1,
          margin: "0 0 16px", color: SMD_PALETTE.text,
        }}>
          So sieht{" "}
          <em style={{ fontStyle: "normal", color: SMD_PALETTE.accent }}>
            {isGewerbe ? "dein Objekt" : "dein Zuhause"}
          </em>{" "}
          aus.
        </h2>
        <p style={{
          fontFamily: "Inter, sans-serif", fontSize: 17, lineHeight: 1.55,
          color: SMD_PALETTE.soft, opacity: 0.8, maxWidth: 660, margin: 0,
        }}>
          {isGewerbe
            ? "Eine Betriebsoberfläche aus dem Alltag — klick dich durch Bereiche, Zutritt, Technikstatus und Energiedashboard. Dein Objekt wird ähnlich strukturiert: mit deinen Flächen, deinen Anlagen, deinen Werten."
            : "Eine echte Konfiguration aus dem Alltag — klick dich durch Räume, Szenen und das Energiedashboard. Dein Setup wird ähnlich aussehen, mit deinen Räumen, deinen Geräten, deinen Werten."}
        </p>
      </div>

      <div className="smd-dash-scroll">
        <SmartHomeDemo pathKey={pathKey}/>
      </div>

      <div style={{
        maxWidth: 1280, margin: "32px auto 0", display: "flex", gap: 16, flexWrap: "wrap",
        fontFamily: "JetBrains Mono, monospace", fontSize: 11,
        color: SMD_PALETTE.textDim, letterSpacing: "0.08em", textTransform: "uppercase",
      }}>
        <div>↑ Sidebar zeigt Hauptbereiche</div>
        <div>· {isGewerbe ? "Bereiche klickbar — Detail mit Kennzahlen + Anlagen" : "Räume klickbar — Detail mit Szenen + Geräten"}</div>
        <div>· Energie-Tab zeigt PV-Fluss, Quellen, Autarkiegrad</div>
      </div>
    </section>
  );
}

window.SmartHomeDemoSection = SmartHomeDemoSection;
window.SmartHomeDemo = SmartHomeDemo;
// Im Konfigurator (Step 2) bauen wir den Room-Detail dynamisch fuer den
// aktuellen Raum nach -- Komponenten + Palette dafuer exposen.
window.SMD_PALETTE = SMD_PALETTE;
window.SMDIcons = SMDIcons;
window.SMDTile = SMDTile;
