// screens2.jsx — formularze, usterki, rezerwacje, głosowanie, powiadomienia, więcej
const { useState: u2, useMemo: uM } = React;

// Lokalny fallback AI (gdy window.claude niedostępne) — heurystyka słów kluczowych
function aiHeuristic(text) {
  const t = text.toLowerCase();
  const map = [
    ['hydraulika', ['kran','wod','ciek','rur','kanaliz','przeciek','spłucz','toalet','grzejnik','ogrzewan','zalew','wyciek']],
    ['elektryka', ['prąd','światł','lamp','gniazd','bezpiecznik','elektr','oświetl','iskrz','domofon']],
    ['winda', ['wind','dźwig']],
    ['czystosc', ['brud','śmiec','sprzątan','czysto','odpad','graffiti','bałagan']],
    ['zielone', ['drzew','gałąź','traw','krzew','liści','zieleń','żywopłot','chwast']],
  ];
  let category = 'inne';
  for (const [k, kw] of map) { if (kw.some(w => t.includes(w))) { category = k; break; } }
  let priority = 'sredni';
  if (/(awari|nie działa|zatrzym|iskrz|zalew|niebezpiecz|pilne|natychmiast|wyciek|grozi)/.test(t)) priority = 'wysoki';
  else if (/(drobn|lekk|czasem|delikatn|od czasu)/.test(t)) priority = 'niski';
  const location = /(mój|moim|mieszkani|lokal|łazienc|kuchni|salon|sypialn|u mnie)/.test(t) ? 'lokal' : 'wspolna';
  const description = text.trim().charAt(0).toUpperCase() + text.trim().slice(1) + (/[.!?]$/.test(text.trim()) ? '' : '.');
  return { category, priority, location, place: '', description };
}

// ════════════════════ NOWA USTERKA (B5) ════════════════════
function NowaUsterka({ ctx }) {
  const [photos, setPhotos] = u2([]);
  const [cat, setCat] = u2(null);
  const [loc, setLoc] = u2('wspolna');
  const [place, setPlace] = u2('');
  const [desc, setDesc] = u2('');
  const [prio, setPrio] = u2('sredni');
  const [busy, setBusy] = u2(false);
  const [submitted, setSub] = u2(false);
  const [sent, setSent] = u2(false);
  const [ai, setAi] = u2('');
  const [aiBusy, setAiBusy] = u2(false);
  const [aiNote, setAiNote] = u2(false);

  const errCat = submitted && !cat;
  const errDesc = submitted && desc.trim().length < 5;

  const runAI = async () => {
    if (!ai.trim() || aiBusy) return;
    setAiBusy(true); setAiNote(false);
    let res = null;
    try {
      if (window.claude && window.claude.complete) {
        const prompt = `Jesteś asystentem zgłoszeń usterek we wspólnocie mieszkaniowej. Na podstawie opisu mieszkańca zwróć WYŁĄCZNIE poprawny JSON (bez markdown, bez komentarzy) o polach:
{"category": jedna z ["hydraulika","elektryka","winda","czystosc","zielone","inne"],
 "priority": jedna z ["niski","sredni","wysoki"],
 "location": "wspolna" lub "lokal",
 "place": krótka lokalizacja po polsku jeśli część wspólna, inaczej "",
 "description": rozwinięty, rzeczowy opis problemu po polsku, 1-2 zdania}
Opis mieszkańca: "${ai.replace(/"/g, "'")}"`;
        const out = await Promise.race([
          window.claude.complete(prompt),
          new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), 8000)),
        ]);
        const m = out.match(/\{[\s\S]*\}/);
        if (m) res = JSON.parse(m[0]);
      }
    } catch (e) { res = null; }
    if (!res) { await new Promise(r => setTimeout(r, 650)); res = aiHeuristic(ai); }
    if (FAULT_CATS[res.category]) setCat(res.category);
    if (['niski','sredni','wysoki'].includes(res.priority)) setPrio(res.priority);
    setLoc(res.location === 'lokal' ? 'lokal' : 'wspolna');
    if (res.location !== 'lokal' && res.place) setPlace(res.place);
    if (res.description) setDesc(res.description);
    setAiBusy(false); setAiNote(true);
  };

  const submit = () => {
    setSub(true);
    if (!cat || desc.trim().length < 5) return;
    setBusy(true);
    setTimeout(() => { setBusy(false); setSent(true); ctx.celebrate(); setTimeout(() => { ctx.toast({ msg: 'Zgłoszenie wysłane — #1252', icon: 'check' }); ctx.back(); }, 1500); }, 950);
  };

  return (
    <div className="flex flex-col h-full bg-bg">
      <AppBar title="Nowa usterka" onBack={ctx.back} />
      <div className="flex-1 overflow-auto app-scroll px-4 pb-32">
        {/* AI — zgłoś jednym zdaniem */}
        <div className="mt-4 rounded-xl border border-accent/30 p-3.5 bg-gradient-to-br from-accent/12 to-brand/8">
          <div className="flex items-center gap-2 mb-2.5">
            <span className="text-accent"><Icon name="sparkles" size={18} stroke={2} /></span>
            <p className="font-display font-700 text-text text-[14px]">Zgłoś jednym zdaniem</p>
            <span className="ml-auto text-[10px] font-mono font-600 px-1.5 py-0.5 rounded bg-accent/15 text-accent">AI</span>
          </div>
          <div className="flex gap-2">
            <input value={ai} onChange={e => setAi(e.target.value)} onKeyDown={e => e.key === 'Enter' && runAI()}
              placeholder="np. cieknie kran w łazience od rana"
              className="focusable flex-1 h-11 px-3.5 rounded-md bg-surface border border-border text-[14px] text-text placeholder:text-text-muted" />
            <Btn size="md" loading={aiBusy} icon={aiBusy ? null : 'sparkles'} onClick={runAI} disabled={!ai.trim()}>{aiBusy ? '' : 'Uzupełnij'}</Btn>
          </div>
          {aiNote && <p className="anim-rise text-[12px] font-display font-600 text-accent mt-2 flex items-center gap-1.5"><Icon name="checkCircle" size={14} stroke={2.4} />Uzupełniono — sprawdź poniżej i wyślij</p>}
        </div>

        {/* 1. zdjęcia */}
        <p className="text-[13px] font-display font-700 text-text mt-6 mb-2">Zdjęcia <span className="text-text-muted font-500">(opcjonalnie)</span></p>
        <div className="flex gap-2.5 flex-wrap">
          {photos.map((p,i) => (
            <div key={i} className="relative">
              <Photo label="zdjęcie" h={84} className="w-[84px]" rounded="rounded-md" />
              <button aria-label="Usuń" onClick={() => setPhotos(photos.filter((_,j)=>j!==i))} className="absolute -top-1.5 -right-1.5 w-6 h-6 rounded-full bg-text text-bg flex items-center justify-center shadow"><Icon name="x" size={13} stroke={2.6} /></button>
            </div>
          ))}
          {photos.length < 4 && (
            <button onClick={() => setPhotos([...photos, 1])}
              className="focusable w-[84px] h-[84px] rounded-md border-2 border-dashed border-border flex flex-col items-center justify-center gap-1 text-text-muted hover:border-brand hover:text-brand transition active:scale-95">
              <Icon name="camera" size={24} /><span className="text-[10px] font-display font-600">Dodaj</span>
            </button>
          )}
        </div>

        {/* 2. kategoria */}
        <p className="text-[13px] font-display font-700 text-text mt-6 mb-2">Kategoria{errCat && <span className="text-danger font-500"> — wybierz kategorię</span>}</p>
        <div className={`grid grid-cols-3 gap-2.5 ${errCat ? 'ring-1 ring-danger rounded-lg p-1 -m-1' : ''}`}>
          {Object.entries(FAULT_CATS).map(([k,v]) => {
            const on = cat === k;
            return (
              <button key={k} onClick={() => setCat(k)}
                className={`focusable flex flex-col items-center gap-1.5 py-3 rounded-lg border transition-all active:scale-95 ${on ? 'border-brand bg-brand/8' : 'border-border bg-surface hover:border-text-muted'}`}>
                <span className={`flex items-center justify-center w-10 h-10 rounded-[12px] ${tone(v.color).bg} ${tone(v.color).text}`}><Icon name={v.icon} size={20} /></span>
                <span className={`text-[11px] font-display font-600 leading-tight text-center ${on ? 'text-brand' : 'text-text-secondary'}`}>{v.label}</span>
                {on && <span className="absolute"></span>}
              </button>
            );
          })}
        </div>

        {/* 3. lokalizacja */}
        <p className="text-[13px] font-display font-700 text-text mt-6 mb-2">Lokalizacja</p>
        <Segmented value={loc} onChange={setLoc} options={[{ value:'wspolna', label:'Część wspólna', icon:'building' }, { value:'lokal', label:'Mój lokal', icon:'home' }]} />
        <input value={loc === 'lokal' ? USER.flat : place} onChange={e => setPlace(e.target.value)} disabled={loc === 'lokal'}
          placeholder={loc === 'lokal' ? '' : 'np. Klatka B2, 3. piętro'}
          className="focusable w-full h-11 px-4 mt-2.5 rounded-md bg-surface border border-border text-[14px] text-text placeholder:text-text-muted disabled:bg-surface-muted disabled:text-text-secondary" />

        {/* 4. opis */}
        <div className="flex items-center justify-between mt-6 mb-2">
          <p className="text-[13px] font-display font-700 text-text">Opis{errDesc && <span className="text-danger font-500"> — opisz problem (min. 5 znaków)</span>}</p>
          <span className="text-[12px] text-text-muted font-mono">{desc.length}/500</span>
        </div>
        <textarea value={desc} maxLength={500} onChange={e => setDesc(e.target.value)} rows={4} placeholder="Co się zepsuło? Gdzie dokładnie? Od kiedy?"
          className={`focusable w-full p-3.5 rounded-md bg-surface border text-[14px] text-text placeholder:text-text-muted resize-none leading-relaxed ${errDesc ? 'border-danger' : 'border-border'}`} />

        {/* 5. priorytet */}
        <p className="text-[13px] font-display font-700 text-text mt-6 mb-2">Priorytet</p>
        <div className="flex gap-2">
          {[['niski','Niski','text-muted'],['sredni','Średni','warning'],['wysoki','Wysoki','danger']].map(([k,l,t]) =>
            <Chip key={k} active={prio===k} tone={t} onClick={()=>setPrio(k)} icon={k==='wysoki'?'alert':null}>{l}</Chip>)}
        </div>
      </div>

      <div className="shrink-0 px-4 pt-3 pb-7 bg-surface/90 backdrop-blur-xl border-t border-border">
        <Btn block size="lg" loading={busy} icon={busy ? null : 'send'} onClick={submit}>Wyślij zgłoszenie</Btn>
      </div>
      {sent && <SuccessOverlay title="Zgłoszenie wysłane" sub="Numer #1252 · powiadomimy Cię o zmianach statusu" />}
    </div>
  );
}

// ════════════════════ USTERKI — LISTA (B4) ════════════════════
function Usterki({ ctx }) {
  const [scope, setScope] = u2('moje');
  const list = FAULTS.filter(f => scope === 'moje' ? f.mine : !f.mine);
  return (
    <div className="flex flex-col h-full bg-bg">
      <header className={`shrink-0 ${TOPPAD} px-4 pb-2 bg-bg/80 backdrop-blur-xl z-20`}>
        <div className="flex items-center gap-1 min-h-[44px] mb-2.5">
          <IconBtn name="arrowLeft" label="Wstecz" onClick={ctx.back} className="-ml-1" />
          <h1 className="font-display font-800 text-text text-[24px] flex-1">Usterki</h1>
          <IconBtn name="mapPin" label="Plan osiedla" onClick={() => ctx.go('plan')} />
          <Btn size="sm" icon="plus" onClick={() => ctx.go('nowa-usterka')}>Zgłoś</Btn>
        </div>
        <Segmented value={scope} onChange={setScope} options={[{ value:'moje', label:'Moje zgłoszenia' }, { value:'wspolne', label:'Część wspólna' }]} />
      </header>
      <div className="flex-1 overflow-auto app-scroll px-4 pt-3 pb-28">
        {list.length === 0
          ? <EmptyState icon="wrench" title="Brak zgłoszeń" action={<Btn size="sm" icon="plus" onClick={() => ctx.go('nowa-usterka')}>Zgłoś usterkę</Btn>}>Nie masz jeszcze żadnych zgłoszeń w tej sekcji.</EmptyState>
          : <div className="space-y-2.5">{list.map(f => <FaultRow key={f.id} f={f} ctx={ctx} />)}</div>}
      </div>
    </div>
  );
}

// ── pionowa oś statusów ──
function Timeline({ f }) {
  const curIdx = FAULT_FLOW.indexOf(f.status);
  return (
    <div className="relative pl-1">
      {FAULT_FLOW.map((step, i) => {
        const st = FAULT_STATUS[step];
        const entry = f.timeline.find(t => t.status === step);
        const reached = i <= curIdx;
        const isCur = i === curIdx;
        const last = i === FAULT_FLOW.length - 1;
        return (
          <div key={step} className="flex gap-3.5 relative">
            {!last && <span className={`absolute left-[11px] top-6 w-0.5 h-[calc(100%-12px)] ${i < curIdx ? 'bg-brand' : 'bg-border'}`} />}
            <div className="shrink-0 relative z-10 mt-0.5">
              <span className={`flex items-center justify-center w-6 h-6 rounded-full ${reached ? 'bg-brand text-brand-fg' : 'bg-surface-muted text-text-muted border border-border'} ${isCur && f.status!=='zamkniete' ? 'anim-pulse' : ''}`}>
                {reached ? <Icon name="check" size={14} stroke={3} /> : <span className="w-1.5 h-1.5 rounded-full bg-current" />}
              </span>
            </div>
            <div className={`pb-5 flex-1 ${reached ? '' : 'opacity-55'}`}>
              <p className={`font-display font-700 text-[14px] ${reached ? 'text-text' : 'text-text-muted'}`}>{st.label}</p>
              {entry ? <>
                <p className="text-[12px] text-text-muted">{entry.date} · {entry.by}</p>
                {entry.note && <p className="text-[13px] text-text-secondary mt-1 bg-surface-muted rounded-md px-3 py-2 leading-snug">{entry.note}</p>}
              </> : <p className="text-[12px] text-text-muted italic">Oczekuje</p>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ════════════════════ USTERKA — SZCZEGÓŁ (B6) ════════════════════
function UsterkaDetail({ ctx, params }) {
  const f = FAULTS.find(x => x.id === params.id);
  const cat = FAULT_CATS[f.cat], st = FAULT_STATUS[f.status];
  const rated = ctx.rating[f.id];
  const [stars, setStars] = u2(0);
  const [rcomment, setRcomment] = u2('');
  const showRate = f.status === 'rozwiazane' && !rated;

  return (
    <div className="flex flex-col h-full bg-bg">
      <AppBar title={`Usterka #${f.id}`} sub={cat.label} onBack={ctx.back} right={<IconBtn name="more" label="Więcej" />} />
      <div className="flex-1 overflow-auto app-scroll px-4 pb-10">
        <div className="pt-3 flex items-center gap-2 flex-wrap">
          <Badge tone={cat.color} icon={cat.icon}>{cat.label}</Badge>
          <Badge tone={st.tone} dot>{st.label}</Badge>
          {f.priority === 'wysoki' && <Badge tone="danger" icon="alert">Priorytet wysoki</Badge>}
        </div>
        <h1 className="font-display font-800 text-text text-[22px] leading-tight mt-3" style={{ textWrap: 'balance' }}>{f.title}</h1>
        <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" />{f.location}</p>

        {f.photos > 0 && <div className="flex gap-2.5 mt-4">{Array.from({length:f.photos}).map((_,i)=><Photo key={i} label={`zdjęcie ${i+1}`} h={110} className="flex-1" />)}</div>}

        <Card className="p-4 mt-4"><p className="text-[14px] text-text leading-relaxed">{f.desc}</p></Card>

        {f.assignee && (
          <div className="flex items-center gap-3 mt-4 p-3.5 rounded-xl bg-brand/8 border border-brand/20">
            <span className="w-10 h-10 rounded-full bg-brand text-brand-fg flex items-center justify-center shrink-0"><Icon name="wrench" size={20} /></span>
            <div><p className="text-[12px] text-text-muted">Przypisany serwis</p><p className="font-display font-700 text-text text-[14px]">{f.assignee}</p></div>
          </div>
        )}

        <h2 className="font-display font-700 text-text text-[16px] mt-6 mb-3">Status zgłoszenia</h2>
        <Card className="p-4"><Timeline f={f} /></Card>

        {f.comments.length > 0 && (<>
          <h2 className="font-display font-700 text-text text-[16px] mt-6 mb-3">Komentarze</h2>
          <div className="space-y-2.5">{f.comments.map((c,i) => (
            <div key={i} className="flex gap-2.5"><Avatar name={c.author} size={34} />
              <div className="flex-1 bg-surface border border-border rounded-xl rounded-tl-sm p-3">
                <div className="flex items-center justify-between"><span className="font-display font-700 text-[13px] text-text">{c.author}</span><span className="text-[11px] text-text-muted">{c.time}</span></div>
                <p className="text-[13px] text-text-secondary mt-1 leading-snug">{c.text}</p>
              </div>
            </div>
          ))}</div>
        </>)}

        {/* ocena */}
        {showRate && (
          <Card className="p-5 mt-6 text-center border-accent-warm/30 bg-accent-warm/8">
            <p className="font-display font-800 text-text text-[16px]">Jak oceniasz obsługę?</p>
            <p className="text-[13px] text-text-secondary mt-1 mb-3">Twoja opinia pomaga ulepszać serwis</p>
            <div className="flex justify-center mb-3"><Stars value={stars} onChange={setStars} /></div>
            <textarea value={rcomment} onChange={e=>setRcomment(e.target.value)} rows={2} placeholder="Komentarz (opcjonalnie)"
              className="focusable w-full p-3 rounded-md bg-surface border border-border text-[13px] text-text placeholder:text-text-muted resize-none mb-3" />
            <Btn block disabled={!stars} onClick={() => { ctx.rate(f.id, stars); ctx.toast({ msg: 'Dziękujemy za ocenę!', icon: 'star' }); }}>Wyślij ocenę</Btn>
          </Card>
        )}
        {rated && (
          <Card className="p-4 mt-6 flex items-center gap-3 anim-pop">
            <span className="w-10 h-10 rounded-full bg-success/15 text-success flex items-center justify-center"><Icon name="checkCircle" size={22} /></span>
            <div className="flex-1"><p className="font-display font-700 text-text text-[14px]">Oceniono zgłoszenie</p><div className="flex gap-0.5 mt-0.5 text-accent-warm">{Array.from({length:5}).map((_,i)=><Icon key={i} name="star" size={15} fill={i<rated} className={i<rated?'':'text-border'} stroke={1.6} />)}</div></div>
          </Card>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { NowaUsterka, Usterki, Timeline, UsterkaDetail });
