// desktop-shared.jsx — sidebar, top bar, primitives for the desktop variant
// Relies on window.I (icons), window.ListingCard data helpers, etc. from mobile bundle.

const dskMonogram = (
  <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
    {/* tiny serif "I" mark — echoes Newsreader feel */}
    <path d="M7 4h10M7 20h10M12 4v16" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
    <circle cx="12" cy="12" r="2.4" fill="currentColor" />
  </svg>
);

// ─── SIDEBAR ────────────────────────────────────────────────────────────
function Sidebar({
  active = 'kauf',
  notifBadge = 0,
  onNav = () => {},
  user = null,
  taskLimit = null,
  onNewSearch = null,
}) {
  const items = [
    { id: 'kauf',     label: 'Kaufen',       icon: <I.home /> },
    { id: 'miete',    label: 'Mieten',       icon: <I.key /> },
    { id: 'investor', label: 'Investor',     icon: <I.trend /> },
    { id: 'merk',     label: 'Merkliste',    icon: <I.bookmark /> },
    { id: 'mitt',     label: 'Mitteilungen', icon: <I.bell />, badge: notifBadge },
    { id: 'entd',     label: 'Entdecken',    icon: <I.swipe /> },
  ];
  const admin = [
    { id: 'profile', label: 'Profil',      icon: <I.user /> },
    ...(user?.isAdmin ? [{ id: 'jobs', label: 'Job-Monitor', icon: <I.settings /> }] : []),
    { id: 'export',  label: 'Exporte',     icon: <I.download /> },
  ];
  const quota = taskLimit?.remaining_evaluations == null ? 'Unbegrenzt' : taskLimit.remaining_evaluations;
  return (
    <aside style={{
      width: 248, flexShrink: 0, height: '100%', background: 'var(--surface)',
      borderRight: '1px solid var(--border)',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Logo */}
      <div style={{ padding: '24px 22px 22px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: '1px solid var(--border)' }}>
        <div style={{
          width: 34, height: 34, borderRadius: 9,
          background: 'var(--ink)', color: 'var(--primary)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{dskMonogram}</div>
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1 }}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, letterSpacing: -0.01, color: 'var(--ink)' }}>
            ImmoBot
          </span>
          <span style={{ fontSize: 10, color: 'var(--ink-muted)', letterSpacing: 0.12, textTransform: 'uppercase', marginTop: 3, fontWeight: 600 }}>
            Pro · v3.4
          </span>
        </div>
      </div>

      {/* Workspace switcher */}
      <div style={{ padding: '14px 14px 4px' }}>
        <div style={{
          padding: '10px 12px', borderRadius: 10, background: 'var(--surface-2)',
          display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
        }}>
          <div style={{
            width: 30, height: 30, borderRadius: 8,
            background: 'linear-gradient(135deg, var(--primary), var(--primary-deep))',
            color: '#fff', fontSize: 12, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--font-display)',
          }}>{user?.initials || 'IB'}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {user?.name || 'ImmoBot'}
            </div>
            <div style={{ fontSize: 11, color: 'var(--ink-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {user?.email || 'Arbeitsbereich'}
            </div>
          </div>
          <I.chevD style={{ color: 'var(--ink-faint)', width: 16, height: 16 }} />
        </div>
      </div>

      {/* Primary nav */}
      <div style={{ padding: '14px 12px 4px' }}>
        <SideLabel>Suchen & Inventar</SideLabel>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 2, marginTop: 6 }}>
          {items.map(it => (
            <NavItem key={it.id} {...it} active={active === it.id} onClick={() => onNav(it.id)} />
          ))}
        </nav>
      </div>
      <div style={{ padding: '14px 12px 4px' }}>
        <SideLabel>Verwaltung</SideLabel>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 2, marginTop: 6 }}>
          {admin.map(it => (
            <NavItem key={it.id} {...it} active={active === it.id} onClick={() => onNav(it.id)} />
          ))}
        </nav>
      </div>

      {/* New search CTA */}
      <div style={{ padding: '16px 14px 14px', marginTop: 'auto' }}>
        <div style={{
          padding: 14, borderRadius: 12,
          background: 'linear-gradient(160deg, var(--primary-soft) 0%, #FBF6E6 100%)',
          border: '1px solid #EFE0BA',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <div style={{
              width: 24, height: 24, borderRadius: 6, background: 'var(--primary)',
              color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><I.spark style={{ width: 14, height: 14 }} /></div>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--primary-ink)', letterSpacing: 0.04, textTransform: 'uppercase' }}>
              KI Pro
            </div>
          </div>
          <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--primary-ink)', lineHeight: 1.45 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 500, display: 'block', marginBottom: 4 }}>
              {quota} von {taskLimit?.max_evaluations_per_day || 100}
            </span>
            KI-Bewertungen heute übrig.
          </div>
          <div style={{ marginTop: 10, height: 4, background: '#fff', borderRadius: 999, overflow: 'hidden' }}>
            <div style={{ width: `${desktopQuotaPct(taskLimit)}%`, height: '100%', background: 'var(--primary)' }} />
          </div>
        </div>

        <button type="button" onClick={onNewSearch || (() => onNav('newSearch'))} style={{
          marginTop: 12, width: '100%', padding: '11px 12px', borderRadius: 10,
          background: 'var(--ink)', color: '#fff', border: 0, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-sans)',
        }}>
          <I.plus style={{ width: 16, height: 16, strokeWidth: 2.4 }} />
          Neue Suche
        </button>
      </div>
    </aside>
  );
}

function desktopQuotaPct(taskLimit) {
  const max = Number(taskLimit?.max_evaluations_per_day || 100);
  const remaining = taskLimit?.remaining_evaluations == null ? max : Number(taskLimit.remaining_evaluations || 0);
  if (!max) return 0;
  return Math.max(0, Math.min(100, (remaining / max) * 100));
}

function SideLabel({ children }) {
  return (
    <div style={{
      fontSize: 10.5, fontWeight: 700, color: 'var(--ink-faint)',
      letterSpacing: 0.1, textTransform: 'uppercase', padding: '0 8px',
    }}>{children}</div>
  );
}

function NavItem({ icon, label, badge, active, onClick }) {
  return (
    <button type="button" onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 11,
      padding: '9px 11px', borderRadius: 9, border: 0, cursor: 'pointer',
      background: active ? 'var(--surface-2)' : 'transparent',
      color: active ? 'var(--ink)' : 'var(--ink-2)',
      fontFamily: 'var(--font-sans)', fontSize: 13.5, fontWeight: active ? 700 : 500,
      textAlign: 'left', width: '100%', position: 'relative',
    }}>
      <span style={{ color: active ? 'var(--primary)' : 'var(--ink-muted)', display: 'flex' }}>
        {React.cloneElement(icon, { width: 18, height: 18 })}
      </span>
      <span style={{ flex: 1 }}>{label}</span>
      {badge > 0 && (
        <span style={{
          background: 'var(--primary)', color: '#fff', fontSize: 10, fontWeight: 700,
          padding: '1px 7px', borderRadius: 999, minWidth: 18, textAlign: 'center',
        }}>{badge}</span>
      )}
      {active && <span style={{
        position: 'absolute', left: -12, top: 8, bottom: 8, width: 3,
        background: 'var(--primary)', borderRadius: 99,
      }} />}
    </button>
  );
}

// ─── TOP BAR ────────────────────────────────────────────────────────────
function DTopBar({
  crumb,
  title,
  subtitle,
  actions,
  notifBadge = 0,
  searchValue = '',
  onSearchChange,
  onSearchSubmit,
  onNotifications,
  searchPlaceholder = 'Adresse, Suchname oder Plattform-ID …',
  showSearch = true,
  compactActions = false,
}) {
  const searchRef = React.useRef(null);
  React.useEffect(() => {
    if (!showSearch) return undefined;
    const onKey = (event) => {
      if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
        event.preventDefault();
        searchRef.current?.focus();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [showSearch]);
  const canSearch = showSearch && typeof onSearchChange === 'function';
  const actionGap = compactActions ? 8 : 10;
  const actionSize = compactActions ? 'sm' : 'md';
  return (
    <header style={{
      padding: '20px 32px 18px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 24, borderBottom: '1px solid var(--border)', background: 'var(--bg)',
    }}>
      <div style={{ minWidth: 0, flex: 1 }}>
        {crumb && (
          <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-muted)', letterSpacing: 0.04, marginBottom: 6, display: 'flex', alignItems: 'center', gap: 6 }}>
            {crumb.map((c, i) => (
              <React.Fragment key={i}>
                <span style={{ color: i === crumb.length - 1 ? 'var(--ink-2)' : 'var(--ink-muted)' }}>{c}</span>
                {i < crumb.length - 1 && <I.chevR style={{ width: 12, height: 12, color: 'var(--ink-faint)' }} />}
              </React.Fragment>
            ))}
          </div>
        )}
        <h1 style={{
          margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500,
          fontSize: 30, lineHeight: 1.1, letterSpacing: -0.015, color: 'var(--ink)',
          minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{title}</h1>
        {subtitle && (
          <div style={{ fontSize: 13, color: 'var(--ink-muted)', marginTop: 4 }}>{subtitle}</div>
        )}
      </div>

      {/* Search + actions */}
      <div style={{ display: 'flex', alignItems: 'center', gap: actionGap, flexShrink: 0 }}>
        {showSearch && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 9,
            background: 'var(--surface)', border: '1px solid var(--border)',
            borderRadius: 10, padding: '9px 12px', minWidth: 280,
          }}>
            <I.search style={{ width: 16, height: 16, color: 'var(--ink-muted)' }} />
            <input
              ref={searchRef}
              value={searchValue}
              disabled={!canSearch}
              placeholder={searchPlaceholder}
              onChange={e => onSearchChange?.(e.target.value)}
              onKeyDown={e => {
                if (e.key === 'Enter') onSearchSubmit?.(e.target.value);
              }}
              style={{
                width: 220, border: 0, background: 'transparent', outline: 'none',
                fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--ink)',
                minWidth: 0,
              }}
            />
            {searchValue ? (
              <button
                type="button"
                onClick={() => onSearchChange?.('')}
                style={{
                  width: 22, height: 22, border: 0, borderRadius: 6, background: 'transparent',
                  color: 'var(--ink-muted)', cursor: 'pointer', display: 'inline-flex',
                  alignItems: 'center', justifyContent: 'center', padding: 0,
                }}
                aria-label="Suche löschen"
              >
                <I.x style={{ width: 14, height: 14 }} />
              </button>
            ) : (
              <kbd style={{
                fontSize: 10.5, color: 'var(--ink-muted)', fontFamily: 'var(--font-mono)',
                background: 'var(--surface-2)', padding: '2px 6px', borderRadius: 4,
                border: '1px solid var(--border)',
              }}>⌘K</kbd>
            )}
          </div>
        )}

        <DButton kind="ghost" icon={<I.bell />} badge={notifBadge} onClick={onNotifications} title="Mitteilungen" size={actionSize} />
        {actions}
      </div>
    </header>
  );
}

// ─── BUTTON ─────────────────────────────────────────────────────────────
function DButton({ kind = 'ghost', icon, children, onClick, badge, size = 'md', disabled = false, title }) {
  const padding = size === 'sm' ? '7px 11px' : '9px 14px';
  const styles = {
    primary:  { background: 'var(--ink)', color: '#fff', border: '1px solid var(--ink)' },
    accent:   { background: 'var(--primary)', color: '#fff', border: '1px solid var(--primary)' },
    outline:  { background: 'var(--surface)', color: 'var(--ink)', border: '1px solid var(--border-strong)' },
    ghost:    { background: 'var(--surface)', color: 'var(--ink-2)', border: '1px solid var(--border)' },
    soft:     { background: 'var(--surface-2)', color: 'var(--ink)', border: '1px solid transparent' },
    icon:     { background: 'transparent', color: 'var(--ink-2)', border: 'none', padding: 8 },
  };
  return (
    <button type="button" onClick={onClick} disabled={disabled} title={title} style={{
      display: 'inline-flex', alignItems: 'center', gap: 7,
      padding, borderRadius: 10, cursor: disabled ? 'default' : 'pointer', position: 'relative',
      fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
      letterSpacing: -0.005, opacity: disabled ? .55 : 1, ...styles[kind],
    }}>
      {icon && React.cloneElement(icon, { width: 16, height: 16 })}
      {children}
      {badge > 0 && (
        <span style={{
          position: 'absolute', top: -4, right: -4,
          background: 'var(--primary)', color: '#fff', fontSize: 10, fontWeight: 700,
          minWidth: 17, height: 17, padding: '0 5px', borderRadius: 999,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          border: '2px solid var(--bg)',
        }}>{badge}</span>
      )}
    </button>
  );
}

// ─── STAT TILE (desktop) ────────────────────────────────────────────────
function DStat({ value, label, delta, icon, accent, trend }) {
  return (
    <div style={{
      padding: '18px 20px 16px', borderRadius: 14,
      background: accent ? 'var(--ink)' : 'var(--surface)',
      color: accent ? '#fff' : 'var(--ink)',
      border: accent ? 'none' : '1px solid var(--border)',
      display: 'flex', flexDirection: 'column', gap: 6, minHeight: 116,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{
          fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.06,
          color: accent ? 'rgba(255,255,255,.65)' : 'var(--ink-muted)',
        }}>{label}</span>
        {icon && <span style={{
          width: 30, height: 30, borderRadius: 8,
          background: accent ? 'rgba(255,255,255,.1)' : 'var(--surface-2)',
          color: accent ? '#fff' : 'var(--primary)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}>{React.cloneElement(icon, { width: 15, height: 15 })}</span>}
      </div>
      <div style={{
        fontFamily: 'var(--font-display)', fontSize: 38, fontWeight: 500, letterSpacing: -0.02,
        lineHeight: 1, marginTop: 6, fontVariantNumeric: 'tabular-nums',
      }}>{value}</div>
      {delta && (
        <div style={{
          fontSize: 11.5, marginTop: 2,
          color: accent ? 'rgba(255,255,255,.7)' : 'var(--ink-muted)',
          display: 'inline-flex', alignItems: 'center', gap: 5,
        }}>
          {trend === 'up' && <span style={{ color: '#5BBB80' }}>▲</span>}
          {trend === 'down' && <span style={{ color: '#E07F70' }}>▼</span>}
          {delta}
        </div>
      )}
    </div>
  );
}

// ─── SMALL UI HELPERS ──────────────────────────────────────────────────
function DChip({ children, tone = 'neutral', icon }) {
  const tones = {
    neutral: { bg: 'var(--surface-2)', c: 'var(--ink-2)' },
    accent:  { bg: 'var(--primary-soft)', c: 'var(--primary-ink)' },
    success: { bg: 'var(--success-soft)', c: 'var(--success)' },
    warn:    { bg: 'var(--warn-soft)',    c: 'var(--warn)' },
    danger:  { bg: 'var(--danger-soft)',  c: 'var(--danger)' },
    info:    { bg: 'var(--info-soft)',    c: 'var(--info)' },
    ghost:   { bg: 'transparent', c: 'var(--ink-muted)' },
  };
  const t = tones[tone];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      background: t.bg, color: t.c, padding: '3px 9px',
      fontSize: 11, fontWeight: 600, borderRadius: 999, letterSpacing: -0.003,
      border: tone === 'ghost' ? '1px solid var(--border)' : 'none',
    }}>
      {icon && React.cloneElement(icon, { width: 12, height: 12 })}
      {children}
    </span>
  );
}

function DSectionHead({ title, subtitle, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, marginBottom: 14 }}>
      <div>
        <h2 style={{
          margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500,
          fontSize: 22, letterSpacing: -0.01, color: 'var(--ink)', lineHeight: 1.15,
        }}>{title}</h2>
        {subtitle && (
          <div style={{ fontSize: 12.5, color: 'var(--ink-muted)', marginTop: 4 }}>{subtitle}</div>
        )}
      </div>
      {right}
    </div>
  );
}

function DCard({ children, padding = 16, style }) {
  return (
    <div style={{
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderRadius: 14, padding, ...style,
    }}>{children}</div>
  );
}

// ─── SCORE PILL (desktop, smaller than mobile ring) ─────────────────────
function DScorePill({ score, size = 32 }) {
  const color = score >= 80 ? '#2F8F5A' : score >= 60 ? '#C28428' : '#C8331C';
  return (
    <div style={{
      width: size, height: size, borderRadius: 999, color: '#fff',
      background: color, fontWeight: 800, fontSize: size * 0.38,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--font-sans)', fontVariantNumeric: 'tabular-nums',
    }}>{score}</div>
  );
}

// ─── DESKTOP APP WRAPPER ────────────────────────────────────────────────
function DesktopFrame({ children, url = 'app.immobot.de', tab = 'ImmoBot' }) {
  return (
    <div className="desktop-root" style={{
      width: '100%', height: '100%', display: 'flex', minHeight: 0,
      background: 'var(--bg)', borderRadius: 12, overflow: 'hidden',
      boxShadow: '0 1px 2px rgba(31,26,20,.06), 0 14px 40px rgba(31,26,20,.10)',
      fontFamily: 'var(--font-sans)', color: 'var(--ink)',
    }}>
      {children}
    </div>
  );
}

Object.assign(window, {
  Sidebar, DTopBar, DButton, DStat, DChip, DSectionHead, DCard, DScorePill, DesktopFrame,
});
