// Home dashboard — three layout variants

function getTimeOfDay() {
  const h = new Date().getHours();
  if (h < 12) return 'morning';
  if (h < 18) return 'afternoon';
  return 'evening';
}

function getGreeting(name) {
  const h = new Date().getHours();
  if (h < 5) return `Still up, ${name}?`;
  if (h < 12) return `Good morning, ${name}`;
  if (h < 18) return `Good afternoon, ${name}`;
  if (h < 22) return `Good evening, ${name}`;
  return `Good night, ${name}`;
}

function DashboardHome({ store, cfg, onNav, onOpenDevice, onOpenScene, user, onLogout }) {
  const { devices, scenes, family, activity, waste, weather, todos, shopping } = store;
  const activeScene = scenes.find(s => s.active);
  const onCount = devices.filter(d => d.on).length;
  const watts = devices.reduce((s, d) => s + (d.type !== 'ac' && d.type !== 'washer' ? (d.watts || 0) : 0), 0);
  const displayName = user?.name || 'Home';
  const pendingTodos = (todos || []).filter(t => !t.done).length;
  const pendingShop = (shopping || []).filter(s => !s.done).length;

  // Dynamic rooms from actual device data
  const roomList = [...new Set(devices.map(d => d.room).filter(Boolean))];

  if (cfg.layout === 'compact') return <DashCompact store={store} cfg={cfg} onNav={onNav} onOpenDevice={onOpenDevice} onOpenScene={onOpenScene} user={user}/>;
  if (cfg.layout === 'wide') return <DashWide store={store} cfg={cfg} onNav={onNav} onOpenDevice={onOpenDevice} onOpenScene={onOpenScene} user={user}/>;

  // default: cozy
  return (
    <div className="hh-scroll" style={{ flex: 1, overflow: 'auto', paddingBottom: 20 }}>
      <TopBar
        subtitle={new Date().toLocaleDateString('en', { weekday: 'long', month: 'long', day: 'numeric' })}
        title={<span className="hh-serif" style={{ fontSize: 22 }}>{getGreeting(displayName)}</span>}
        trailing={
          <div style={{ display: 'flex', gap: 8 }}>
            {weather && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 13, color: 'var(--hh-ink-soft)', cursor: 'default' }} title={`${weather.label} · Wind ${weather.wind} km/h · Humidity ${weather.humidity}%`}>
                <span style={{ fontSize: 18 }}>{weather.icon}</span>
                <span className="hh-numeric">{weather.temp}°</span>
              </div>
            )}
            <div style={{ position: 'relative' }}>
              <Avatar name={displayName} color="var(--hh-accent)" size={40} photoUrl={user?.photo_url || null}/>
              <div style={{ position: 'absolute', right: -2, bottom: -2, width: 14, height: 14, borderRadius: 999, background: 'var(--hh-good)', border: '2px solid var(--hh-bg)' }}/>
            </div>
          </div>
        }
      />

      {/* Ambient summary */}
      <AmbientStrip items={[
        { label: weather ? weather.label : 'Outside', value: weather ? weather.temp : '—', unit: '°' },
        { label: 'Power', value: watts, unit: 'W' },
        { label: 'Active', value: onCount, unit: ' devices' },
      ]}/>

      {/* Quick glance: todos + shopping + people home */}
      {(pendingTodos > 0 || pendingShop > 0) && (
        <div style={{ display: 'flex', gap: 8, padding: '0 20px', marginBottom: 14, flexWrap: 'wrap' }}>
          {pendingTodos > 0 && (
            <button className="press" onClick={() => onNav('lists')} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 999, background: 'var(--hh-surface)', border: '1px solid var(--hh-line-soft)', fontSize: 12, color: 'var(--hh-ink)', cursor: 'pointer' }}>
              <Icon name="check" size={13} color="var(--hh-accent)"/>
              <span><b>{pendingTodos}</b> task{pendingTodos !== 1 ? 's' : ''} pending</span>
            </button>
          )}
          {pendingShop > 0 && (
            <button className="press" onClick={() => onNav('lists')} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 999, background: 'var(--hh-surface)', border: '1px solid var(--hh-line-soft)', fontSize: 12, color: 'var(--hh-ink)', cursor: 'pointer' }}>
              <Icon name="cart" size={13} color="var(--hh-sage)"/>
              <span><b>{pendingShop}</b> shopping item{pendingShop !== 1 ? 's' : ''}</span>
            </button>
          )}
        </div>
      )}

      {/* Active scene hero */}
      <div style={{ padding: '0 20px 16px' }}>
        {activeScene ? (
        <button className="press" onClick={() => onNav('scenes')} style={{
          width: '100%', textAlign: 'left',
          background: `linear-gradient(135deg, ${activeScene.color} 0%, ${activeScene.color}dd 100%)`,
          borderRadius: 22, padding: 18, color: '#fff',
          display: 'flex', alignItems: 'center', gap: 14,
          boxShadow: 'var(--hh-shadow)',
        }}>
          <div style={{ fontSize: 44, lineHeight: 1 }}>{activeScene.emoji}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.85 }}>Now playing</div>
            <div className="hh-serif" style={{ fontSize: 24, lineHeight: 1.1 }}>{activeScene.name}</div>
            <div style={{ fontSize: 12, opacity: 0.85, marginTop: 2 }}>{activeScene.note}</div>
          </div>
          <Icon name="chevronR" size={22}/>
        </button>
        ) : (
        <button className="press" onClick={() => onNav('scenes')} style={{
          width: '100%', textAlign: 'left',
          background: 'var(--hh-surface)', border: '1px solid var(--hh-line-soft)',
          borderRadius: 22, padding: 18,
          display: 'flex', alignItems: 'center', gap: 14,
          boxShadow: 'var(--hh-shadow-sm)',
        }}>
          <div style={{ fontSize: 36, lineHeight: 1 }}>✨</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.6 }}>Scenes</div>
            <div className="hh-serif" style={{ fontSize: 20, color: 'var(--hh-ink)' }}>No active scene</div>
          </div>
          <Icon name="chevronR" size={22} color="var(--hh-ink-mute)"/>
        </button>
        )}
      </div>

      {/* Family strip */}
      <div style={{ padding: '0 20px 16px' }}>
        <div className="hh-section-h" style={{ padding: '0 0 8px' }}>Who's where</div>
        <div className="hh-card" style={{ padding: 12, display: 'flex', gap: 10 }}>
          {family.map(f => (
            <div key={f.id} onClick={() => onNav('map')} className="press" style={{ flex: 1, textAlign: 'center', cursor: 'pointer' }}>
              <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 6, position: 'relative' }}>
                <Avatar name={f.name} color={f.color} size={44} photoUrl={f.photo_url || null}/>
                <div style={{ position: 'absolute', bottom: -2, right: '30%', width: 12, height: 12, borderRadius: 999, background: f.location === 'Home' ? 'var(--hh-good)' : 'var(--hh-mustard)', border: '2px solid var(--hh-surface)' }}/>
              </div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{f.name}</div>
              <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>{f.location}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Rooms quick row */}
      <div className="hh-section-h">Rooms</div>
      <div className="hh-hscroll hh-scroll">
        {(roomList.length > 0 ? roomList : ['Living Room','Kitchen','Bedroom','Office']).map((r, i) => {
          const onRooms = store.devices.filter(d => d.room === r && d.on).length;
          return (
            <button key={r} className="press" onClick={() => onNav('devices')}
              style={{ width: 120, padding: 12, background: 'var(--hh-surface)', border: '1px solid var(--hh-line-soft)', borderRadius: 18, textAlign: 'left' }}>
              <div style={{ height: 60, borderRadius: 12, background: [
                'linear-gradient(135deg,#F0C9B8,#E8A96B)',
                'linear-gradient(135deg,#F0DCA8,#C99A2E)',
                'linear-gradient(135deg,#C5D5DE,#5F7E91)',
                'linear-gradient(135deg,#CBDABB,#6E8662)',
                'linear-gradient(135deg,#E4D5C2,#B26749)',
                'linear-gradient(135deg,#F0C9B8,#C9562E)',
                'linear-gradient(135deg,#DCC7D5,#7A4F6B)',
              ][i % 7], marginBottom: 8, opacity: 0.85, position: 'relative' }}>
                <div style={{ position: 'absolute', top: 6, right: 8, fontSize: 10, background: 'rgba(0,0,0,0.2)', color: '#fff', padding: '2px 6px', borderRadius: 999 }}>{onRooms} on</div>
              </div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{r}</div>
              <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>{store.devices.filter(d => d.room === r).length} devices</div>
            </button>
          );
        })}
      </div>

      {/* Quick devices */}
      <div className="hh-section-h" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingRight: 20 }}>
        <span>Favorites</span>
        <button className="press" onClick={() => onNav('devices')} style={{ fontSize: 12, color: 'var(--hh-accent)', textTransform: 'none', letterSpacing: 0 }}>All devices →</button>
      </div>
      <div style={{ padding: '0 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {devices.slice(0, 4).map(d => (
          <DeviceTile key={d.id} d={d} onToggle={() => store.toggleDevice(d.id).catch(() => {})} onOpen={() => onOpenDevice(d)} iconVariant={cfg.iconVariant}/>
        ))}
      </div>

      {/* Scenes carousel */}
      <div className="hh-section-h" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingRight: 20 }}>
        <span>Scenes</span>
        <button className="press" onClick={() => onNav('scenes')} style={{ fontSize: 12, color: 'var(--hh-accent)', textTransform: 'none', letterSpacing: 0 }}>All →</button>
      </div>
      <div className="hh-hscroll hh-scroll">
        {scenes.map(s => (
          <button key={s.id} onClick={() => store.activateScene(s.id)} className="press" style={{
            width: 130, padding: 12, borderRadius: 18,
            background: s.active ? s.color : 'var(--hh-surface)',
            border: `1px solid ${s.active ? s.color : 'var(--hh-line-soft)'}`,
            color: s.active ? '#fff' : 'var(--hh-ink)', textAlign: 'left',
          }}>
            <div style={{ fontSize: 30, marginBottom: 6 }}>{s.emoji}</div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{s.name}</div>
            <div style={{ fontSize: 11, opacity: 0.75, marginTop: 2 }}>{s.devices} devices</div>
          </button>
        ))}
      </div>

      {/* Waste & rules next up */}
      <div style={{ padding: '16px 20px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <div className="hh-card press" onClick={() => onNav('waste')} style={{ padding: 14, cursor: 'pointer' }}>
          <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--hh-ink-mute)' }}>Next collection</div>
          {waste[0] ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: waste[0].color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>{waste[0].icon}</div>
            <div>
              <div className="hh-serif" style={{ fontSize: 18 }}>{waste[0].type}</div>
              <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>{waste[0].next}</div>
            </div>
          </div>
          ) : (
          <div style={{ fontSize: 13, color: 'var(--hh-ink-mute)', marginTop: 6 }}>No schedule</div>
          )}
        </div>
        <div className="hh-card press" onClick={() => onNav('rules')} style={{ padding: 14, cursor: 'pointer' }}>
          <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--hh-ink-mute)' }}>Automations</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--hh-accent-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="sparkle" size={18} color="var(--hh-accent)" variant={cfg.iconVariant}/>
            </div>
            <div>
              <div className="hh-serif" style={{ fontSize: 18 }}>{store.rules.filter(r => r.active).length} active</div>
              <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>{store.rules.length} total</div>
            </div>
          </div>
        </div>
      </div>

      {/* Quick actions */}
      <div style={{ padding: '16px 20px 0', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
        {[
          { label: 'Rules', icon: 'sparkle', to: 'rules' },
          { label: 'Cameras', icon: 'camera', to: 'cameras' },
          { label: 'Activity', icon: 'bolt', to: 'activity' },
          { label: 'Family', icon: 'users', to: 'family' },
        ].map(a => (
          <button key={a.to} className="press" onClick={() => onNav(a.to)} style={{
            padding: '14px 6px', borderRadius: 14,
            background: 'var(--hh-surface)', border: '1px solid var(--hh-line-soft)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, color: 'var(--hh-ink)',
          }}>
            <div style={{ width: 32, height: 32, borderRadius: 10, background: 'var(--hh-accent-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name={a.icon} size={18} color="var(--hh-accent)" variant={cfg.iconVariant}/>
            </div>
            <div style={{ fontSize: 11, fontWeight: 500 }}>{a.label}</div>
          </button>
        ))}
      </div>

      {/* Activity preview */}
      <div className="hh-section-h" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingRight: 20 }}>
        <span>Recent</span>
        <button className="press" onClick={() => onNav('activity')} style={{ fontSize: 12, color: 'var(--hh-accent)', textTransform: 'none', letterSpacing: 0 }}>See all →</button>
      </div>
      <div className="hh-card" style={{ margin: '0 20px' }}>
        {activity.slice(0, 3).map((a, i) => (
          <div key={a.id} style={{ padding: '12px 14px', borderBottom: i < 2 ? '1px solid var(--hh-line-soft)' : 'none', display: 'flex', gap: 10, alignItems: 'center' }}>
            <div style={{ width: 8, height: 8, borderRadius: 999, flexShrink: 0, background: {device:'var(--hh-sage)',rule:'var(--hh-accent)',geo:'var(--hh-mustard)',list:'var(--hh-sky)',camera:'var(--hh-plum)',scene:'var(--hh-clay)'}[a.cat] }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {a.who && a.who !== 'System'
                  ? <><b style={{ fontWeight: 600 }}>{a.who}</b>{' '}{a.action}</>
                  : a.action}
              </div>
              <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>{a.time}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// Device tile
function DeviceTile({ d, onToggle, onOpen, iconVariant = 'duotone' }) {
  const iconMap = { bulb: 'bulb', plug: 'plug', ac: 'wave', thermo: 'thermo', lock: 'lock', washer: 'cycle' };
  const tint = d.on ? 'var(--hh-accent-tint)' : 'var(--hh-surface-2)';
  return (
    <div onClick={onOpen} className="press" style={{
      padding: 14, borderRadius: 18,
      background: d.on ? 'var(--hh-surface)' : 'var(--hh-surface-2)',
      border: `1px solid ${d.on ? 'var(--hh-accent-soft)' : 'var(--hh-line-soft)'}`,
      cursor: 'pointer', position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: tint, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name={iconMap[d.type] || 'plug'} size={20} color={d.on ? 'var(--hh-accent)' : 'var(--hh-ink-mute)'} variant={iconVariant}/>
        </div>
        <Toggle on={d.on} onChange={onToggle}/>
      </div>
      <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 2 }}>{d.name}</div>
      <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)' }}>
        {d.type === 'bulb' && (d.on ? `${d.value}% warm` : 'Off')}
        {d.type === 'plug' && (d.on ? `${d.watts} W` : 'Off')}
        {d.type === 'ac' && (d.on ? `${d.temp}° ${d.mode}` : 'Off')}
        {d.type === 'thermo' && `${d.temp}° → ${d.target}°`}
        {d.type === 'lock' && (d.locked ? 'Locked' : 'Unlocked')}
        {d.type === 'washer' && (d.on ? `${d.progress}% ${d.status}` : 'Idle')}
      </div>
    </div>
  );
}

// Compact layout — dense grid
function DashCompact({ store, cfg, onNav }) {
  const { devices, scenes, family } = store;
  const homeLabel = family[0]?.name ? `${family[0].name}'s casa` : 'Home';
  return (
    <div className="hh-scroll" style={{ flex: 1, overflow: 'auto' }}>
      <div style={{ padding: '14px 20px 6px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 11, color: 'var(--hh-ink-mute)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{homeLabel}</div>
            <div className="hh-serif" style={{ fontSize: 22 }}>Good afternoon</div>
          </div>
          <div style={{ display: 'flex' }}>
            {family.map((f, i) => (
              <div key={f.id} style={{ marginLeft: i === 0 ? 0 : -8 }}><Avatar name={f.name} color={f.color} size={32}/></div>
            ))}
          </div>
        </div>
      </div>
      <div style={{ padding: '6px 20px', display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 6 }}>
        {[{ k:'Inside',v:'21°' },{ k:'Power',v:'121W' },{ k:'Online',v:'10/11' }].map(s => (
          <div key={s.k} style={{ background: 'var(--hh-surface)', padding: '8px 10px', borderRadius: 10, border: '1px solid var(--hh-line-soft)' }}>
            <div style={{ fontSize: 10, color: 'var(--hh-ink-mute)' }}>{s.k}</div>
            <div className="hh-numeric" style={{ fontSize: 16 }}>{s.v}</div>
          </div>
        ))}
      </div>
      <div className="hh-section-h">Devices</div>
      <div style={{ padding: '0 20px', display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 6 }}>
        {devices.map(d => (
          <div key={d.id} onClick={() => store.toggleDevice(d.id).catch(() => {})} className="press" style={{ background: d.on ? 'var(--hh-surface)' : 'var(--hh-surface-2)', borderRadius: 12, padding: 10, display: 'flex', gap: 8, alignItems: 'center', border: `1px solid ${d.on ? 'var(--hh-accent-soft)' : 'var(--hh-line-soft)'}` }}>
            <div style={{ width: 8, height: 8, borderRadius: 999, background: d.on ? 'var(--hh-accent)' : 'var(--hh-line)' }}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.name}</div>
              <div style={{ fontSize: 10, color: 'var(--hh-ink-mute)' }}>{d.room}</div>
            </div>
          </div>
        ))}
      </div>
      <div className="hh-section-h">Scenes</div>
      <div style={{ padding: '0 20px 20px', display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 6 }}>
        {scenes.map(s => (
          <button key={s.id} onClick={() => store.activateScene(s.id)} className="press" style={{
            padding: 10, borderRadius: 12, textAlign: 'left',
            background: s.active ? s.color : 'var(--hh-surface)',
            color: s.active ? '#fff' : 'var(--hh-ink)',
            border: `1px solid ${s.active ? s.color : 'var(--hh-line-soft)'}`,
          }}>
            <div style={{ fontSize: 20 }}>{s.emoji}</div>
            <div style={{ fontSize: 11, fontWeight: 600, marginTop: 2 }}>{s.name}</div>
          </button>
        ))}
      </div>
    </div>
  );
}

// Wide — magazine layout
function DashWide({ store, cfg, onNav, onOpenDevice }) {
  const { devices, scenes, family, activity } = store;
  const activeScene = scenes.find(s => s.active);
  return (
    <div className="hh-scroll" style={{ flex: 1, overflow: 'auto', paddingBottom: 20 }}>
      <div style={{ padding: '18px 20px', background: 'var(--hh-ink)', color: 'var(--hh-bg)', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -30, right: -30, width: 180, height: 180, borderRadius: '50%', background: 'var(--hh-accent)', opacity: 0.35, filter: 'blur(30px)' }}/>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', opacity: 0.7 }}>Today · Sat Apr 18</div>
          <div className="hh-serif" style={{ fontSize: 34, lineHeight: 1, marginTop: 4 }}>All calm.</div>
          <div className="hh-serif" style={{ fontSize: 34, lineHeight: 1, fontStyle: 'italic', color: 'var(--hh-accent-soft)' }}>Scene: {activeScene?.name}</div>
          <div style={{ display: 'flex', gap: 16, marginTop: 16, fontSize: 12 }}>
            <div><div style={{ opacity: 0.7 }}>Inside</div><div className="hh-numeric" style={{ fontSize: 22 }}>21.4°</div></div>
            <div><div style={{ opacity: 0.7 }}>Outside</div><div className="hh-numeric" style={{ fontSize: 22 }}>14°</div></div>
            <div><div style={{ opacity: 0.7 }}>Power</div><div className="hh-numeric" style={{ fontSize: 22 }}>121W</div></div>
          </div>
        </div>
      </div>
      <div style={{ padding: 20, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {devices.slice(0, 6).map(d => (
          <DeviceTile key={d.id} d={d} onToggle={() => store.toggleDevice(d.id).catch(() => {})} onOpen={() => onOpenDevice(d)} iconVariant={cfg.iconVariant}/>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { DashboardHome, DeviceTile });
