// manager.jsx — panel zarządcy (desktop): ramka okna, shell z sidebarem, dashboard
const { useState: uMg } = React;

// ── dane przykładowe zarządcy ──
const MG_PROPS = ['Wszystkie nieruchomości', 'Zielone Tarasy', 'Osiedle Słoneczne', 'Apartamenty Park'];
const MG_KPIS = [
  { label: 'Usterki otwarte', value: '23', trend: '+3 dziś', dir: 'up', tone: 'danger', icon: 'wrench' },
  { label: 'Zgłoszenia w SLA', value: '88%', trend: '+4 pkt', dir: 'up', tone: 'success', icon: 'clock' },
  { label: 'Read‑rate komunikatów', value: '76%', trend: '−2 pkt', dir: 'down', tone: 'warning', icon: 'megaphone' },
  { label: 'Aktywne rezerwacje', value: '14', trend: '+5', dir: 'up', tone: 'info', icon: 'calendar' },
  { label: 'Frekwencja głosowań', value: '51%', trend: 'kworum ✓', dir: 'up', tone: 'accent', icon: 'vote' },
];
const MG_TREND = [{ d: 'Pn', v: 4 }, { d: 'Wt', v: 7 }, { d: 'Śr', v: 3 }, { d: 'Cz', v: 8 }, { d: 'Pt', v: 5 }, { d: 'So', v: 9 }, { d: 'Nd', v: 6 }];
const MG_ATTENTION = [
  { icon: 'wrench', tone: 'danger', title: 'Usterka #1240 — przekroczone SLA', meta: 'Elektryka · Budynek A · 4 godz. po terminie', action: 'Przypisz' },
  { icon: 'users', tone: 'info', title: '3 prośby o dostęp do konta', meta: 'Nowi mieszkańcy oczekują na weryfikację', action: 'Sprawdź' },
  { icon: 'calendar', tone: 'warning', title: '2 rezerwacje do akceptacji', meta: 'Parking gościnny · wymaga zatwierdzenia', action: 'Otwórz' },
  { icon: 'elevator', tone: 'danger', title: 'Usterka #1247 — winda, priorytet wysoki', meta: 'Serwis WindTech w drodze (do 14:00)', action: 'Podgląd' },
];
const MG_NAV = [
  { id: 'dashboard', icon: 'home', label: 'Dashboard' },
  { id: 'usterki', icon: 'wrench', label: 'Usterki', badge: '23' },
  { id: 'ogloszenia', icon: 'megaphone', label: 'Ogłoszenia' },
  { id: 'rezerwacje', icon: 'calendar', label: 'Rezerwacje' },
  { id: 'dokumenty', icon: 'fileText', label: 'Dokumenty' },
  { id: 'mieszkancy', icon: 'users', label: 'Mieszkańcy i lokale' },
  { id: 'uchwaly', icon: 'vote', label: 'Uchwały i ankiety' },
  { id: 'alert', icon: 'alert', label: 'Komunikaty awaryjne', danger: true },
  { id: 'raporty', icon: 'list', label: 'Raporty' },
  { id: 'ustawienia', icon: 'settings', label: 'Ustawienia' },
];

// ── ramka okna przeglądarki (desktop) ──
function DesktopFrame({ children, dark }) {
  return (
    <div className="rounded-[14px] overflow-hidden border border-border" style={{ width: 1240, height: 800, background: 'rgb(var(--c-bg))', boxShadow: '0 40px 90px rgba(0,0,0,0.22), 0 0 0 1px rgba(0,0,0,0.08)' }}>
      <div className="h-11 flex items-center gap-2 px-4 bg-surface border-b border-border shrink-0">
        <div className="flex gap-2"><span className="w-3 h-3 rounded-full bg-danger/70" /><span className="w-3 h-3 rounded-full bg-warning/70" /><span className="w-3 h-3 rounded-full bg-success/70" /></div>
        <div className="flex-1 flex justify-center">
          <span className="inline-flex items-center gap-2 text-[12px] text-text-muted bg-surface-muted rounded-md px-3 py-1 font-mono"><Icon name="shield" size={12} className="text-success" />panel.e‑osiedle.pl</span>
        </div>
        <span className="w-12" />
      </div>
      <div className="relative" style={{ height: 756 }}>{children}</div>
    </div>
  );
}

// ── sidebar ──
function MgSidebar({ view, setView }) {
  return (
    <aside className="w-[244px] shrink-0 h-full bg-surface border-r border-border flex flex-col">
      <div className="h-16 flex items-center gap-2.5 px-5 border-b border-border">
        <div className="w-9 h-9 rounded-[11px] bg-brand flex items-center justify-center"><Icon name="building" size={20} className="text-brand-fg" /></div>
        <div className="leading-none"><p className="font-display font-800 text-text text-[16px]">e‑Osiedle</p><p className="text-[11px] text-text-muted mt-0.5">Panel zarządcy</p></div>
      </div>
      <nav className="flex-1 overflow-auto app-scroll p-3 space-y-0.5">
        {MG_NAV.map(it => {
          const active = view === it.id;
          return (
            <button key={it.id} onClick={() => setView(it.id)}
              className={`focusable w-full flex items-center gap-3 px-3 h-10 rounded-md text-[14px] font-display font-600 transition
                ${active ? 'bg-brand/12 text-brand' : it.danger ? 'text-danger/90 hover:bg-danger/8' : 'text-text-secondary hover:bg-surface-muted hover:text-text'}`}>
              <Icon name={it.icon} size={19} stroke={active ? 2.3 : 2} />
              <span className="flex-1 text-left truncate">{it.label}</span>
              {it.badge && <span className={`text-[11px] font-700 px-1.5 py-0.5 rounded-full ${active ? 'bg-brand text-brand-fg' : 'bg-surface-muted text-text-muted'}`}>{it.badge}</span>}
            </button>
          );
        })}
      </nav>
      <div className="p-3 border-t border-border flex items-center gap-2.5">
        <Avatar name="Marek Zieliński" size={36} />
        <div className="leading-none flex-1 min-w-0"><p className="font-display font-700 text-text text-[13px] truncate">Marek Zieliński</p><p className="text-[11px] text-text-muted">Zarządca</p></div>
        <Icon name="settings" size={17} className="text-text-muted" />
      </div>
    </aside>
  );
}

// ── topbar ──
function MgTopbar({ prop, setProp, title }) {
  const [open, setOpen] = uMg(false);
  return (
    <header className="h-16 shrink-0 border-b border-border bg-surface/80 backdrop-blur-xl flex items-center gap-4 px-6 relative z-30">
      <h1 className="font-display font-800 text-text text-[20px]">{title}</h1>
      <div className="relative">
        <button onClick={() => setOpen(!open)} className="focusable flex items-center gap-2 h-9 px-3 rounded-md border border-border bg-surface text-[13px] font-display font-600 text-text hover:bg-surface-muted">
          <Icon name="building" size={15} className="text-brand" />{prop}<Icon name="chevronDown" size={15} className="text-text-muted" />
        </button>
        {open && <div className="absolute top-11 left-0 w-60 bg-surface border border-border rounded-lg shadow-lg p-1.5 z-40">
          {MG_PROPS.map(p => <button key={p} onClick={() => { setProp(p); setOpen(false); }} className={`focusable w-full text-left px-3 h-9 rounded-md text-[13px] font-600 flex items-center gap-2 ${p === prop ? 'bg-brand/10 text-brand' : 'text-text-secondary hover:bg-surface-muted'}`}>{p === prop && <Icon name="check" size={14} />}<span className={p === prop ? '' : 'ml-5'}>{p}</span></button>)}
        </div>}
      </div>
      <div className="flex-1 max-w-md relative">
        <Icon name="search" size={17} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
        <input placeholder="Szukaj globalnie…" className="focusable w-full h-9 pl-10 pr-3 rounded-md bg-surface-muted border border-transparent focus:border-border text-[13px] text-text placeholder:text-text-muted" />
      </div>
      <button className="focusable relative w-10 h-10 rounded-md flex items-center justify-center text-text-secondary hover:bg-surface-muted"><Icon name="bell" size={20} /><span className="absolute top-2 right-2 w-2 h-2 rounded-full bg-danger" /></button>
    </header>
  );
}

// ── DASHBOARD ──
function MgDashboard({ ctx, setView }) {
  const maxV = Math.max(...MG_TREND.map(t => t.v));
  return (
    <div className="flex-1 overflow-auto app-scroll p-6">
      {/* KPI */}
      <div className="grid grid-cols-5 gap-4 mb-6">
        {MG_KPIS.map(k => (
          <Card key={k.label} className="p-4">
            <div className="flex items-center justify-between mb-3">
              <span className={`w-10 h-10 rounded-[12px] flex items-center justify-center ${tone(k.tone).bg} ${tone(k.tone).text}`}><Icon name={k.icon} size={20} /></span>
              <span className={`inline-flex items-center gap-0.5 text-[12px] font-display font-700 ${k.dir === 'up' ? (k.tone === 'danger' || k.tone === 'warning' ? 'text-danger' : 'text-success') : 'text-warning'}`}>
                <Icon name={k.dir === 'up' ? 'chevronRight' : 'chevronRight'} size={12} style={{ transform: k.dir === 'up' ? 'rotate(-45deg)' : 'rotate(45deg)' }} />{k.trend}
              </span>
            </div>
            <p className="font-display font-800 text-text text-[30px] leading-none">{k.value}</p>
            <p className="text-[12.5px] text-text-secondary mt-1.5">{k.label}</p>
          </Card>
        ))}
      </div>

      <div className="grid grid-cols-3 gap-5">
        {/* lewa: wykres + wymaga uwagi */}
        <div className="col-span-2 space-y-5">
          <Card className="p-5">
            <div className="flex items-center justify-between mb-4">
              <div><h2 className="font-display font-700 text-text text-[16px]">Trend zgłoszeń</h2><p className="text-[12px] text-text-muted">Ostatnie 7 dni · nowe usterki</p></div>
              <Badge tone="brand" dot>Ten tydzień</Badge>
            </div>
            <div className="flex items-end justify-between gap-3 h-40 pt-2">
              {MG_TREND.map((t, i) => (
                <div key={t.d} className="flex-1 flex flex-col items-center gap-2">
                  <div className="w-full flex items-end justify-center" style={{ height: 130 }}>
                    <div className="w-full max-w-[40px] rounded-t-md bg-gradient-to-t from-brand to-brand/60" style={{ height: `${(t.v / maxV) * 100}%`, animation: `om-grow .7s cubic-bezier(.22,1,.36,1) ${i * 0.05}s both` }} title={`${t.v} zgłoszeń`} />
                  </div>
                  <span className="text-[11px] font-display font-600 text-text-muted">{t.d}</span>
                </div>
              ))}
            </div>
          </Card>

          <Card className="p-5">
            <h2 className="font-display font-700 text-text text-[16px] mb-3">Wymaga uwagi</h2>
            <div className="space-y-2">
              {MG_ATTENTION.map((a, i) => (
                <div key={i} className="flex items-center gap-3 p-3 rounded-lg border border-border hover:bg-surface-muted transition">
                  <span className={`w-10 h-10 rounded-[12px] flex items-center justify-center shrink-0 ${tone(a.tone).bg} ${tone(a.tone).text}`}><Icon name={a.icon} size={19} /></span>
                  <div className="flex-1 min-w-0"><p className="font-display font-700 text-text text-[14px] truncate">{a.title}</p><p className="text-[12px] text-text-muted truncate">{a.meta}</p></div>
                  <Btn size="sm" variant="secondary" onClick={() => setView('usterki')}>{a.action}</Btn>
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* prawa: skróty + aktywność */}
        <div className="space-y-5">
          <Card className="p-5">
            <h2 className="font-display font-700 text-text text-[16px] mb-3">Szybkie akcje</h2>
            <div className="space-y-2.5">
              <Btn block icon="megaphone" onClick={() => setView('ogloszenia')}>Nowy komunikat</Btn>
              <Btn block variant="danger" icon="alert" onClick={() => setView('alert')}>Komunikat awaryjny</Btn>
              <Btn block variant="secondary" icon="vote" onClick={() => setView('uchwaly')}>Nowa uchwała</Btn>
            </div>
          </Card>
          <Card className="p-5">
            <h2 className="font-display font-700 text-text text-[16px] mb-3">Ostatnia aktywność</h2>
            <div className="space-y-3.5">
              {[['A. Kowalska potwierdziła komunikat', '5 min temu', 'success', 'checkCircle'], ['Nowe zgłoszenie #1251', '3 godz. temu', 'cat-czystosc', 'wrench'], ['Serwis WindTech przyjął zlecenie', '4 godz. temu', 'cat-winda', 'wrench'], ['Opublikowano sprawozdanie 2025', 'wczoraj', 'info', 'fileText']].map((a, i) => (
                <div key={i} className="flex items-start gap-3">
                  <span className={`w-7 h-7 rounded-full flex items-center justify-center shrink-0 ${tone(a[2]).bg} ${tone(a[2]).text}`}><Icon name={a[3]} size={14} /></span>
                  <div className="min-w-0"><p className="text-[13px] text-text leading-snug">{a[0]}</p><p className="text-[11px] text-text-muted">{a[1]}</p></div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

// ── shell ──
function ManagerApp({ ctx }) {
  const [view, setView] = uMg('dashboard');
  const [prop, setProp] = uMg('Wszystkie nieruchomości');
  const titles = { dashboard: 'Dashboard', usterki: 'Kolejka usterek', alert: 'Komunikat awaryjny', ogloszenia: 'Ogłoszenia', rezerwacje: 'Rezerwacje', dokumenty: 'Dokumenty', mieszkancy: 'Mieszkańcy i lokale', uchwaly: 'Uchwały i ankiety', raporty: 'Raporty', ustawienia: 'Ustawienia' };
  let body;
  if (view === 'dashboard') body = <MgDashboard ctx={ctx} setView={setView} />;
  else if (view === 'usterki') body = <MgKolejka ctx={ctx} />;
  else if (view === 'alert') body = <MgAlert ctx={ctx} />;
  else body = <MgStub label={titles[view]} />;
  return (
    <div className="flex h-full">
      <MgSidebar view={view} setView={setView} />
      <div className="flex-1 flex flex-col min-w-0">
        <MgTopbar prop={prop} setProp={setProp} title={titles[view]} />
        {body}
      </div>
    </div>
  );
}

function MgStub({ label }) {
  return <div className="flex-1 flex items-center justify-center"><EmptyState icon="settings" title={`${label}`}>Ta sekcja panelu jest częścią pełnego zakresu — w prototypie skupiamy się na Dashboardzie, Kolejce usterek i Komunikacie awaryjnym.</EmptyState></div>;
}

Object.assign(window, { DesktopFrame, ManagerApp, MgDashboard, MG_KPIS, MG_TREND });
