// manager2.jsx — kolejka usterek (master-detail + SLA) i komunikat awaryjny
const { useState: uM2 } = React;

const MG_FAULTS = [
  { id: 1240, cat: 'elektryka', title: 'Brak światła na klatce schodowej', location: 'Budynek A · klatka 1', reporter: 'M. Nowak', status: 'przyjete', assignee: null, priority: 'wysoki', sla: { label: 'Po terminie · 4h', tone: 'danger' }, photos: 1, desc: 'Od wczoraj wieczorem nie działa oświetlenie na klatce. Na schodach jest ciemno — zagrożenie dla mieszkańców.' },
  { id: 1247, cat: 'winda', title: 'Winda B2 zatrzymuje się między piętrami', location: 'Budynek B · klatka 2', reporter: 'A. Kowalska', status: 'wtrakcie', assignee: 'WindTech', priority: 'wysoki', sla: { label: '4h do przekroczenia', tone: 'warning' }, photos: 1, desc: 'Winda zatrzymuje się między 3. a 4. piętrem i nie reaguje na przyciski.' },
  { id: 1236, cat: 'elektryka', title: 'Migająca lampa na parkingu', location: 'Parking podziemny', reporter: 'D. Sokół', status: 'wtrakcie', assignee: 'ElektroPro', priority: 'sredni', sla: { label: '1h do przekroczenia', tone: 'warning' }, photos: 0, desc: 'Świetlówka miga, prawdopodobnie do wymiany.' },
  { id: 1248, cat: 'hydraulika', title: 'Przeciek przy pionie w garażu', location: 'Garaż -1', reporter: 'K. Zając', status: 'wtrakcie', assignee: 'Hydro-Fix', priority: 'sredni', sla: { label: '2h do przekroczenia', tone: 'warning' }, photos: 2, desc: 'Woda zbiera się pod rurą głównego pionu wodnego.' },
  { id: 1251, cat: 'czystosc', title: 'Rozsypane śmieci przy wiacie', location: 'Wiata B', reporter: 'P. Lis', status: 'nowe', assignee: null, priority: 'niski', sla: { label: 'W normie · 20h', tone: 'success' }, photos: 1, desc: 'Worki rozerwane, śmieci wokół wiaty na odpady.' },
  { id: 1245, cat: 'inne', title: 'Uszkodzony domofon przy wejściu', location: 'Budynek C · wejście', reporter: 'J. Wójcik', status: 'nowe', assignee: null, priority: 'sredni', sla: { label: 'W normie · 11h', tone: 'success' }, photos: 0, desc: 'Domofon nie otwiera drzwi po naciśnięciu.' },
  { id: 1238, cat: 'zielone', title: 'Połamana ławka na dziedzińcu', location: 'Dziedziniec A', reporter: 'T. Mak', status: 'przyjete', assignee: null, priority: 'niski', sla: { label: 'W normie · 2 dni', tone: 'success' }, photos: 1, desc: 'Deska siedziska jest pęknięta.' },
  { id: 1243, cat: 'hydraulika', title: 'Cieknący kran w łazience', location: 'Lokal B/24', reporter: 'A. Kowalska', status: 'rozwiazane', assignee: 'Hydro-Fix', priority: 'sredni', sla: { label: 'Zamknięte w SLA', tone: 'success' }, photos: 2, desc: 'Wymieniono uszczelkę i głowicę.' },
];
const MG_SERVICES = ['WindTech', 'Hydro-Fix', 'ElektroPro', 'Czysto-Serwis', 'Zieleń24'];

function MgSelect({ value, onChange, options, placeholder }) {
  return (
    <div className="relative">
      <select value={value || ''} onChange={e => onChange(e.target.value)}
        className="focusable appearance-none w-full h-10 pl-3 pr-9 rounded-md bg-surface border border-border text-[13px] font-display font-600 text-text">
        {placeholder && <option value="">{placeholder}</option>}
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
      <Icon name="chevronDown" size={15} className="absolute right-3 top-1/2 -translate-y-1/2 text-text-muted pointer-events-none" />
    </div>
  );
}

// ── KOLEJKA USTEREK (master-detail) ──
function MgKolejka({ ctx }) {
  const [filter, setFilter] = uM2('all');
  const [onlySla, setOnlySla] = uM2(false);
  const [statuses, setStatuses] = uM2({});
  const [assignees, setAssignees] = uM2({});
  const [selId, setSel] = uM2(MG_FAULTS[0].id);
  const getStatus = f => statuses[f.id] || f.status;
  const getAssignee = f => assignees[f.id] !== undefined ? assignees[f.id] : f.assignee;

  const filters = [['all', 'Wszystkie'], ['nowe', 'Nowe'], ['przyjete', 'Przyjęte'], ['wtrakcie', 'W trakcie'], ['rozwiazane', 'Rozwiązane']];
  const list = MG_FAULTS.filter(f => (filter === 'all' || getStatus(f) === filter) && (!onlySla || f.sla.tone === 'danger'));
  const sel = MG_FAULTS.find(f => f.id === selId);

  return (
    <div className="flex-1 flex min-h-0">
      {/* lewy panel: filtry + lista */}
      <div className="w-[440px] shrink-0 border-r border-border flex flex-col min-h-0">
        <div className="p-4 border-b border-border space-y-2.5">
          <div className="flex gap-2 overflow-x-auto app-scroll">
            {filters.map(([k, l]) => <Chip key={k} active={filter === k} onClick={() => setFilter(k)}>{l}</Chip>)}
          </div>
          <button onClick={() => setOnlySla(!onlySla)} className={`focusable inline-flex items-center gap-1.5 h-8 px-3 rounded-pill text-[12.5px] font-display font-600 border transition ${onlySla ? 'bg-danger text-white border-danger' : 'bg-surface text-danger border-danger/40'}`}>
            <Icon name="alert" size={14} />Tylko po terminie
          </button>
        </div>
        <div className="flex-1 overflow-auto app-scroll p-3 space-y-2">
          {list.length === 0 ? <div className="pt-10"><EmptyState icon="checkCircle" title="Brak zgłoszeń">Żadne zgłoszenie nie pasuje do wybranych filtrów.</EmptyState></div>
          : list.map(f => {
            const st = FAULT_STATUS[getStatus(f)], cat = FAULT_CATS[f.cat], on = selId === f.id;
            return (
              <button key={f.id} onClick={() => setSel(f.id)}
                className={`focusable w-full text-left p-3 rounded-lg border transition ${on ? 'border-brand bg-brand/8 shadow-sm' : 'border-border bg-surface hover:bg-surface-muted'}`}>
                <div className="flex items-center gap-2 mb-1">
                  <span className={`w-8 h-8 rounded-[10px] flex items-center justify-center shrink-0 ${tone(cat.color).bg} ${tone(cat.color).text}`}><Icon name={cat.icon} size={16} /></span>
                  <span className="font-mono text-[11px] text-text-muted">#{f.id}</span>
                  <Badge tone={st.tone} dot size="sm">{st.label}</Badge>
                  <span className="ml-auto"><Badge tone={f.sla.tone} icon={f.sla.tone === 'success' ? 'checkCircle' : 'clock'} size="sm">{f.sla.label}</Badge></span>
                </div>
                <p className="font-display font-700 text-text text-[13.5px] leading-tight line-clamp-1">{f.title}</p>
                <p className="text-[11.5px] text-text-muted mt-0.5">{f.location} · {f.reporter}{getAssignee(f) ? ` · ${getAssignee(f)}` : ''}</p>
              </button>
            );
          })}
        </div>
      </div>

      {/* prawy panel: szczegół */}
      <div className="flex-1 overflow-auto app-scroll p-6 min-w-0">
        {sel && (() => {
          const st = FAULT_STATUS[getStatus(sel)], cat = FAULT_CATS[sel.cat];
          return (
            <div className="max-w-2xl">
              <div className="flex items-center gap-2 flex-wrap mb-2">
                <span className="font-mono text-[13px] text-text-muted">#{sel.id}</span>
                <Badge tone={cat.color} icon={cat.icon}>{cat.label}</Badge>
                <Badge tone={st.tone} dot>{st.label}</Badge>
                {sel.priority === 'wysoki' && <Badge tone="danger" icon="alert">Priorytet wysoki</Badge>}
                <span className="ml-auto"><Badge tone={sel.sla.tone} icon={sel.sla.tone === 'success' ? 'checkCircle' : 'clock'}>{sel.sla.label}</Badge></span>
              </div>
              <h2 className="font-display font-800 text-text text-[22px] leading-tight">{sel.title}</h2>
              <p className="text-[13px] text-text-secondary flex items-center gap-1.5 mt-1.5"><Icon name="mapPin" size={14} className="text-text-muted" />{sel.location} · zgłosił(a): {sel.reporter}</p>

              {sel.photos > 0 && <div className="flex gap-3 mt-4">{Array.from({ length: sel.photos }).map((_, i) => <Photo key={i} label={`zdjęcie ${i + 1}`} h={120} className="w-44" />)}</div>}
              <Card className="p-4 mt-4"><p className="text-[14px] text-text leading-relaxed">{sel.desc}</p></Card>

              {/* akcje triażu */}
              <div className="grid grid-cols-2 gap-4 mt-5">
                <div>
                  <label className="text-[12px] font-display font-700 text-text-muted uppercase tracking-wide">Przypisz do serwisu</label>
                  <div className="mt-1.5"><MgSelect value={getAssignee(sel) || ''} placeholder="— wybierz serwis —" options={MG_SERVICES.map(s => ({ value: s, label: s }))}
                    onChange={v => { setAssignees(a => ({ ...a, [sel.id]: v })); ctx.toast({ msg: `Przypisano do: ${v}`, icon: 'check' }); }} /></div>
                </div>
                <div>
                  <label className="text-[12px] font-display font-700 text-text-muted uppercase tracking-wide">Zmień status</label>
                  <div className="mt-1.5"><MgSelect value={getStatus(sel)} options={FAULT_FLOW.map(s => ({ value: s, label: FAULT_STATUS[s].label }))}
                    onChange={v => { setStatuses(s => ({ ...s, [sel.id]: v })); ctx.toast({ msg: `Status: ${FAULT_STATUS[v].label}`, icon: 'check' }); }} /></div>
                </div>
              </div>
              <div className="flex gap-2.5 mt-4">
                <Btn variant="secondary" icon="users" onClick={() => ctx.toast({ msg: 'Otwarto kartę zgłaszającego', icon: 'users', tone: 'info' })}>Kontakt z mieszkańcem</Btn>
                <Btn variant="ghost" icon="paperclip" onClick={() => ctx.toast({ msg: 'Oznaczono jako duplikat', icon: 'check', tone: 'info' })}>Scal jako duplikat</Btn>
              </div>
            </div>
          );
        })()}
      </div>
    </div>
  );
}

// ── KOMUNIKAT AWARYJNY (broadcast) ──
const MG_TEMPLATES = [
  { id: 'woda', icon: 'droplet', label: 'Awaria wody', text: 'Informujemy o awarii sieci wodociągowej. Woda będzie niedostępna do czasu usunięcia usterki. Pracujemy nad jak najszybszym przywróceniem dostaw.' },
  { id: 'prad', icon: 'zap', label: 'Brak prądu', text: 'Wystąpiła awaria zasilania. Trwa ustalanie przyczyny z dostawcą energii. O przywróceniu zasilania poinformujemy osobnym komunikatem.' },
  { id: 'winda', icon: 'elevator', label: 'Awaria windy', text: 'Winda została wyłączona ze względów bezpieczeństwa. Serwis został powiadomiony. Prosimy o korzystanie z klatki schodowej.' },
  { id: 'inny', icon: 'alert', label: 'Inny', text: '' },
];
const SCOPE_COUNT = { all: 248, budynek: 96, klatka: 24 };

function MgAlert({ ctx }) {
  const [tpl, setTpl] = uM2(null);
  const [content, setContent] = uM2('');
  const [scope, setScope] = uM2('all');
  const [ch, setCh] = uM2({ push: true, email: true, sms: false });
  const [ack, setAck] = uM2(true);
  const [modal, setModal] = uM2(false);
  const [report, setReport] = uM2(false);

  const count = SCOPE_COUNT[scope];
  const chanList = [ch.push && 'Push', ch.email && 'E‑mail', ch.sms && 'SMS'].filter(Boolean);
  const canSend = content.trim().length > 3 && chanList.length > 0;

  if (report) return (
    <div className="flex-1 overflow-auto app-scroll p-6">
      <div className="max-w-2xl mx-auto">
        <div className="flex items-center gap-3 mb-5">
          <span className="w-12 h-12 rounded-full bg-success/15 text-success flex items-center justify-center"><DrawCheck size={30} ring={false} stroke={3.4} /></span>
          <div><h2 className="font-display font-800 text-text text-[22px]">Alert wysłany</h2><p className="text-[13px] text-text-secondary">Do {count} mieszkańców przez {chanList.join(' + ')}</p></div>
        </div>
        {[['Dostarczono', 240, 'success'], ack ? ['Potwierdziło zapoznanie', 156, 'brand'] : null, ['Otworzyło', 198, 'info']].filter(Boolean).map(([l, n, t]) => (
          <Card key={l} className="p-4 mb-3">
            <div className="flex justify-between text-[13px] mb-2"><span className="font-display font-700 text-text">{l}</span><span className="font-mono text-text-secondary">{n} / {count} ({Math.round(n / count * 100)}%)</span></div>
            <div className="h-2.5 rounded-full bg-surface-muted overflow-hidden"><div className={`h-full rounded-full ${tone(t).dot}`} style={{ width: `${n / count * 100}%`, animation: 'om-grow .8s cubic-bezier(.22,1,.36,1) both' }} /></div>
          </Card>
        ))}
        <Btn className="mt-3" variant="secondary" icon="arrowLeft" onClick={() => { setReport(false); setContent(''); setTpl(null); }}>Nowy komunikat</Btn>
      </div>
    </div>
  );

  return (
    <div className="flex-1 overflow-auto app-scroll p-6 relative">
      {/* baner trybu alarmowego */}
      <div className="flex items-center gap-3 rounded-xl p-3.5 mb-5 bg-danger/10 border border-danger/30">
        <span className="w-10 h-10 rounded-[12px] bg-danger text-white flex items-center justify-center shrink-0"><Icon name="alert" size={22} /></span>
        <div><p className="font-display font-800 text-danger text-[15px]">Tryb komunikatu awaryjnego</p><p className="text-[12.5px] text-text-secondary">Wiadomość trafi natychmiast wybranymi kanałami. Używaj tylko w sytuacjach pilnych.</p></div>
      </div>

      <div className="grid grid-cols-3 gap-6">
        {/* formularz */}
        <div className="col-span-2 space-y-5">
          <div>
            <p className="text-[13px] font-display font-700 text-text mb-2">Szybki szablon</p>
            <div className="grid grid-cols-4 gap-2.5">
              {MG_TEMPLATES.map(t => (
                <button key={t.id} onClick={() => { setTpl(t.id); setContent(t.text); }}
                  className={`focusable flex flex-col items-center gap-2 py-3.5 rounded-lg border transition active:scale-95 ${tpl === t.id ? 'border-danger bg-danger/8' : 'border-border bg-surface hover:border-text-muted'}`}>
                  <span className={`w-10 h-10 rounded-[12px] flex items-center justify-center ${tpl === t.id ? 'bg-danger text-white' : 'bg-surface-muted text-text-secondary'}`}><Icon name={t.icon} size={20} /></span>
                  <span className={`text-[12px] font-display font-700 ${tpl === t.id ? 'text-danger' : 'text-text-secondary'}`}>{t.label}</span>
                </button>
              ))}
            </div>
          </div>
          <div>
            <p className="text-[13px] font-display font-700 text-text mb-2">Treść komunikatu</p>
            <textarea value={content} onChange={e => setContent(e.target.value)} rows={5} placeholder="Opisz krótko sytuację i zalecane działania…"
              className="focusable w-full p-3.5 rounded-md bg-surface border border-border text-[14px] text-text placeholder:text-text-muted resize-none leading-relaxed" />
          </div>
          <div>
            <p className="text-[13px] font-display font-700 text-text mb-2">Zasięg</p>
            <div className="flex gap-2.5">
              {[['all', 'Cała wspólnota'], ['budynek', 'Budynek B'], ['klatka', 'Klatka B2']].map(([k, l]) =>
                <button key={k} onClick={() => setScope(k)} className={`focusable flex-1 py-3 rounded-lg border text-[13px] font-display font-700 transition ${scope === k ? 'border-brand bg-brand/8 text-brand' : 'border-border bg-surface text-text-secondary hover:border-text-muted'}`}>
                  {l}<span className="block text-[11px] font-500 text-text-muted mt-0.5">{SCOPE_COUNT[k]} odbiorców</span>
                </button>)}
            </div>
          </div>
          <div>
            <p className="text-[13px] font-display font-700 text-text mb-2">Kanały wysyłki</p>
            <div className="space-y-2">
              {[['push', 'Push', 'bell', null], ['email', 'E‑mail', 'inbox', null], ['sms', 'SMS', 'phone', 'płatny dodatek']].map(([k, l, ic, note]) => (
                <div key={k} className="flex items-center gap-3 p-3 rounded-lg border border-border bg-surface">
                  <span className="w-9 h-9 rounded-[10px] bg-surface-muted text-text-secondary flex items-center justify-center"><Icon name={ic} size={18} /></span>
                  <span className="font-display font-700 text-text text-[14px]">{l}</span>
                  {note && <span className="text-[11px] font-mono px-1.5 py-0.5 rounded bg-accent-warm/15 text-accent-warm">{note}</span>}
                  <span className="ml-auto"><Toggle checked={ch[k]} onChange={v => setCh(c => ({ ...c, [k]: v }))} label={l} /></span>
                </div>
              ))}
            </div>
          </div>
          <div className="flex items-center gap-3 p-3 rounded-lg border border-border bg-surface">
            <span className="w-9 h-9 rounded-[10px] bg-surface-muted text-text-secondary flex items-center justify-center"><Icon name="checkCircle" size={18} /></span>
            <div className="flex-1"><p className="font-display font-700 text-text text-[14px]">Wymagaj potwierdzenia</p><p className="text-[12px] text-text-muted">Mieszkańcy potwierdzają zapoznanie się z komunikatem</p></div>
            <Toggle checked={ack} onChange={setAck} label="Wymagaj potwierdzenia" />
          </div>
          <Btn variant="danger" size="lg" icon="send" disabled={!canSend} onClick={() => setModal(true)}>Wyślij alert do {count} mieszkańców</Btn>
        </div>

        {/* podgląd push */}
        <div>
          <p className="text-[13px] font-display font-700 text-text mb-2">Podgląd powiadomienia</p>
          <div className="rounded-xl p-4 bg-surface-muted border border-border">
            <div className="rounded-2xl bg-surface shadow-md border border-border p-3.5">
              <div className="flex items-center gap-2 mb-1.5">
                <span className="w-7 h-7 rounded-[8px] bg-danger text-white flex items-center justify-center"><Icon name="alert" size={15} /></span>
                <span className="font-display font-800 text-text text-[12px]">e‑Osiedle · ALERT</span>
                <span className="ml-auto text-[10px] text-text-muted">teraz</span>
              </div>
              <p className="font-display font-700 text-text text-[13px] leading-snug">{MG_TEMPLATES.find(t => t.id === tpl)?.label || 'Komunikat awaryjny'}</p>
              <p className="text-[12px] text-text-secondary leading-snug mt-0.5 line-clamp-4">{content || 'Treść komunikatu pojawi się tutaj…'}</p>
            </div>
            <p className="text-[11px] text-text-muted text-center mt-3">Tak zobaczą komunikat mieszkańcy</p>
          </div>
        </div>
      </div>

      {/* modal potwierdzenia */}
      {modal && (
        <div className="absolute inset-0 z-50 flex items-center justify-center anim-fade" onClick={() => setModal(false)}>
          <div className="absolute inset-0 bg-black/45" />
          <div className="relative bg-surface rounded-2xl shadow-lg w-[420px] p-6 anim-rise" onClick={e => e.stopPropagation()}>
            <span className="flex items-center justify-center w-14 h-14 rounded-full bg-danger/12 text-danger mx-auto mb-4"><Icon name="alert" size={28} /></span>
            <h3 className="font-display font-800 text-text text-[19px] text-center">Wysłać komunikat awaryjny?</h3>
            <p className="text-[14px] text-text-secondary text-center mt-2 leading-snug">Wyślesz do <b className="text-text">{count} mieszkańców</b> przez <b className="text-text">{chanList.join(' + ')}</b>. Tej akcji nie można cofnąć.</p>
            <div className="flex gap-3 mt-5">
              <Btn variant="secondary" block onClick={() => setModal(false)}>Anuluj</Btn>
              <Btn variant="danger" block icon="send" onClick={() => { setModal(false); setReport(true); ctx.toast({ msg: 'Alert wysłany', icon: 'check' }); }}>Wyślij teraz</Btn>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { MgKolejka, MgAlert, MG_FAULTS, MG_TEMPLATES });
