// app.jsx — shell: nawigacja, motyw, dolna nawigacja, ramka telefonu, stany
const { useState: uA, useEffect: uEf, useRef: uRf } = React;

const SCREENS = {
  pulpit: Pulpit, ogloszenia: Ogloszenia, rezerwacje: Rezerwacje, wiecej: Wiecej,
  usterki: Usterki, ogloszenie: OgloszenieDetail, usterka: UsterkaDetail,
  'nowa-usterka': NowaUsterka, uchwala: Uchwala, powiadomienia: Powiadomienia,
  dokumenty: Dokumenty, kontakty: Kontakty, plan: PlanOsiedla,
};
const TAB_SET = ['pulpit', 'ogloszenia', 'rezerwacje', 'wiecej'];
const NAV_ITEMS = [
  { id: 'pulpit', icon: 'home', label: 'Pulpit' },
  { id: 'ogloszenia', icon: 'megaphone', label: 'Ogłoszenia' },
  { id: '__zglos', icon: 'plus', label: 'Zgłoś' },
  { id: 'rezerwacje', icon: 'calendar', label: 'Rezerwacje' },
  { id: 'wiecej', icon: 'grid', label: 'Więcej' },
];

function BottomNav({ tab, onTab, onReport }) {
  return (
    <nav className="absolute bottom-0 left-0 right-0 z-40 pt-2 pb-7 px-2 bg-surface/85 backdrop-blur-xl border-t border-border"
      style={{ paddingBottom: 26 }}>
      <div className="flex items-end justify-around">
        {NAV_ITEMS.map(it => {
          if (it.id === '__zglos') return (
            <button key="z" onClick={onReport} aria-label="Zgłoś usterkę"
              className="focusable flex flex-col items-center -mt-7 active:scale-90 transition">
              <span className="w-14 h-14 rounded-pill bg-brand text-brand-fg flex items-center justify-center shadow-md border-4 border-surface"><Icon name="plus" size={28} stroke={2.6} /></span>
              <span className="text-[10px] font-display font-700 text-brand mt-1">Zgłoś</span>
            </button>
          );
          const active = tab === it.id;
          return (
            <button key={it.id} onClick={() => onTab(it.id)} aria-current={active ? 'page' : undefined}
              className={`focusable flex flex-col items-center gap-1 w-16 py-1 transition active:scale-90 ${active ? 'text-brand' : 'text-text-muted'}`}>
              <Icon name={it.icon} size={24} stroke={active ? 2.4 : 2} fill={false} />
              <span className={`text-[10px] font-display ${active ? 'font-700' : 'font-600'}`}>{it.label}</span>
            </button>
          );
        })}
      </div>
    </nav>
  );
}

function ControlPill({ active, onClick, icon, children }) {
  return (
    <button onClick={onClick}
      className={`inline-flex items-center gap-1.5 h-9 px-3 rounded-pill text-[12.5px] font-display font-600 border transition active:scale-95
        ${active ? 'bg-brand text-brand-fg border-brand' : 'bg-surface text-text-secondary border-border hover:border-text-muted'}`}>
      {icon && <Icon name={icon} size={15} stroke={2.2} />}{children}
    </button>
  );
}

function App() {
  const [theme, setTheme] = uA(() => localStorage.getItem('osiedle-theme') || 'light');
  const [tab, setTab] = uA('pulpit');
  const [stack, setStack] = uA([]);
  const [dir, setDir] = uA('tab');
  const [toast, setToast] = uA(null);
  const [acked, setAcked] = uA({});
  const [vote, setVote] = uA(null);
  const [rating, setRating] = uA({});
  const [flags, setFlags] = uA({ fresh: false, offline: false, loading: false });
  const [scale, setScale] = uA(1);
  const [celebrate, setCelebrate] = uA(0);
  const [persona, setPersona] = uA('mieszkaniec');
  const toastTimer = uRf();
  const isMgr = persona === 'zarzadca';
  const CW = isMgr ? 1240 : 402, CH = isMgr ? 800 : 874;

  // motyw
  uEf(() => {
    document.documentElement.classList.toggle('dark', theme === 'dark');
    localStorage.setItem('osiedle-theme', theme);
  }, [theme]);

  // skalowanie ramki do okna
  uEf(() => {
    const fit = () => {
      const vh = window.innerHeight, vw = window.innerWidth;
      const s = Math.min(1, (vh - 132) / CH, (vw - 32) / CW);
      setScale(Math.max(0.34, s));
    };
    fit(); window.addEventListener('resize', fit);
    return () => window.removeEventListener('resize', fit);
  }, [persona]);

  const fireToast = (t) => {
    setToast(t); clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(null), 2600);
  };

  const ctx = {
    theme, toggleTheme: () => setTheme(t => t === 'dark' ? 'light' : 'dark'),
    flags,
    go: (name, params = {}) => { setDir('fwd'); setStack(s => [...s, { name, params }]); },
    back: () => { setDir('back'); setStack(s => s.slice(0, -1)); },
    setTab: (t) => { setDir('tab'); setStack([]); setTab(t); },
    hasStack: stack.length > 0,
    toast: fireToast,
    acked, ack: (id) => { setAcked(a => ({ ...a, [id]: new Date().toLocaleDateString('pl-PL', { day: 'numeric', month: 'long' }) + ', ' + new Date().toLocaleTimeString('pl-PL', { hour: '2-digit', minute: '2-digit' }) })); },
    vote, castVote: (c) => { setVote(c); fireToast({ msg: 'Głos oddany', icon: 'check' }); setCelebrate(n => n + 1); },
    rating, rate: (id, n) => { setRating(r => ({ ...r, [id]: n })); setCelebrate(n => n + 1); },
    celebrate: () => setCelebrate(n => n + 1),
  };

  const onTab = (id) => { setDir('tab'); setStack([]); setTab(id); };
  const current = stack.length ? stack[stack.length - 1] : { name: tab, params: {} };
  const Screen = SCREENS[current.name] || Pulpit;
  const showNav = stack.length === 0 && TAB_SET.includes(tab);
  const animClass = dir === 'fwd' ? 'om-anim-fwd' : dir === 'back' ? 'om-anim-back' : 'om-anim-tab';

  // wczytywanie demo
  const triggerLoading = () => { setFlags(f => ({ ...f, loading: true })); setStack([]); setTab('pulpit'); setTimeout(() => setFlags(f => ({ ...f, loading: false })), 1500); };

  return (
    <div className="min-h-screen flex flex-col items-center">
      {/* PASEK STEROWANIA (poza telefonem) */}
      <div className="w-full flex items-center justify-between gap-3 px-5 py-3 flex-wrap" style={{ color: 'rgb(var(--c-text))' }}>
        <div className="flex items-center gap-2.5">
          <div className="w-8 h-8 rounded-[10px] bg-brand flex items-center justify-center"><Icon name="building" size={18} className="text-brand-fg" /></div>
          <div className="leading-none">
            <p className="font-display font-800 text-[15px]" style={{ color: 'rgb(var(--c-text))' }}>e‑Osiedle</p>
            <p className="text-[11px]" style={{ color: 'rgb(var(--c-text-muted))' }}>{isMgr ? 'Panel zarządcy · desktop' : 'Prototyp mieszkańca · świeży i żywy'}</p>
          </div>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          {/* przełącznik persony */}
          <div className="flex p-1 bg-surface border border-border rounded-pill gap-1 mr-1">
            {[['mieszkaniec', 'Mieszkaniec', 'home'], ['zarzadca', 'Zarządca', 'grid']].map(([k, l, ic]) => (
              <button key={k} onClick={() => setPersona(k)} className={`inline-flex items-center gap-1.5 h-8 px-3 rounded-pill text-[12.5px] font-display font-700 transition ${persona === k ? 'bg-brand text-brand-fg' : 'text-text-secondary hover:text-text'}`}><Icon name={ic} size={15} stroke={2.2} />{l}</button>
            ))}
          </div>
          {!isMgr && <>
            <ControlPill active={flags.fresh} icon="users" onClick={() => { setFlags(f => ({ ...f, fresh: !f.fresh })); onTab('pulpit'); }}>Nowy mieszkaniec</ControlPill>
            <ControlPill active={flags.offline} icon="wifiOff" onClick={() => { setFlags(f => ({ ...f, offline: !f.offline })); onTab('pulpit'); }}>Offline</ControlPill>
            <ControlPill icon="refresh" onClick={triggerLoading}>Wczytywanie</ControlPill>
          </>}
          <ControlPill active={theme === 'dark'} icon={theme === 'dark' ? 'moon' : 'sun'} onClick={ctx.toggleTheme}>{theme === 'dark' ? 'Ciemny' : 'Jasny'}</ControlPill>
        </div>
      </div>

      {/* SCENA: telefon (mieszkaniec) lub okno desktop (zarządca) */}
      <div style={{ height: CH * scale + 8 }} className="flex items-start justify-center w-full">
        <div style={{ transform: `scale(${scale})`, transformOrigin: 'top center' }}>
          {isMgr ? (
            <DesktopFrame dark={theme === 'dark'}>
              <ManagerApp ctx={ctx} />
              {celebrate > 0 && <Confetti key={celebrate} />}
              <Toast toast={toast} />
            </DesktopFrame>
          ) : (
            <IOSDevice dark={theme === 'dark'}>
              <div className="relative h-full overflow-hidden" style={{ background: 'rgb(var(--c-bg))' }}>
                <div key={current.name + JSON.stringify(current.params)} className={`h-full ${animClass}`}>
                  <Screen ctx={ctx} params={current.params} />
                </div>
                {showNav && <BottomNav tab={tab} onTab={onTab} onReport={() => ctx.go('nowa-usterka')} />}
                {celebrate > 0 && <Confetti key={celebrate} />}
                <Toast toast={toast} />
              </div>
            </IOSDevice>
          )}
        </div>
      </div>

      <style>{`
        .om-anim-fwd  { animation: om-in-right .32s cubic-bezier(.22,1,.36,1) both; }
        .om-anim-back { animation: om-in-left  .32s cubic-bezier(.22,1,.36,1) both; }
        .om-anim-tab  { animation: om-fade .26s ease both; }
      `}</style>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
